You can also add dimensions to your tensor whilst keeping the same information present using tf.newaxis.
# Create a rank 2 tensor (2 dimensions)
rank_2_tensor = tf.constant([[10, 7],
[3, 4]])
print("dimension: ", rank_2_tensor.ndim)
print("shape : ", rank_2_tensor.shape)
output:
dimension: 2
shape: TensorShape([2, 2])
# Add an extra dimension (to the end)
rank_3_tensor = rank_2_tensor[..., tf.newaxis]
# in Python "..." means "all dimensions prior to"
print("dimension: ", rank_3_tensor .ndim)
print("shape : ", rank_3_tensor .shape)
output:
dimension: 3
shape: TensorShape([2, 2, 1])
You can achieve the same using tf.expand_dims().
rank_new_3_tensor = tf.expand_dims(rank_2_tensor, axis=-1) # "-1" means last axis
print("dimension: ", rank_new_3_tensor .ndim)
print("shape : ", rank_new_3_tensor .shape)
output:
dimension: 3
shape: TensorShape([2, 2, 1])