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

标签 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>]

我想每次都返回子张量

最佳答案

您的代码存在几个问题:

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

  • 通过tf.while_loop编辑的张量应该具有固定的形状。如果您想构建一个循环来收集切片,那么您应该首先使用适当的形状初始化张量 res 以包含所有切片值,例如res = tf.zeros([结果, 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]]]

关于python - 使用 tf.while_loop 对张量进行切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51686340/

相关文章:

python遍历列表列表

Python:在一个正则表达式中多次使用同名捕获组

python - 当 QListWidget 索引更改时更新嵌套的 QStackWidget

python - 将时间列添加到基于另一个 DataFrame 的 DataFrame

python - Django 应用程序的入口点,它只是一个需要访问模型的 redis 订阅循环 - 没有 urls/views

python - Tensorflow 的开端——类的数量

Python:用读入文件替换字符错误

javascript - 在 Javascript 中通过多个 if 语句运行 While 循环

tensorflow - 如何检查Bazel版本?

python - TensorFlow:使用 tf.merge_all_summaries() 时出现 PlaceHolder 错误