Related Articles

# Python – Tensorflow math.add_n() method

• Last Updated : 04 Jun, 2020

Tensorflow `math.add_n()` method adds the all passed tensors element-wise. The operation is done on the representation of a and b.
This method belongs to math module.

Syntax: `tf.math.add_n(inputs, name=None)`

Arguments

• inputs: It specifies a list of tf.Tensor or tf.IndexedSlices objects, and the shape and type of each must be same. tf.IndexedSlices objects converted automatically into dense tensors before applying method.
• name: This is optional parameter and this is the name of the operation.

Return: It returns a Tensor having the same shape and type as the elements of passed inputs.

Note: This method performs the same operation as tf.math.accumulate_n, but this method waits for the inputs to ready before starting to sum. So, this buffering results in more memory consumption when inputs might not ready at same time.

Let’s see this concept with the help of few examples:
Example 1:
 `# Importing the Tensorflow library ``import` `tensorflow as tf `` ` `# A constant a and b``a ``=` `tf.constant([[``1``, ``3``], [``2``, ``8``]])``b ``=` `tf.constant([[``2``, ``1``], [``6``, ``7``]])  `` ` `# Applying the math.add_n() function ``# storing the result in 'c' ``c ``=` `tf.math.add_n([a, b])`` ` `# Initiating a Tensorflow session ``with tf.Session() as sess:``    ``print``(``"Input 1"``, a)``    ``print``(sess.run(a))``    ``print``(``"Input 2"``, b)``    ``print``(sess.run(b))``    ``print``(``"Output: "``, c)`

Output:

```Input 1 Tensor("Const_99:0", shape=(2, 2), dtype=int32)
[[1 3]
[2 8]]
Input 2 Tensor("Const_100:0", shape=(2, 2), dtype=int32)
[[2 1]
[6 7]]
[[ 3  4]
[ 8 15]]
```

Example 2:

 `# Importing the Tensorflow library ``import` `tensorflow as tf `` ` `# A constant a and b``a ``=` `tf.constant([[``1``, ``1``], [``2``, ``6``]])``b ``=` `tf.constant([[``5``, ``1``], [``8``, ``7``]])  `` ` `# Applying the math.add_n() function ``# storing the result in 'c' ``c ``=` `tf.math.add_n([a, b], name ``=` `"Add_N"``)`` ` `# Initiating a Tensorflow session ``with tf.Session() as sess:``    ``print``(``"Input 1"``, a)``    ``print``(sess.run(a))``    ``print``(``"Input 2"``, b)``    ``print``(sess.run(b))``    ``print``(``"Output: "``, c)``    ``print``(sess.run(c))`

Output:

```Input 1 Tensor("Const_101:0", shape=(2, 2), dtype=int32)
[[1 1]
[2 6]]
Input 2 Tensor("Const_102:0", shape=(2, 2), dtype=int32)
[[5 1]
[8 7]]