while_loop错误Tensorflow
我试图在使用while_loop Tensorflow,但是当我尝试从while循环调用返回的目标输出,因为形状每次增加它给了我一个错误。while_loop错误Tensorflow
输出应该包含基于数据值(输入数组)的值(0或1)值。如果数据的值大于5返回否则返回。返回的值必须加入到输出
这是代码::
import numpy as np
import tensorflow as tf
data = np.random.randint(10, size=(30))
data = tf.constant(data, dtype= tf.float32)
global output
output= tf.constant([], dtype= tf.float32)
i = tf.constant(0)
c = lambda i: tf.less(i, 30)
def b(i):
i= tf.add(i,1)
cond= tf.cond(tf.greater(data[i-1], tf.constant(5.)), lambda: tf.constant(1.0), lambda: tf.constant([0.0]))
output =tf.expand_dims(cond, axis = i-1)
return i, output
r,out = tf.while_loop(c, b, [i])
print(out)
sess= tf.Session()
sess.run(out)
错误::
r, out = tf.while_loop(c, b, [i])
ValueError: The two structures don't have the same number of elements.
First structure (1 elements): [tf.Tensor 'while/Identity:0' shape=() dtype=int32]
Second structure (2 elements): [tf.Tensor 'while/Add:0' shape=() dtype=int32, tf.Tensor 'while/ExpandDims:0' shape=unknown dtype=float32>]
我用tensorflow-1.1.3和蟒蛇-3.5
如何更改我的代码t o给我的目标结果?
编辑::
我编辑的代码基于@mrry的答案,但我仍然有一个问题,输出是不正确的答案 输出数字总和
a = tf.ones([10,4])
print(a)
a = tf.reduce_sum(a, axis = 1)
i =tf.constant(0)
c = lambda i, _:tf.less(i,10)
def Smooth(x):
return tf.add(x,2)
summ = tf.constant(0.)
def b(i,_):
global summ
summ = tf.add(summ, tf.cast(Smooth(a[i]), tf.float32))
i= tf.add(i,1)
return i, summ
r, smooth_l1 = tf.while_loop(c, b, [i, smooth_l1])
print(smooth_l1)
sess = tf.Session()
print(sess.run(smooth_l1))
的出把是6.0(错误)。
的tf.while_loop()
功能需要以下四个列表具有相同的长度,以及相同类型的每个元素:
- 的参数传递给
cond
函数(c
在这种情况下)的列表。 - 函数参数列表
body
函数(在这种情况下为b
)。 - 函数返回值列表
body
函数。 - 表示循环变量的
loop_vars
的列表。
因此,如果您的循环体有两个输出,你必须向b
和c
,以及相应的元素添加相应的参数,以loop_vars
:
c = lambda i, _: tf.less(i, 30)
def b(i, _):
i = tf.add(i, 1)
cond = tf.cond(tf.greater(data[i-1], tf.constant(5.)),
lambda: tf.constant(1.0),
lambda: tf.constant([0.0]))
# NOTE: This line fails with a shape error, because the output of `cond` has
# a rank of either 0 or 1, but axis may be as large as 28.
output = tf.expand_dims(cond, axis=i-1)
return i, output
# NOTE: Use a shapeless `tf.placeholder_with_default()` because the shape
# of the output will vary from one iteration to the next.
r, out = tf.while_loop(c, b, [i, tf.placeholder_with_default(0., None)])
正如评论指出,身体的该循环(特别是tf.expand_dims()
的调用)似乎不正确,并且该程序不会按原样运行,但希望这足以让您开始。
感谢您的回答,我编辑代码以使输出成为数字求和的结果。我没有语法错误,但输出不是正确的答案。我不知道为什么会发生。我将根据你的回答在这里编辑我的问题 – CCCC
你的代码的期望答案是什么? 'global summ'忽略第二个主体参数是可疑的:你可能想要传递'0'作为第二个循环变量的初始值,并且使用第二个主体参数而不是'global summ'作为累加器。 – mrry