Python Tensorflow math.accumulate\_n()方法及示例


发布日期 : 2023-05-23 19:46:37 UTC

访问量: 10 次浏览

Python – Tensorflow math.accumulate_n()方法

Tensorflow的math.accumulate_n()方法对一个传入的张量列表进行元素相加。执行该操作后的结果是一个张量。该操作是在a和b的表示上进行的,该方法属于数学模块。

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

参数

  • inputs:这个参数需要一个张量对象的列表,并且每个对象都有相同的形状和类型。
  • shape:这是一个可选的参数,它定义了输入元素的预期形状。
  • dtype :这是一个可选参数,它定义了输入的预期数据类型。
  • name: 这是一个可选的参数,这是操作的名称。

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

让我们借助几个例子来看看这个概念。例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))

输出:

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]]

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

输出:

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]]