使用tf.while_loop切片张量

时间:2018-08-04 14:00:41

标签: python loops tensorflow slice tensor

我正在尝试将张量切成小张,只要还有一些使用tf.while_loop的列即可。
注意:之所以使用这种方式,是因为在图构造时(没有session)我无法在占位符上循环一个值,而该值被视为张量而不是整数。

[ 5 7 8 ]      
[ 7 4 1 ]  =>  
[5 7 ]     [ 7 8 ]  
[7 4 ]     [ 4 1 ]

这是我的代码:

i = tf.constant(0)

result = tf.subtract(tf.shape(f)[1],1)

c = lambda result : tf.greater(result, 0)

b = lambda i: [i+1, tf.slice(x, [0,i],[2, 3])] 

o= tf.while_loop(c, b,[i])

with tf.Session() as sess: 

   print (sess.run(o))

但是,出现此错误:

 ValueError: The two structures don't have the same nested structure.

 First structure: type=list str=[<tf.Tensor 'while_2/Identity:0' shape=()                     dtype=int32>]
 Second structure: type=list str=[<tf.Tensor 'while_2/add:0' shape=()     dtype=int32>, <tf.Tensor 'while_2/Slice:0' shape=(2, 3) dtype=int32>]

我想每次返回次张量

1 个答案:

答案 0 :(得分:1)

您的代码有几个问题:

  • 您没有传递任何结构/张量来接收tf.slice(...)的值。您的lambda b应该具有lambda i, res : i+1, ...

  • 之类的签名。 通过tf.while_loop编辑的
  • 张量应具有固定的形状。如果要构建一个循环以收集切片,则应首先使用适当的形状初始化张量res以包含所有切片值,例如res = tf.zeros([result, 2, 2])


注意:对于您的特定应用程序(收集所有成对的相邻列),可以在没有tf.while_loop的情况下完成:

import tensorflow as tf

x = tf.convert_to_tensor([[ 5, 7, 8, 9 ],
                          [ 7, 4, 1, 0 ]])
num_rows, num_cols = tf.shape(x)[0], tf.shape(x)[1]

# Building tuples of neighbor column indices:
n = 2 # or 5 cf. comment
idx_neighbor_cols = [tf.range(i, num_cols - n + i) for i in range(n)]
idx_neighbor_cols = tf.stack(idx_neighbor_cols, axis=-1)

# Finally gathering the column pairs accordingly:
res = tf.transpose(tf.gather(x, idx_neighbor_cols, axis=1), [1, 0, 2])

with tf.Session() as sess:
    print(sess.run(res))
    # [[[5 7]
    #   [7 4]]
    #  [[7 8]
    #   [4 1]]
    #  [[8 9]
    #   [1 0]]]
相关问题