Tensorflow 2 – Aggregation Operators on Tensors

Last updated on August 30, 2021 A Goodman Loading... Post a comment

In simple words, aggregating means condensing the from multiple values down to a smaller amount of values. You can find a more formal definition in the Cambridge dictionary or Merriam Webster dictionary.

This article shows you how to aggregate tensors in Tensorflow 2. We’ll walk through a few examples of performing 6 basic (and popular) aggregation operators: finding the mean, sum, min, max, standard deviation, and variance of elements across dimensions of a given tensor.

Mean & Sum

You can calculate mean and sum of a tensor by using the tf.math.reduce_mean and tf.math.reduce_sum functions, repectively.

Example:

import tensorflow as tf
import numpy as np

# np.random.seed(1)
arr = np.random.randint(0, 100, size=(3, 4, 5))
tensor = tf.constant(arr)

sum = tf.math.reduce_sum(tensor)
mean = tf.math.reduce_mean(tensor)

print('Sum:', sum)
print('Mean:', mean)

Output:

import tensorflow as tf
import numpy as np

# np.random.seed(1)
arr = np.random.randint(0, 100, size=(3, 4, 5))
tensor = tf.constant(arr)

sum = tf.math.reduce_sum(tensor)
mean = tf.math.reduce_mean(tensor)

print('Sum:', sum)
print('Mean:', mean)

Min & Max

To find the minimum and maximum elements of a given tensor, you can use the tf.math.reduce_min and tf.math.reduce_max functions, respectively.

Example:

import tensorflow as tf

tensor = tf.constant([
                      [1, 2, 3],
                      [4, 5, 6],
                      [-1, -8, 10]
])

min = tf.math.reduce_min(tensor)
max = tf.math.reduce_max(tensor)

print('Min:', min)
print('Max:', max)

Output:

Min: tf.Tensor(-8, shape=(), dtype=int32)
Max: tf.Tensor(10, shape=(), dtype=int32)

Standard Deviation & Vairance

The tf.math.reduce_std and tf.math.reduce_variance functions help us computes the standard deviation and variance of elements of a tensor.

Example:

import tensorflow as tf
import numpy as np

a = tf.constant(np.random.randint(0, 1000, size=(6, 7, 8)), dtype=tf.float32)

std = tf.math.reduce_std(a)
var = tf.math.reduce_variance(a)

print('Standard deviation:', std)
print('Variance:', var)

Output:

Standard deviation: tf.Tensor(299.8748, shape=(), dtype=float32)
Variance: tf.Tensor(89924.89, shape=(), dtype=float32)

Note: The data type of the input must be float or complex.

Final Words

Reference: https://www.tensorflow.org/api_docs/python/tf/math

We’ve covered the fundamental aggregation operators in Tensorfow. If you’d like to explore more about machine learning and Python stuff, take a look at the following articles:

You can also check out our Machine Learning category page or Python category page for more tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles