TensorArray 和 while_loop 如何在 tensorflow 中协同工作? [英] How TensorArray and while_loop work together in tensorflow?

查看:27
本文介绍了TensorArray 和 while_loop 如何在 tensorflow 中协同工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to produce a very easy example for combination of TensorArray and 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).

有人知道这是什么问题吗?

Anyone has on idea what is the problem?

推荐答案

您的代码中有几件事情需要指出.首先,您不需要将矩阵解压到 TensorArray 中以在循环内使用它,您可以安全地引用主体内的矩阵 Tensor 并使用 matrix[i] 符号.另一个问题是您的矩阵 (tf.int32) 和 TensorArray (tf.float32) 之间的不同数据类型,基于您的代码'将矩阵整数乘以 2 并将结果写入数组,因此它也应该是 int32.最后,当您希望读取循环的最终结果时,正确的操作是 TensorArray.stack(),这是您需要在 session.run 调用中运行的操作.

There are several things in your code to point out. First, you don't need to unstack the matrix into the TensorArray to use it inside the loop, you can safely reference the matrix Tensor inside the body and index it using matrix[i] notation. Another issue is the different data type between your matrix (tf.int32) and the TensorArray (tf.float32), based on your code you're multiplying the matrix ints by 2 and writing the result into the array so it should be int32 as well. Finally, when you wish to read the final result of the loop, the correct operation is TensorArray.stack() which is what you need to run in your 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)}) 

这篇关于TensorArray 和 while_loop 如何在 tensorflow 中协同工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆