Python ``tensorflow.math.add_n()`` 多张量逐元素求和方法与实例


发布日期 : 2024-05-28 16:56:14 UTC

访问量: 10 次浏览

Python – Tensorflow math.add\_n() 方法

Tensorflow math.add\_n() 方法将所有传递的张量按元素相加。该操作是在a和b的表示上进行的。

这个方法属于数学模块。

语法:
tf.math.add_n(inputs, name=None)

参数

  • inputs: 它指定了一个 tf.Tensortf.IndexedSlices 对象的列表,并且每个对象的形状和类型必须相同。tf.IndexedSlices 对象在应用方法之前自动转换为密集的张量。
  • name: 这是一个可选的参数,这是操作的名称。

返回:
它返回一个张量,其形状和类型与通过的输入的元素相同。

注意:该方法与 tf.math.accumulate\_n 执行相同的操作,但该方法在开始求和之前会等待输入准备好。
因此,当输入可能没有同时准备好时,这种缓冲会导致更多的内存消耗。

让我们借助几个例子来看看这个概念。

示例 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)

输出:

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]]
Output: Tensor("AddN:0", shape=(2, 2), dtype=int32)
[[ 3 4]
[ 8 15]]

示例 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))

输出:

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]]
Output: Tensor("Add_N:0", shape=(2, 2), dtype=int32)
[[ 6 2]
[10 13]]