我尝试执行以下操作时遇到了以上错误
import tensorflow as tf
import numpy as np
i = tf.constant(0)
a = tf.constant(1, shape = [1], dtype = np.float32)
def che(i, a):
return tf.less(i, 10)
def ce(i, a):
a = tf.concat([a, tf.constant(2, shape = [1], dtype = np.float32)], axis = -1)
i = tf.add(i, 1)
return i, a
c, p = tf.while_loop(che, ce, loop_vars = [i, a], shape_invariants = [tf.shape(i), tf.shape(a)])
我在this页上找到了一些解释,但是不明白如何使用它来解决我的问题。
这是完整的错误日志:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/IPython/core/interactiveshell.py", line 2882, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-28-22be4921aa6d>", line 9, in <module>
c, p = tf.while_loop(che, ce, loop_vars = [i, a], shape_invariants = [tf.shape(i), tf.shape(a)])
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/control_flow_ops.py", line 3291, in while_loop
return_same_structure)
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/control_flow_ops.py", line 3004, in BuildLoop
pred, body, original_loop_vars, loop_vars, shape_invariants)
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/control_flow_ops.py", line 2908, in _BuildLoop
_SetShapeInvariants(real_vars, enter_vars, shape_invariants)
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/control_flow_ops.py", line 555, in _SetShapeInvariants
raise ValueError("`shapes` must be a (possibly nested) list of shapes.")
ValueError: `shapes` must be a (possibly nested) list of shapes.
答案 0 :(得分:1)
首先,shape_invariants
需要TensorShape
而不是Tensor
。因此,通常您需要使用get_shape()
而不是tf.shape()
。
第二,您的a
是一个张量,其长度在不断变化。因此,您应该使用None
来指定形状。
import tensorflow as tf
import numpy as np
i = tf.constant(0)
a = tf.constant(1, shape = [1], dtype = np.float32)
def che(i, a):
return tf.less(i, 10)
def ce(i, a):
a = tf.concat([a, tf.constant(2, shape = [1], dtype = np.float32)], axis = -1)
i = tf.add(i, 1)
return i, a
c, p = tf.while_loop(che, ce, loop_vars = [i, a], shape_invariants = [i.get_shape(), tf.TensorShape([None,])])
with tf.Session() as sess:
print(sess.run(p))
[1. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2.]