How to create tensors in TensorFlow

This tutorial explains how to create tensors in TensorFlow.

What are tensors

Tensors are multi-dimensional arrays with a uniform type.

Create Scalar in TensorFlow

Scalar is a rank-0 tensor. A scalar doesn't have any axis and contains single value. Below is the example for creating a scalar in TensorFlow.

   
    import tensorflow as tf

    scalar = tf.constant(10)
    print(scalar)

    # Output
    tf.Tensor(10, shape=(), dtype=int32)
     
Check number of axes in Scalar
   
    print(scalar.ndim)

    # Output
    0
     
Check shape of Scalar
   
    print(scalar.shape)

    # Output
    ()
     

Create Vector in TensorFlow

A vector is a rank-1 tensor. A vector contains one axis. Below is the example of creating a Vector in TensorFlow.

   
    import tensorflow as tf

    vector = tf.constant([6.0, 9.0, 11.0])
    print(vector)

    # Output
    tf.Tensor([ 6.  9. 11.], shape=(3,), dtype=float32)        
     
Check number of axes in Vector
   
    print(vector.ndim)

    # Output
    1
     
Check shape of Vector
   
    print(vector.shape)

    # Output
    (3,)
     

Create Matrix in TensorFlow

A matrix is a rank-2 tensor. Matrix have 2 axes. Below is the example of creating matrix in TensorFlow.

   
    import tensorflow as tf

    matrix = tf.constant([[4, 4, 2],
                        [3, 4, 3],
                        [5, 6, 1]])
    print(matrix)
    
    # Output
    tf.Tensor(
    [[4 4 2]
    [3 4 3]
    [5 6 1]], shape=(3, 3), dtype=int32)            
     
Check number of axes in Matrix
   
    print(matrix.ndim)

    # Output
    2
     
Check shape of Matrix
   
    print(matrix.shape)
    
    # Output
    (3, 3)
     

Create tensor with more than 2 axes

   
    import tensorflow as tf

    rank_3_tensor = tf.constant([
                    [[2 ,1, 1, 2, 3, 4],
                    [4, 5, 6, 7, 8, 9]],
                    [[6, 10, 11, 12, 13, 14],
                    [7, 15, 16, 17, 18, 19]],
                    [[11, 20, 21, 22, 23, 24],
                    [12, 25, 26, 27, 28, 29]],])
    
    print(rank_3_tensor)

    # Output
    tf.Tensor(
    [[[ 2  1  1  2  3  4]
    [ 4  5  6  7  8  9]]

    [[ 6 10 11 12 13 14]
    [ 7 15 16 17 18 19]]

    [[11 20 21 22 23 24]
    [12 25 26 27 28 29]]], shape=(3, 2, 6), dtype=int32)
     
Check shape of tensor
   
    print(rank_3_tensor.shape)

    # Output
    (3, 2, 6)
     
Check number of axes in tensor
   
    print(rank_3_tensor.ndim)

    # Output
    3
     
Check type of element in tensor
   
    print(rank_3_tensor.dtype)

    # Output
    dtype: 'int32'
     
Check number of elements along axis 0 of tensor
   
    print(rank_3_tensor.shape[0])

    # Output
    3
     
Check number of elements along last axis of tensor
  
    print(rank_3_tensor.shape[-1])   

    # Output
    6       
     

Category: TensorFlow