使用 tf.while_loop 对张量进行切片

Posted

技术标签:

【中文标题】使用 tf.while_loop 对张量进行切片【英文标题】:Slice tensor using tf.while_loop 【发布时间】:2019-01-12 03:45:42 【问题描述】:

只要还有一些列使用tf.while_loop,我就会尝试将张量切成小块。 注意:我使用这种方式是因为我无法在图形构建时(没有会话)循环占位符中的值,该值被视为张量而不是整数。

[ 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】:

你的代码有几个问题:

您没有传递任何结构/张量来接收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]]]

【讨论】:

您好,在 n =5.. 的情况下,是否有自动化的过程,不仅是成对的。谢谢 只需进一步生成 idx_col2, ... idx_coln 并将它们堆叠在一起,就像我的代码中所做的那样。我更新了我的答案(未经测试),展示了如何通过列表理解来完成。

以上是关于使用 tf.while_loop 对张量进行切片的主要内容,如果未能解决你的问题,请参考以下文章

在 Tensorflow 中使用索引对张量进行切片

Keras:如何使用来自另一个张量的信息对张量进行切片?

计算 tf.while_loop 的每个时间步长的梯度

tf.while_loop

没有为任何变量提供渐变来增加tf.while_loop中的Loss值

11 tensorflow在tf.while_loop循环(非一般循环)中使用操纵变量该怎么做