How to get the dimensions of a tensor (in TensorFlow) at graph construction time?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to get the dimensions of a tensor (in TensorFlow) at graph construction time in Python. So Here I am Explain to you all the possible Methods here.

How to get the dimensions of a tensor (in TensorFlow) at graph construction time?

1. How to get the dimensions of a tensor (in TensorFlow) at graph construction time?

tensor.get_shape is used for fixed shapes, which means the tensor's shape can be deduced in the graph.

2. get the dimensions of a tensor (in TensorFlow) at graph construction time

tensor.get_shape is used for fixed shapes, which means the tensor's shape can be deduced in the graph.

Method 1

I see most people confused about tf.shape(tensor) and tensor.get_shape() Let’s make it clear:

1. tf.shape

tf.shape is used for dynamic shape. If your tensor’s shape is changable, use it. An example: a input is an image with changable width and height, we want resize it to half of its size, then we can write something like:
new_height = tf.shape(image) / 2

1. tensor.get_shape

tensor.get_shape is used for fixed shapes, which means the tensor’s shape can be deduced in the graph.

Conclusion: tf.shape can be used almost anywhere, but t.get_shape only for shapes can be deduced from graph.

Method 2

A function to access the values:

def shape(tensor):
s = tensor.get_shape()
return tuple([s[i].value for i in range(0, len(s))])

Example:

batch_size, num_feats = shape(logits)

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.