# Understanding tf.reduce_sum() function in TensorFlow

Hello everyone,

This tutorial will explain how to `use tf.reduce_sum()`

in TensorFlow.

## What is TensorFlow?

TensorFlow is a Python library used in machine learning as well as deep learning. To install the TensorFlow library we need to run the command below on the command prompt:

pip install tensorflow

tf.reduce_sum() is one of the functions used by of TensorFlow library. It is used to find the sum of elements of the tensor.

A tensor is n-dimenesional numeric array.

## Explaination of Code to understand TensorFlow tf.reduce_sum()

Now let’s understand the tf.reduce_sum() with the help of a simple program.

Let’s start with importing the library

import tensorflow as tf

Now let’s just define a multi-dimensional array ,here we are taking a two-dimensional array in below code:

tensor1=tf.constant([5,18],[6,8],dtype=tf.float64) print('Input',tensor1)

Output: Input tf.Tensor( [[ 5. 18.] [ 6. 8.]], shape=(2, 2), dtype=float64)

Now, let’s apply `tf.sum_reduce()`

function on above tensor ,it has the following syntax:

**Syntax: **tf.math.reduce_sum( tensor, axis(optional), keepdims=False(optional), name(optional))

**Parameters:**

- input: tensor to reduce
- axis(optional): dimension to reduce
- keepdims(optional):True if it will retain the reduced dimension with length 1 or False(default).
- name(optional):name of operation.

result = tf.math.reduce_sum(tensor1, axis = 1, keepdims = True) # Printing the result print('Result: ', result)

Result: tf.Tensor( [[23.] [14.]], shape=(2, 1), dtype=float64)

This function will return a tensor with a reduced sum along the given dimension.

We can also use this function on 1-d array:

tensor2 = tf.constant([21,56,78,9], dtype = tf.float

result1 = tf.math.reduce_sum(tensor2) # Printing the result print('Result: ', result1)

Result: tf.Tensor(164.0, shape=(), dtype=float64)

In this way we can make use of tf.reduce_sum() on multi-dimensional array.

## Leave a Reply