Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tf.shape() get wrong shape in tensorflow

I define a tensor like this:

x = tf.get_variable("x", [100])

But when I try to print shape of tensor :

print( tf.shape(x) )

I get Tensor("Shape:0", shape=(1,), dtype=int32), why the result of output should not be shape=(100)

like image 979
Nils Cao Avatar asked May 07 '16 06:05

Nils Cao


People also ask

How does TF reshape work?

The tf. reshape does not change the order of or the total number of elements in the tensor, and so it can reuse the underlying data buffer. This makes it a fast operation independent of how big of a tensor it is operating on. To instead reorder the data to rearrange the dimensions of a tensor, see tf.

What does shape mean in TensorFlow?

The shape of a tensor is the number of elements in each dimension. TensorFlow automatically infers shapes during graph construction. These inferred shapes might have known or unknown rank. If the rank is known, the sizes of each dimension might be known or unknown.


2 Answers

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/

like image 141
nessuno Avatar answered Sep 18 '22 01:09

nessuno


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.

like image 36
Lazar Valkov Avatar answered Sep 20 '22 01:09

Lazar Valkov