tf.shape() get wrong shape in tensorflow

Solution 1:

tf.shape(input, name=None) returns a 1-D integer tensor representing the shape of input.

You're looking for: x.get_shape() that returns the TensorShape of the x variable.

Update: I wrote an article to clarify the dynamic/static shapes in Tensorflow because of this answer: https://pgaleone.eu/tensorflow/2018/07/28/understanding-tensorflow-tensors-shape-static-dynamic/

Solution 2:

Clarification:

tf.shape(x) creates an op and returns an object which stands for the output of the constructed op, which is what you are printing currently. To get the shape, run the operation in a session:

matA = tf.constant([[7, 8], [9, 10]])
shapeOp = tf.shape(matA) 
print(shapeOp) #Tensor("Shape:0", shape=(2,), dtype=int32)
with tf.Session() as sess:
   print(sess.run(shapeOp)) #[2 2]

credit: After looking at the above answer, I saw the answer to tf.rank function in Tensorflow which I found more helpful and I have tried rephrasing it here.

Solution 3:

Just a quick example, to make things clear:

a = tf.Variable(tf.zeros(shape=(2, 3, 4)))
print('-'*60)
print("v1", tf.shape(a))
print('-'*60)
print("v2", a.get_shape())
print('-'*60)
with tf.Session() as sess:
    print("v3", sess.run(tf.shape(a)))
print('-'*60)
print("v4",a.shape)

Output will be:

------------------------------------------------------------
v1 Tensor("Shape:0", shape=(3,), dtype=int32)
------------------------------------------------------------
v2 (2, 3, 4)
------------------------------------------------------------
v3 [2 3 4]
------------------------------------------------------------
v4 (2, 3, 4)

Also this should be helpful: How to understand static shape and dynamic shape in TensorFlow?