Python TensorFlow reduce_mean

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

  • TensorFlow reduce_mean with mask
  • TensorFlow reduce_mean nan
  • TensorFlow reduce mean squared error
  • TensorFlow reduce mean ignore zero
  • TensorFlow reduce_mean numpy
  • TensorFlow reduce_mean reduction_indices
  • TensorFlow reduce mean ignore nan
  • TensorFlow reduce_mean keepdims

Python TensorFlow reduce_mean

  • In this section, we will learn how to use the tf.reduce_mean() function in TensorFlow Python.
  • To perform this particular task, we are going to use the tf.math.reduce_mean() function and this function is available in TensorFlow version 2.x.
  • In Python TensorFlow, the tf.math.reduce_mean() function is used to calculate the mean of values across dimensions of an input tensor.

Syntax:

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

tf.math.reduce_mean
                   (
                    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 once you will use this in function then by default all dimensions will reduce.
    • keepdims: This parameter will check the condition if it is true then it reduces the length of the 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 get the mean value of the input tensor.

import tensorflow as tf

new_tensor = tf.constant([[13,69,55],
                         [245,78,94]])

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

In the above code we have imported the TensorFlow library and then created a tensor by using the tf.constant() function. After that, we have used the tf.math.reduce_mean() function and within this function, we have assigned the tensor and axis=1 as an argument.

Here is the Screenshot of the following given code.

Python TensorFlow reduce_mean
Python TensorFlow reduce_mean

As you can see in the Screenshot the output displays the mean value of the tensor.

Also, check: TensorFlow Tensor to numpy

TensorFlow reduce_mean with mask

  • In this section, we will discuss how to use the mast in reduce_mean() function.
  • To do this task, we are going to use the tf.boolean_mask() function and it is used to compute boolean mask to tensor this method is available in the TensorFlow package.
  • In this method, the mask shape must match the first K dimension of the tensor’s shape.

Syntax:

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

tf.boolean_mask
               (
                tensor,
                mask,
                axis=None,
                name='boolean_mask',
               )
  • It consists of a few parameters
    • tensor: This parameter indicates the input tensor and it can be a n-dimensional tensor.
    • mask: It is a K-D boolean Tensor and it will set the condition K<=N, where K must be represented as statically.
    • axis: By default it takes none value and it specifies the axis in tensor to mask.

Example:

import tensorflow as tf
import numpy as np

tens=[14,67,89,25]
new_mask=np.array([True,False,False,True])
result=tf.boolean_mask(tens, new_mask)
print("mask value:",result)
new_output=tf.math.reduce_mean(result)
print("Mean value of mask:",new_output)
  • In the above code, we have created a mask by using the np.array() function and assigned boolean values. After that, we have used the tf.boolean_mask() function and within this function, we have passed the tensor and mask as an argument.
  • Once you will execute this function the output displays the True value along with associated tensor values.
  • After that, we have used the tf.math.reduce_mean() function and pass ‘result’ as an argument and it will return the mean value of the mask.

Here is the execution of the following given code

Python TensorFlow reduce_mean with mask
Python TensorFlow reduce_mean with mask

Read: TensorFlow get shape

TensorFlow reduce_mean nan

  • Here we are going to discuss how to reduce nan values by using the reduce_mean() function in TensorFlow Python.
  • In this example, we are going to get the mean value of nan values. To do this task first we will import the numpy library for np.nan values and then we are going to create the tensor by using the tf.constant() function and inside this function, we have set the nan values. In Python, the nan stands for ‘not a number’.
  • Next, we will declare a variable ‘new_result’ and assign the tf.math.reduce_mean() function and within this function we are going to set the input tensor and axis as an argument.

Example:


import tensorflow as tf
import numpy as np


new_tensor = tf.constant([[np.nan,np.nan,np.nan,15,76],
                         [np.nan,np.nan,np.nan,24,89]])

new_result = tf.math.reduce_mean(new_tensor,[0,1])
print("Sum of nan values:",new_result)

Here is the execution of the following given code

Python TensorFlow reduce_mean nan
Python TensorFlow reduce_mean nan

As you can see in the Screenshot the output displays the mean of nan values.

Read: Python TensorFlow random uniform

TensorFlow reduce mean squared error

  • In this section, we will discuss how to use the mean squared error function in TensorFlow Python.
  • To perform this particular task we are going to use the tf.compat.v1.losses.mean_squared_error() function and this function is available in Tensorflow packages.

Syntax:

Here is the Syntax of tf.compat.v1.losses.mean_squared_error() function

tf.compat.v1.losses.mean_squared_error
                                      (
                                       labels,
                                       prediction,
                                       weights=1.0,
                                       scope=None,
                                      )
  • It consists of a few parameters
    • labels: This parameter indicates the parameter inside the function.
    • prediction: The prediction parameter is used in call() method.

Example:

import tensorflow as tf

y_true = tf.constant([[4.6, 7.3, 3.2],
                      [4.1,5.8,7.2]])
y_pred = tf.constant([[2.4, 4.6, 9.7],
                      [1.2,2.3,1.6]])


result=tf.compat.v1.losses.mean_squared_error(y_true,y_pred)
print("Reduce mean squared error:",result)

In the following given code, we have created a tensor by using the tf.constant() function and then we have used the tf.compat.v1.losses.mean_squared_error() function and within this function, we assigned the labels and prediction as an argument.

Here is the implementation of the following given code.

TensorFlow reduce mean squared error in Python
TensorFlow reduce mean squared error in Python

Read: Module ‘TensorFlow’ has no attribute ‘session’

TensorFlow reduce mean ignore zero

  • In this section, we will learn how to ignore zero values in a tensor by using the reduce_mean() function in Python.
  • To do this task we are going to use the tf.cast() function and this function is used to caste an input tensor to a new type within this function we will set the condition new_tensor!=0 along with datatype.
  • Next, we will use the tf.reduce_sum() function and divide it with tensor and it will ignore zero value from the tensor.

Syntax:

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

tf.cast
       (
        x,
        dtype,
        name=None
       )
  • It consists of a few parameters
    • x: This parameter indicates the input tensor.
    • name: This is an optional parameter and by default it takes none value.

Example:


import tensorflow as tf

new_tensor= tf.constant([[2,0,3],[12,34,0],[0,23,31]])
m = tf.cast(new_tensor != 0,tf.int32)
z = tf.reduce_sum(new_tensor, -1) / tf.reduce_sum(m, -1)
print(z)

Here is the Screenshot of the following given code

TensorFlow reduce mean ignore zero in Python
TensorFlow reduce mean ignore zero in Python

Read: Import error no module named TensorFlow

TensorFlow reduce_mean numpy

  • In this Program, we will learn how to work numpy compatibility in tf.reduce_mean() function.
  • To perform this particular task, we are going to use the tf.reduce_mean() function and within this function, we have assigned the tensor as an argument.
  • And it is used to specify the output type and by default, it takes float32.

Example:

import tensorflow as tf

tensor = tf.constant([12, 13.5, 1, 1.5])
tf.reduce_mean(tensor)

Here is the execution of the following given code.

Python TensorFlow reduce_mean numpy
Python TensorFlow reduce_mean numpy

As you can see in the Screenshot the output displays the mean value in NumPy.

Read: Python TensorFlow one_hot

TensorFlow reduce_mean reduction_indices

  • In this section, we will discuss how to use the reduction_indices parameter in the tf.reduce_mean() function.
  • To perform this particular task, we are going to use the tf.compat.v1.reduce_mean() function and this method will help the user to calculate the mean of values across dimensions of an input tensor.

Syntax:

Let’s have a look at the Syntax and understand the working of tf.compat.v1.reduce_mean() function.

tf.compat.v1.reduce_mean
                        (
                         input_tensor,
                         axis=None,
                         keepdims=None,
                         name=None,
                         reduction_indices=None,
                         keep_dims=None
                        )

Example:

import tensorflow as tf

tensor = tf.constant([14, 15.5, 12, 17.5])
z=tf.compat.v1.reduce_mean(tensor, reduction_indices=[0])
print(z)

In the above code we have imported the TensorFlow library and then created the tensor by using the tf.constant() function.

After that we have used the tf.compat.v1.reduce_mean() function and within this function we have used the reduction_indices[0] parameter.

You can refer to the below Screenshot

Python TensorFlow reduce_mean reduction_indices
Python TensorFlow reduce_mean reduction_indices

Read: Python TensorFlow Placeholder

TensorFlow reduce mean ignore nan

  • In this section, we will discuss how to ignore nan values by using the reduce_mean() function in Python TensorFlow.
  • To do this task we are going to use the tf.where function along with tf.math.is_nan() and this function will help the user to remove the nan values from the tensor.
  • After removing the tensor we are going to use the tf.reduce_mean() function to calculate the mean values of the updated tensor.

Syntax:

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

tf.math.is_nan
              (
               x,
               name=None,
              )

Example:

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

Source Code:

import tensorflow as tf
import numpy as np

tens1 = tf.constant([[16, 67], [24, np.nan]])
tens2 = tf.constant([[np.nan, np.nan], [np.nan, 56]])

c = tf.where(tf.math.is_nan(tens1), tens2, tens1)
result=tf.reduce_mean(c)
print(result)

Here is the execution of the following given code

Python TensorFlow reduce mean ignore nan
Python TensorFlow reduce mean ignore nan

Read: Tensorflow custom loss function

TensorFlow reduce_mean keepdims

  • In this Program, we will discuss how to use the keepdims parameter in reduce_mean() function.
  • In this function, the keepdims parameter will check the condition if the value is true the rank of the input tensor is reduced by 1, and by default, it takes a false value.

Syntax:

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

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

Example:

import tensorflow as tf

new_tensor = tf.constant([[67,145,267],
                         [18,29,31]])

new_result = tf.math.reduce_mean(new_tensor,1,keepdims=False)
print("Sum of nan values with keepdims axis:",new_result)

In the following given code first, we have imported the TensorFlow library and then for creating a tensor we have used the tf.constant() function. After that, we have used the tf.math.reduce_mean() function and inside the function we have set the tensor, axis, and keepdims=False as an argument.

Here is the implementation of the following given code

Python TensorFlow reduce_mean keepdims
Python TensorFlow reduce_mean keepdims

YOu may also like to read the following Python TensorFlow tutorials.

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

  • TensorFlow reduce_mean pytorch
  • TensorFlow reduce_mean with mask
  • TensorFlow reduce_mean nan
  • TensorFlow reduce mean squared error
  • TensorFlow reduce mean layer
  • TensorFlow reduce mean ignore zero
  • TensorFlow reduce_mean numpy
  • TensorFlow reduce_mean reduction_indices
  • TensorFlow reduce mean ignore nan
  • TensorFlow reduce_mean keepdims