我尝试在Tensorflow中使用while_loop,但是当我试图从time循环中返回可调用的目标输出时,它会给出一个错误,因为形状每次都会增加。
输出应该包含(0或1)基于数据值(输入数组)的值。如果数据值大于5,则返回1或返回。返回的值必须添加到输出中。
这是守则:
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:这两个结构没有相同数量的元素。 第一个结构(1个元素):tf.Tensor 'while/Identity:0‘shape=() dtype=int32 第二个结构(2个元素):tf.Tensor 'while/Add:0‘shape=() dtype=int32,tf.Tensor 'while/ExpandDims:0’shape=unknown dtype=float32>
我使用tensorflow-1.1.3和python-3.5
如何更改代码以给出目标结果?
编辑::
我根据@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 (错误)。
发布于 2017-10-16 14:50:51
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()的调用)似乎是不正确的,这个程序将无法按原样工作,但希望这足以让您开始工作。
发布于 2022-11-06 10:08:06
如果您看到这个错误: ValueError:这两个结构没有相同数量的元素。
如果您在while_loop中看到它,这意味着您的输入和输出在while循环中有不同的形状。
我通过确保从while循环函数返回相同的loop_vars结构来解决这个问题,条件函数也必须接受相同的循环vars。
下面是一个示例代码
loop_vars = [i, loss, batch_size, smaller_str_lens]
def condition(*loop_vars):
i = loop_vars[0]
batch_size = loop_vars[2]
return tf.less(i, batch_size)
def body(*loop_vars):
i, loss, batch_size, smaller_str_lens = loop_vars
tf.print("The loop passed here")
## logic here
i = tf.add(i, 1)
return i, loss, batch_size, smaller_str_lens
loss = tf.while_loop(condition, compare_strings, loop_vars)[1]主体函数必须返回循环vars,条件函数必须接受循环vars。
https://stackoverflow.com/questions/46768386
复制相似问题