TensorArray和while_loop如何在tensorflow中协同工作?

E.A*_*ari 8 python tensorflow

我正在尝试为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())
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

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

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

sir*_*rfz 10

您的代码中有几点需要指出.首先,您不需要将矩阵取消堆叠到TensorArray循环中使用它,您可以安全地引用Tensor正文中的矩阵并使用matrix[i]符号对其进行索引.另一个问题是你的矩阵(tf.int32)和TensorArray(tf.float32)之间的数据类型不同,根据你的代码,你将矩阵整数乘以2并将结果写入数组,因此它也应该是int32.最后,当您希望读取循环的最终结果时,正确的操作就是TensorArray.stack()您需要在session.run调用中运行的操作.

这是一个有效的例子:

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)}) 
Run Code Online (Sandbox Code Playgroud)