Anubhav Pandey
Anubhav Pandey

Reputation: 1295

ValueError: `shapes` must be a (possibly nested) list of shapes

I got the above error when I was trying to do the following

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)])

I found a bit of an explanation on this page, but couldn't understand how it can be used to solve my problem.
Here's the complete error log:

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.

Upvotes: 1

Views: 235

Answers (1)

giser_yugang
giser_yugang

Reputation: 6166

First, shape_invariants needs TensorShape instead of Tensor. So in general you need to use get_shape() instead of tf.shape().

Second, your a is a tensor whose length is constantly changing. So you should use None to specified the shape.

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.]

Upvotes: 2

Related Questions