Python ``tensorflow.math.cumsum()`` 累积和函数与实例


发布日期 : 2024-11-20 21:25:45 UTC

访问量: 10 次浏览

Python – tensorflow.math.cumsum()

TensorFlow是谷歌设计的开源Python库,用于开发机器学习模型和深度学习神经网络。 cumsum() 用于计算输入张量的累积和。

语法:
tensorflow.math.cumsum(x, axis, exclusive, reverse, name)

参数:

  • x:它是输入的张量。这个张量允许的 dtype 是float32, float64, int64, int32, uint8, uint16, int16, int8, complex64, complex128, qint8, quint8, qint32, half。
  • axis(可选):它是一个 int32 类型的张量。它的值应该在一个int32类型的张量的范围内(默认:0)。必须在[-rank(x), rank(x)]范围内。默认值是0。
  • exclusive(可选):它的类型是bool。默认值是False,如果设置为true,那么输入[a, b, c]的输出将是[0, a, a+b]。
  • reverse(可选):它的类型是bool。默认值是False,如果设置为true,那么输入[a, b, c]的输出将是[a+b+c, a+b, a]。
  • name(可选):它定义了操作的名称。

返回:它返回一个与x具有相同 dtype 的张量。

示例 1:

# importing the library
import tensorflow as tf

# initializing the input
a = tf.constant([1, 2, 4, 5], dtype = tf.int32) 

# Printing the input
print("Input: ",a)

# Cumulative sum
res  = tf.math.cumsum(a)

# Printing the result
print("Output: ",res)

输出:

Input: tf.Tensor([1 2 4 5], shape=(4,), dtype=int32)
Output: tf.Tensor([ 1 3 7 12], shape=(4,), dtype=int32)

例子2:
在这个例子中,反向和排他都被设置为 “真”。

# importing the library
import tensorflow as tf

# initializing the input
a = tf.constant([2, 3, 4, 5], dtype = tf.int32) 

# Printing the input
print("Input: ",a)

# Cumulative sum
res  = tf.math.cumsum(a, reverse = True, exclusive = True)

# Printing the result
print("Output: ",res)

输出:

Input: tf.Tensor([2 3 4 5], shape=(4,), dtype=int32)
Output: tf.Tensor([12 9 5 0], shape=(4,), dtype=int32)