【问题标题】:How TensorArray and while_loop work together in tensorflow?TensorArray 和 while_loop 如何在 tensorflow 中协同工作?
【发布时间】:2018-02-03 08:20:03
【问题描述】:

我正在尝试为 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,你需要session.run(ta.stack()),而不是直接运行循环,因为你不能session.run(TensorArray)
  • 对不起,我没明白你的意思。请写出正确的表格好吗?

标签: python tensorflow


【解决方案1】:

您的代码中有几处需要指出。首先,您无需将矩阵解栈到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)}) 

【讨论】:

  • 在此我可以在不使用 feed 字典的情况下指定输入,就像我在计算图之间使用它一样,我将如何指定张量数组取决于某个张量?
  • @Rahul matrix 可以是任何类型的Tensor,如果我理解你的问题,不一定是placeholder
  • 在最后一行中,我将np.ones(tf.int32, shape=(100,1000)) 更改为np.ones(dtype=np.int32, shape=(100,1000)) 以便能够在python 3 上运行此代码。
猜你喜欢
  • 2017-05-07
  • 2016-09-02
  • 1970-01-01
  • 2018-01-16
  • 2015-08-17
  • 2021-12-09
  • 2019-04-21
  • 2014-08-05
  • 2020-01-14
相关资源
最近更新 更多