Shape of tensor

Shape of tensor

When you print the tensor, TensorFlow guesses the shape. However, you can get the shape of the tensor with the shape property.

Below, you construct a matrix filled with a number from 10 to 15 and you check the shape of m_shape

# Shape of tensor
m_shape = tf.constant([ [10, 11],
                        [12, 13],
                        [14, 15] ]                      
                     ) 
m_shape.shape                                   

Output

TensorShape([Dimension(3), Dimension(2)])                                            

The matrix has 3 rows and 2 columns.

TensorFlow has useful commands to create a vector or a matrix filled with 0 or 1. For instance, if you want to create a 1-D tensor with a specific shape of 10, filled with 0, you can run the code below:

# Create a vector of 0
print(tf.zeros(10))                                             

Output

Tensor("zeros:0", shape=(10,), dtype=float32)                                           

The property works for matrix as well. Here, you create a 10×10 matrix filled with 1

# Create a vector of 1
print(tf.ones([10, 10]))                                     

Output

Tensor("ones:0", shape=(10, 10), dtype=float32)                                      

You can use the shape of a given matrix to make a vector of ones. The matrix m_shape is a 3×2 dimensions. You can create a tensor with 3 rows filled by one’s with the following code:

# Create a vector of ones with the same number of rows as m_shape
print(tf.ones(m_shape.shape[0]))                                  

Output

Tensor("ones_1:0", shape=(3,), dtype=float32)                                          

If you pass the value 1 into the bracket, you can construct a vector of ones equals to the number of columns in the matrix m_shape.

# Create a vector of ones with the same number of column as m_shape
print(tf.ones(m_shape.shape[1]))                                  

Output

Tensor("ones_2:0", shape=(2,), dtype=float32)                                          

Finally, you can create a matrix 3×2 with only one’s

print(tf.ones(m_shape.shape))                                        

Output

Tensor("ones_3:0", shape=(3, 2), dtype=float32)