In the previous article, we learnt about the Tensors and tensor dtypes. In this post we will learn about the tensor shapes.
A TensorShape represents a possibly-partial shape specification for a tensor. It may be one of the following.
Tensor with a Fully-known shape has a known number of dimensions and a known size for each dimension.
e.g TensorShape([2, 4])
import tensorflow as tf
t1 = tf.constant([[1,2,3,4], [5,6,7,8]])
t1.shape
Tensor with a Fully-known shape has a known number of dimensions and a unknown size for one or more dimension.
e.g TensorShape([4, None])
import tensorflow as tf
sample_list = [[1], [2,3], [4,5], [1,2,3,4]]
t1 = tf.ragged.constant(sample_list)
t1.shape
Tensor with a Unknown shape has an unknown number of dimensions and an unknown size in all dimensions.
e.g TensorShape([None])
import tensorflow as tf
t1 = tf.RaggedTensorSpec(shape=(None,))
t1.shape
Tensor Shape represents the length of the each of the axes of tensor.
import tensorflow as tf
t1 = tf.constant([[[1,2,3,4],[2,3,5,4],[6,7,8,4]]])
print(t1.shape)
print("Length of axis 0 of tensor t1:", t1.shape[0])
print("Length of axis 2 of tensor t1:", t1.shape[1])
print("Length of last axis of tensor t1:", t1.shape[-1])
Tensor Rank represents number of axes in tensor.
import tensorflow as tf
t1 = tf.constant([[[1,2,3,4],[2,3,5,4],[6,7,8,4]]])
t1._rank()
Scalar: A scalar is a rank-0 tensor and it has no axes.
import tensorflow as tf
t1 = tf.constant(9)
t1._rank()
Vector: A vector is a rank-1 tensor and it has one axis.
import tensorflow as tf
t1 = tf.constant([1,3,4])
t1._rank()
Matrix: A matrix is a rank-2 tensor and it has two axes.
import tensorflow as tf
t1 = tf.constant([[1,3,4], [4,5,6]])
t1._rank()
Tensor Size represents the total number of items in the tensor, that is the product of the shape vector's elements.
import tensorflow as tf
t1 = tf.constant([[1,3,4], [4,5,6], [3,5,6]])
print("Shape of tensor t1 : ", t1.shape)
print("Size of tensor t1 : ", tf.size(t1).numpy())