user10024395
user10024395

Reputation: 1

Why Tensorflow complains when shape is specified with round bracket but do not when it is specified with square bracket?

When I specify tf.random_normal([1]), it works fine but when I specify tf.random_normal((1)), I get

ValueError: Shape must be rank 1 but is rank 0 for 'random_normal_24/RandomStandardNormal' (op: 'RandomStandardNormal') with input shapes: [].

This behavior applies to many functions that requires shape to be inputed in Tensorflow.

Is this normal? Or is it a bug? Many tutorials and books use round bracket but it seems to be that square bracket should be the right way based on the behavior.

Upvotes: 1

Views: 1020

Answers (2)

nessuno
nessuno

Reputation: 27042

In python, a tuple with a single element is a scalar. Hence (1) == 1.

If you want to explicitly create a tuple that contains a single element, you have to use the syntax: (1,).

Instead, in python, you can create a list with a single element using the square brackets: [1] != 1.

However, when you define shapes, you should prefer the usage of the tuple instead of the list, because in python the creation of a tuple is way more efficient than the creation of an array (a tuple is an immutable object while a list is not. Hence the python interpreter can do a lot of optimizations like constant folding, and moving the object around, while the list have to be copied).

Upvotes: 3

Siyuan Ren
Siyuan Ren

Reputation: 7844

It is not a TensorFlow-specific issue. In Python, (1) is the same as 1. You need an ugly syntax (1,) to specify an one-element tuple.

Upvotes: 1

Related Questions