Skip to main content
 首页 » 编程设计

python之如何使用 strided_slice 选择 tensorflow 中的所有元素

2024年10月01日34artech

我阅读了文档中的示例:

# '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]] 

我能做什么?

请您参考如下方法:

我无法理解您的问题,但这是我尝试回答的问题:

您可以使用 x[:, :, :] 语法来选择数组的所有元素:

sess = tf.Session() 
inp = tf.constant([[[1, 1, 1], [2, 2, 2]], 
                   [[3, 3, 3], [4, 4, 4]], 
                   [[5, 5, 5], [6, 6, 6]]]) 
print(inp.shape) 
 
x = inp[:, :, :] 
print(sess.run(x)) 

要获得您想要的最后输出,当然可以通过一些手动尺寸计算:

sess = tf.Session() 
x = tf.constant([[1,2,3], 
                 [3,4,5], 
                 [7,8,9]]) 
y = tf.shape(x) 
bounds = tf.concat([y[:-1], [-1]], axis=0) 
out = tf.strided_slice(x, [0,0], bounds, [1,1]) 
print(sess.run(out)) 

一般来说,Tensorflow 切片语法遵循 numpy 的切片语法,记录在此处: https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html

希望对您有所帮助!