Python – TensorFlow math.add_n() 方法
Tensorflow math.add_n()
方法按元素添加所有传递的张量。该操作是在 a 和 b 的表示上完成的。
该方法属于数学模块。
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.
注意:此方法执行与 tf.math.accumulate_n 相同的操作,但此方法在开始求和之前等待输入准备好。因此,当输入可能没有同时准备好时,这种缓冲会导致更多的内存消耗。
让我们通过几个例子来看看这个概念:
示例 1:
示例 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]]
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。