TensorArray 和 while_loop 在张量流中如何协同工作?

2023-11-26

我正在尝试为 TensorArray 和 while_loop 的组合生成一个非常简单的示例:

# 1000 sequence in the length of 100
matrix = tf.placeholder(tf.int32, shape=(100, 1000), name="input_matrix")
matrix_rows = tf.shape(matrix)[0]
ta = tf.TensorArray(tf.float32, size=matrix_rows)
ta = ta.unstack(matrix)

init_state = (0, ta)
condition = lambda i, _: i < n
body = lambda i, ta: (i + 1, ta.write(i,ta.read(i)*2))

# run the graph
with tf.Session() as sess:
    (n, ta_final) = sess.run(tf.while_loop(condition, body, init_state),feed_dict={matrix: tf.ones(tf.float32, shape=(100,1000))})
    print (ta_final.stack())

但我收到以下错误:

ValueError: Tensor("while/LoopCond:0", shape=(), dtype=bool) must be from the same graph as Tensor("Merge:0", shape=(), dtype=float32).

任何人都知道问题是什么?


您的代码中有几件事需要指出。首先,您不需要将矩阵拆入TensorArray要在循环内使用它,您可以安全地引用矩阵Tensor在体内并使用索引它matrix[i]符号。另一个问题是矩阵之间的不同数据类型(tf.int32)和TensorArray (tf.float32),根据您的代码,您将矩阵 int 乘以 2 并将结果写入数组,因此它也应该是 int32 。最后,当你想读取循环的最终结果时,正确的操作是TensorArray.stack()这就是你需要在你的session.run call.

这是一个工作示例:

import numpy as np
import tensorflow as tf    

# 1000 sequence in the length of 100
matrix = tf.placeholder(tf.int32, shape=(100, 1000), name="input_matrix")
matrix_rows = tf.shape(matrix)[0]
ta = tf.TensorArray(dtype=tf.int32, size=matrix_rows)

init_state = (0, ta)
condition = lambda i, _: i < matrix_rows
body = lambda i, ta: (i + 1, ta.write(i, matrix[i] * 2))
n, ta_final = tf.while_loop(condition, body, init_state)
# get the final result
ta_final_result = ta_final.stack()

# run the graph
with tf.Session() as sess:
    # print the output of ta_final_result
    print sess.run(ta_final_result, feed_dict={matrix: np.ones(shape=(100,1000), dtype=np.int32)}) 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

TensorArray 和 while_loop 在张量流中如何协同工作? 的相关文章

随机推荐