Tensorflow中的while_循环错误
我尝试在Tensorflow中使用while\u loop,但当我尝试从while-in-callable循环返回目标输出时,它会给我一个错误,因为形状每次都会增加 输出应包含基于数据值(输入数组)的(0或1)个值。如果数据值大于5,则返回1否则返回0。返回值必须添加到输出中 这是代码::Tensorflow中的while_循环错误,tensorflow,while-loop,python-3.5,Tensorflow,While Loop,Python 3.5,我尝试在Tensorflow中使用while\u loop,但当我尝试从while-in-callable循环返回目标输出时,它会给我一个错误,因为形状每次都会增加 输出应包含基于数据值(输入数组)的(0或1)个值。如果数据值大于5,则返回1否则返回0。返回值必须添加到输出中 这是代码:: import numpy as np import tensorflow as tf data = np.random.randint(10, size=(30)) data = tf.constant(d
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_循环(c,b,[i])
ValueError:这两个结构的元素数不相同
第一个结构(1个元素):[tf.Tensor'while/Identity:0'shape=()
dtype=int32]
第二个结构(2个元素):[tf.Tensor'while/Add:0'shape=()
dtype=int32,tf.Tensor'while/ExpandDims:0'形状=未知
dtype=float32>]
我使用了tensorflow-1.1.3和python-3.5
如何更改代码以获得目标结果
编辑::
我根据@mrry answer编辑代码,但我仍然存在一个问题,即输出的答案不正确
输出是数字总和
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(错误) 该函数要求以下四个列表的长度相同,每个元素的类型相同:
函数的参数列表(本例中为cond
)c
函数的参数列表(本例中为body
)b
函数体的返回值列表
- 表示循环变量的
循环变量的列表
b
和c
添加相应的参数,并向loop\u 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()
)的调用似乎不正确,该程序无法正常工作,但希望这足以让您开始使用。感谢您的回答,我编辑了代码,使输出成为数字求和的结果。我没有得到语法错误,但是输出不是正确的答案。我不知道为什么会这样。我将根据您的答案编辑我的问题。您的代码的预期答案是什么?global sum
和忽略第二个body参数是可疑的:您可能希望传递0.
作为第二个循环变量的初始值,并使用第二个body参数而不是global sum
作为累加器。