import tensorflow as tf
array = tf.Variable(tf.random_normal([10]))
i = tf.constant(0)
l = []
def cond(i,l):
return i < 10
def body(i,l):
temp = tf.gather(array,i)
l.append(temp)
return i+1,l
index,list_vals = tf.while_loop(cond, body, [i,l])
我想以上述代码中描述的类似方式处理张量数组。在while循环的主体中,我想逐个元素地处理数组以应用一些函数。为了演示,我给出了一个小代码片段。但是,它给出了如下错误消息。
ValueError: Number of inputs and outputs of body must match loop_vars: 1, 2
对解决此问题的任何帮助表示赞赏。
谢谢
最佳答案
引用文档:
loop_vars
is a (possibly nested) tuple, namedtuple or list of tensors that is passed to bothcond
andbody
您不能将常规 python 数组作为张量传递。你可以做的是:
i = tf.constant(0)
l = tf.Variable([])
def body(i, l):
temp = tf.gather(array,i)
l = tf.concat([l, [temp]], 0)
return i+1, l
index, list_vals = tf.while_loop(cond, body, [i, l],
shape_invariants=[i.get_shape(),
tf.TensorShape([None])])
形状不变量在那里,因为通常
tf.while_loop
预计 while 循环内张量的形状不会改变。sess = tf.Session()
sess.run(tf.global_variables_initializer())
sess.run(list_vals)
Out: array([-0.38367489, -1.76104736, 0.26266089, -2.74720812, 1.48196387,
-0.23357525, -1.07429159, -1.79547787, -0.74316853, 0.15982138],
dtype=float32)
关于python-2.7 - Tensorflow while 循环 : dealing with lists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41233462/