Python TensorFlow reduce_sum

In this Python tutorial, we will learn how to use TensorFlow reduce_sum() in Python. Also, we will cover the following topics.

  • TensorFlow reduce_sum keepdims
  • TensorFlow reduce_sum vs sum
  • TensorFlow reduce_sum axis=-1
  • TensorFlow reduce count boolean
  • TensorFlow reduce_sum nan
  • TensorFlow reduce_sum function
  • TensorFlow reduce_sum list
  • TensorFlow weighted reduce sum
  • TensorFlow reduce_mean vs reduce_sum

Python TensorFlow reduce_sum

  • In this section, we will learn how to find the sum of a tensor in TensorFlow Python.
  • To perform this particular task, we are going to use the tf.math.reduce_sum() function.
  • In Python, this function is used to equate the sum of all elements across the dimension of Tensor.

Syntax:

Let’s have a look at the Syntax and understand the working of tf.math.reduce_sum() function.

tf.math.reduce_sum
                  (
                   input_tensor,
                   axis=None,
                   Keepdims=False,
                   name=None
                  )
  • It consists of a few parameters
    • input_tensor: This parameter indicates the tensor which we want to reduce and it should always be a numeric type.
    • axis: By default it takes none value and it reduces all dimension, if there is no value in tensor.
    • keepdims: This parameter will check the condition if it is true then it reduce the length of rank tensor. By default it takes False value.
    • name: It is an optional parameter and it indicates the name for the operation.

Example:

Let’s take an example and check how to find the sum of a tensor in TensorFlow Python

Source Code:

import tensorflow as tf

new_tensor = tf.constant([67, 89, 24, 56])
new_output = tf.math.reduce_sum(new_tensor)
print("Sum of tensor:",new_output)

In the above code first, we have imported the TensorFlow library and then declare the input tensor named ‘new_tensor’. After we have used the tf.math.reduce() function and within this function, we have assigned the given tensor as an argument.

Once you will execute this code the Output displays the sum of all elements which is present in the tensor.

Here is the Screenshot of the following given code.

Python TensorFlow reduce_sum
Python TensorFlow reduce_sum

Read: TensorFlow Tensor to numpy

TensorFlow reduce_sum keepdims

  • In this section, we will learn how to use the keepdims parameter in tf.reduce_sum() function.
  • By using the tf.math.reduce_sum() function, we can easily perform this particular task. First, we will import the TensorFlow library, and then we will create a tensor by using the tf.constant() function.
  • Next, we will declare a variable ‘new_output’ and use the tf.math.reduce_sum() function. Inside this function, we are going to use the tensor and keepdims=True as an argument.

Syntax:

Here is the Syntax of tf.math.reduce_sum() function.

tf.math.reduce_sum
                  (
                   input_tensor,
                   axis=None,
                   Keepdims=True,
                   name=None
                  )

Note: In this function, if the keepdims parameter is true then the rank of the tensor is reduced by 1

Example:

import tensorflow as tf

new_tensor = tf.constant([[67, 89, 24, 56],
                         [86,34,18,89]])
new_tensor.numpy()
new_output = tf.math.reduce_sum(new_tensor,0, keepdims=True).numpy()
print("Sum of tensor:",new_output)

Here is the execution of the following given code.

Python TensorFlow reduce_sum keepdims
Python TensorFlow reduce_sum keepdims

Read: TensorFlow get shape

TensorFlow reduce_sum vs sum

  • In this section, we will learn the difference between reduce_sum and sum in TensorFlow Python.
  • In this example, we are going to see the major difference between reduce_sum() and numpy.sum() function. In Python the numpy.sum() function is used to calculate the sum of all elements of a given array.
  • While in the case of the reduce_sum() function it will help the user to compute the sum of all elements across the dimension of Tensor.
  • In Python the numpy.sum() function is available in the numpy package module and if the axis is provided then it will return the sum of all elements along with the axis. While in the case of the reduce_sum() function it will reduce the input tensor along with the axis.

Syntax:

Here is the Syntax of Python numpy.sum() function.

numpy.sum
         (
          a,
          axis=None,
          dtype=None,
          out=None,
          keepdims=<no value>,
          initial=<no value>,
          where=<no value>
         )

Example:

Let’s take an example and check the difference between Python reduce_sum() and sum() function.

Source Code:

import tensorflow as tf

new_tensor = tf.constant([[178, 98, 23, 198],
                         [289,945,435,190]])
new_tensor.numpy()
new_output = tf.math.reduce_sum(new_tensor,0, keepdims=True).numpy()
print("Sum of tensor:",new_output)

# sum() function
import numpy as np
new_arr=np.array([[178, 98, 23, 198],
                  [289,945,435,190]])
new_result=np.sum(new_arr,axis=0)
print("Sum of array:",new_result)

In the above code first, we have imported the TensorFlow library for using the tf.math.reduce() function and then we have declared a tensor by using the tf.constant() function. After creating the tensor we have used the tf.math.reduce() function and assign the tensor, axis,keedims=True as an argument.

Next, we have created an array by using the np.array() function and then used the np.sum() function and pass an array as an argument. Once you will execute this code the output displays the sum of all elements.

Here is the implementation of the following given code.

TensorFlow reduce_sum vs sum
TensorFlow reduce_sum vs sum

Also, check: Module ‘TensorFlow’ has no attribute ‘session’

TensorFlow reduce_sum axis=-1

  • Here we are going to see how to use the axis=-1 in Python TensorFlow reduce_sum() function.
  • To perform this particular task we are going to use the TensorFlow function tf.math.reduce_sum(). In this function, we are going to set the axis=-1 along with the input tensor and it will reduce the second dimension.
  • In Python, the axis specifies the dimension of a tensor, and -1 means the last axis.

Example:

import tensorflow as tf

new_tensor = tf.constant([[34, 45, 89, 178],
                         [134,456,976,234]])

new_result = tf.math.reduce_sum(new_tensor,-1)
print("Sum of tensor:",new_result)

In the following given code first, we have imported the TensorFlow library and then created a tensor ‘new_tensor’ by using the tf.constant() function. After that, we have used the tf.math.reduce_sum() function and within this function, we assigned the tensor and axis=-1 as an argument.

Here is the Output of the following given code.

TensorFlow reduce_sum axis-1
TensorFlow reduce_sum axis-1

Read: Python TensorFlow reduce_mean

TensorFlow reduce count boolean

  • In this section, we will learn how to count the boolean values in Python TensorFlow reduce_sum() function.
  • To do this task we are going to use the tf.math.count_nonzero() function. In Python TensorFlow the tf. math.count_nonzero() function is used to count the non-zero elements across dimensions of the input tensor. Suppose you have an input tensor that contains zero and non-zero elements.
  • In this example we have assigned only true and false (boolean) values then this function will help the user to count the non-zero elements which are available in the given Tensor.

Syntax:

Let’s have a look at the Syntax and understand the working of tf.math.count_nonzero() function.

tf.math.count_nonzero
                     (
                      input,
                      axis=None,
                      keepdims=None,
                      dtype=tf.dtypes.int64,
                      name=None,
                     )
  • It consists of a few parameters
    • input: This parameter indicates the tensor that need to be reduced and it always will be boolean,numeric and string.
    • axis: By default it takes none value that specifies reduces all dimensions.
    • keepdims: It is an optional parameter and if it is true then it will reduce dimension with length 1.
    • dtype: By default it takes tf.dtypes.int64 data type and indicates the output of dtype.

Example:

Let’s take an example and check how to count the boolean values in Python TensorFlow

Source Code:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
new_tensor = tf.constant([[True, True], [False, True]])
with tf.compat.v1.Session() as val:
    result = tf.math.count_nonzero(new_tensor)
    new_output=val.run(result)
    print(new_output)

In the above code, we have created a tensor and then we have used the tf.compat.v1.session() function for running the session. After that, we have used the tf.math.count_nonzero() function and assign the input tensor as an argument. Once you will execute this code the output displays the count of True values.

Here is the Screenshot of the following given code.

Python TensorFlow reduce count boolean
Python TensorFlow reduce count boolean

Read TensorFlow Multiplication

Another example to check the sum of boolean in Tensorflow

In this example, we have created a tensor by using the tf.constant() function and assigned the boolean values. Next, we have used the tf.reduce_any() function and it will return only the True value.

Syntax:

Here is the Syntax of tf.reduce_any() function.

tf.math.reduce_any
                  (
                   input_tensor,
                   axis=None,
                   keepdims=False,
                   name=None
                  )

Example:

import tensorflow as tf

new_tensor = tf.constant([[True,True],
                         [False,True]])

new_result = tf.reduce_any(new_tensor,1)
print("Boolean value of Tensor:",new_result)

Here is the execution of the following given code.

TensorFlow reduce count boolean
TensorFlow reduce count boolean

Read: Python TensorFlow random uniform

TensorFlow reduce_sum nan

  • In this section we will learn how to reduce nan values by using tf.math.reduce_sum() function in Python TensorFlow.
  • First, we will create a tensor by using the tf.constant() function and within this tensor, we are going to assign the nan values and then reduce the values by using the tf.math.reduce_sum() function along with axis=1.

Example:

import tensorflow as tf
import numpy as np
new_tensor = tf.constant([[np.nan,np.nan],
                         [np.nan,np.nan]])

new_result = tf.math.reduce_sum(new_tensor,1)
print("Sum of nan values:",new_result)

Here is the implementation of the following given code

Python TensorFlow reduce_sum nan
Python TensorFlow reduce_sum nan

Read: Python TensorFlow expand_dims

TensorFlow reduce_sum function

  • In this section, we will learn how to use the reduce_sum function in Python TensorFlow.
  • By using the tf.math.reduce_sum() function, we can easily sum all the elements that are available in Tensor. To create a tensor in TensorFlow we are going to use the tf.contstant() function.

Syntax:

Here is the Syntax of tf.math.reduce_sum() function

tf.math.reduce_sum
                  (
                   input_tensor,
                   axis=None,
                   Keepdims=False,
                   name=None
                  )

Example:

Let’s take an example and understand the working of tf.math.reduce_sum() function

Source Code:

import tensorflow as tf

tensor1 = tf.constant([[56,78,34,67],
                         [88,45,38,145]])

new_output = tf.math.reduce_sum(tensor1,[0,1],keepdims=True)
print(new_output)

In the following given code, we have used the tf.math.reduce_sum() function and within this function we have set the axis [0,1] and keepsdims=True as an argument.

You can refer to the below Screenshot

TensorFlow reduce_sum function in Python
TensorFlow reduce_sum function in Python

Read: Python TensorFlow Placeholder

TensorFlow weighted reduce sum

  • In this Program, we will learn how to find the weighted sum of a Tensor in Python TensorFlow.
  • In this example, we will create two tensors ‘tens1’ and ‘tens2’ by using the tf.constant() function. Next, we will define the function ‘apply_weight’ and pass the input tensor.

Example:

import tensorflow as tf
tens1 = tf.constant([13.0, 17.0, 14.0])
tens2 = tf.constant([[[24.0, 15.0],[45.0, 36.0],[15.0, 26.0]],
                 [[44.0, 13.0],[66.0, 69.0],[16.0, 23.0]]]
)

def apply_weight(tens2, tens1): 
    return tf.map_fn(mult, tens2)

def mult(l):
    result = tf.transpose(l)
    return tf.map_fn(mult_pars, result)

def mult_pars(m): 
    return tf.reduce_sum(tens1 * m) / tf.reduce_sum(tens1)

print(apply_weight(tens2,tens1))

Here is the Screenshot of the following given code

TensorFlow weighted reduce sum in Python
TensorFlow weighted reduce sum in Python

Read: TensorFlow Get Variable + Examples

TensorFlow reduce_mean vs reduce_sum

  • Here we are going to discuss the difference between reduce_mean() and reduce_sum() function in Python TensorFlow.
  • In TensorFlow, the reduce_mean() function is used to calculate the mean of values across dimensions of a Tensor. While in the case of the reduce_sum() function it will help the user to calculate the sum of values across dimensions of an input tensor.

Syntax:

Here is the Syntax of TensorFlow reduce_mean() function

tf.math.reduce_mean
                   (
                    input_tensor,
                    axis=None,
                    keepdims=False,
                    name=None
                   )

Example:

Let’s take an example and check the difference between tf.reduce_mean() and tf.reduce_sum() function

Source Code:

import tensorflow as tf

new_tens=tf.constant([[23,45,11],
                      [67,89,12]])
new_result=tf.reduce_mean(new_tens)
print(new_result)
#sum of all elements
new_result2=tf.reduce_sum(new_tens)
print(new_result2)

Here is the implementation of the following given code

TensorFlow reduce_mean vs reduce_sum in Python
TensorFlow reduce_mean vs reduce_sum in Python

In this Python tutorial, we have learned how to use TensorFlow reduce_sum() in Python. Also, we have covered the following topics.

  • TensorFlow reduce_sum keepdims
  • TensorFlow reduce_sum vs sum
  • TensorFlow reduce_sum axis=-1
  • TensorFlow reduce sum boolean
  • TensorFlow reduce_sum nan
  • TensorFlow reduce_sum function
  • TensorFlow reduce_sum list
  • TensorFlow weighted reduce sum
  • TensorFlow reduce_mean vs reduce_sum