Python ``tensorflow.math.cumprod()`` 累积乘积函数与实例


发布日期 : 2019-11-05 23:12:50 UTC

访问量: 10 次浏览

Python – tensorflow.math.cumprod()

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

语法:
tensorflow.math.cumprod( 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]的输出将是[1, a, a*b]。
  • reverse(可选):它的类型是bool。默认值是False,如果设置为true,那么输入[a, b, c]的输出将是[abc, 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 product
res  = tf.math.cumprod(a)

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

输出:

Input: tf.Tensor([1 2 4 5], shape=(4,), dtype=int32)
Output: tf.Tensor([ 1 2 8 40], 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 product
res  = tf.math.cumprod(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([60 20 5 1], shape=(4,), dtype=int32)