如何使用strided_slice选择张量流中的所有元素?

时间:2017-05-07 04:23:41

标签: python tensorflow

我阅读了文档中的示例:

# 'input' is [[[1, 1, 1], [2, 2, 2]],
#             [[3, 3, 3], [4, 4, 4]],
#             [[5, 5, 5], [6, 6, 6]]]
tf.strided_slice(input, [1, 0, 0], [2, 1, 3], [1, 1, 1]) ==> [[[3, 3, 3]]]
tf.strided_slice(input, [1, 0, 0], [2, 2, 3], [1, 1, 1]) ==> [[[3, 3, 3],
                                                               [4, 4, 4]]]
tf.strided_slice(input, [1, -1, 0], [2, -3, 3], [1, -1, 1]) ==>[[[4, 4, 4],
                                                                 [3, 3, 3]]] 

似乎我不能简单地使用input[:,:]来选择所有元素,而是必须使用input[:-1, :-1]之类的语法。但是以这种方式input[:-1, :-1],我将错过最后一行或最后一列。我该怎么办?

我举个例子:

ph = tf.placeholder(shape=[None, 3], dtype=tf.int32)
x = tf.strided_slice(ph, [0,0],[-1,-1],[1,1])
input_ = np.array([[1,2,3],
                  [3,4,5],
                  [7,8,9]])
sess = tf.InteractiveSession()
sess.run(x,feed_dict={ph:input_})

输出:

array([[1, 2],
       [3, 4]])

我阅读了很多材料,发现我可以使用tf.shape(ph),让我们看看:

ph = tf.placeholder(shape=[None, 3], dtype=tf.int32)
x = tf.strided_slice(ph, [0,0],tf.shape(ph),[1,1])
input_ = np.array([[1,2,3],
                  [3,4,5],
                  [7,8,9]])
sess = tf.InteractiveSession()
sess.run(x,feed_dict={ph:input_})

出:

array([[1, 2, 3],
       [3, 4, 5],
       [7, 8, 9]])

但是,如果我想得到这样的结果:

[[1, 2],
 [3, 4],
 [7, 8]]

我该怎么办?

1 个答案:

答案 0 :(得分:0)

以下内容也适用:

ph = tf.placeholder(shape=[None, 3], dtype=tf.int32)
x = tf.strided_slice(ph, [0,0],[tf.shape(ph)[0],-1],[1,1])
input_ = np.array([[1,2,3],
                  [3,4,5],
                  [7,8,9]])
sess = tf.InteractiveSession()
sess.run(x,feed_dict={ph:input_})

http://imgur.com/ho3kj5Q

上的ipython notebook截图