ValueError:`shapes`必须是形状列表(可能是嵌套的)

2024-04-18 12:18:46 发布

您现在位置:Python中文网/ 问答频道 /正文

当我试图做下面的事情时,我得到了上面的错误

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.

Tags: inpylooplibpackagesusrdisttf
1条回答
网友
1楼 · 发布于 2024-04-18 12:18:46

首先,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.]

相关问题 更多 >