Skip to content
Related Articles

Related Articles

Improve Article

Python – Tensorflow math.accumulate_n() method

  • Last Updated : 04 Jun, 2020

Tensorflow math.accumulate_n() method performs performs the element-wise sum of a list of passed tensors. The result is a tensor after performing the operation. The operation is done on the representation of a and b. This method belongs to math module.

Syntax: tf.math.accumulate_n( inputs, shape=None, tensor_dtype=None, name=None)

Arguments

  • inputs: This parameter takes a list of Tensor objects, and each of them with same shape and type.
  • shape: This is optional parameter and it defines the expected shape of elements of inputs.
  • dtype: This is optional parameter and it defines the expected data type of inputs.
  • 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 inputs.

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], [6, 7]])
b = tf.constant([[5, 2], [3, 8]])  
  
# Applying the accumulate_n() function 
# storing the result in 'c' 
c = tf.math.accumulate_n([a, b, 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)
    print(sess.run(c))

Output:

Input 1 Tensor("Const_67:0", shape=(2, 2), dtype=int32)
[[1 3]
 [6 7]]
Input 2 Tensor("Const_68:0", shape=(2, 2), dtype=int32)
[[5 2]
 [3 8]]
Output:  Tensor("AccumulateNV2_2:0", shape=(2, 2), dtype=int32)
[[11  7]
 [12 23]]

Example 2:




# Importing the Tensorflow library 
import tensorflow as tf 
  
# A constant a and b
a = tf.constant([[2, 4], [1, 3]])
b = tf.constant([[5, 3], [4, 6]])  
  
# Applying the accumulate_n() function 
# storing the result in 'c' 
c = tf.math.accumulate_n([b, a, b], shape =[2, 2], tensor_dtype = tf.int32)
  
# 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_73:0", shape=(2, 2), dtype=int32)
[[2 4]
 [1 3]]
Input 2 Tensor("Const_74:0", shape=(2, 2), dtype=int32)
[[5 3]
 [4 6]]
Output:  Tensor("AccumulateNV2_5:0", shape=(2, 2), dtype=int32)
[[12 10]
 [ 9 15]]

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :