TensorFlow | How to use tf.reduce_sum in TensorFlow

tf.reduce_sum in TensorFlow reduces input_tensor along the dimensions given in axis. If axis is None, all dimensions are reduced, and a tensor with a single element is returned. Below are the example for tf.reduce_sum in TensorFlow.

  • Reducing Tensor to scalar value using tf.reduce_sum
  •  
    import tensorflow as tf
    tensor1 = tf.constant(value=[1,2,3])
    tensor2 = tf.reduce_sum(tensor1)
    print(tensor2)
    ====Output====
    tf.Tensor(6, shape=(), dtype=int32)
    
    
     
    tensor1 = tf.constant(value=[[1,2,3],[2,3,5]])
    tensor2 = tf.reduce_sum(tensor1)                
    print(tensor2)
    
    =====Output=====
    tf.Tensor(16, shape=(), dtype=int32)
    
    

  • Use of axis paramter in tf.reduce_sum
  •  
    # tf.reduce_sum with axis = 0
    tensor1 = tf.constant(value=[[1,2,3],[2,3,5]])
    tensor2 = tf.reduce_sum(tensor1,axis=0)
    
    print(tensor2)
    ====Output====
    tf.Tensor([3 5 8], shape=(3,), dtype=int32)
    
    
     
    # tf.reduce_sum with axis = 1
    tensor1 = tf.constant(value=[[1,2,3],[2,3,5]])
    tensor2 = tf.reduce_sum(tensor1,axis=1)
    
    print(tensor2)
    
    ====Output====
    tf.Tensor([ 6 10], shape=(2,), dtype=int32)
                  
    
    

    Category: TensorFlow