Python TensorFlow ``cumulative_logsumexp()`` 函数与代码示例


发布日期 : 2024-12-27 01:17:19 UTC

访问量: 10 次浏览

Python – tensorflow.math.cumulative\_logsumexp()

TensorFlow是谷歌设计的开源Python库,用于开发机器学习模型和深度学习神经网络。

cumulative\_logsumexp()用于计算输入张量的累积对数-exp。
这个操作相当于tensorflow.math.log( tensorflow.math.cumsum( tensorflow.math.exp(x)),但它在数值上更稳定。

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

参数:

  • x:它是输入张量。这个张量允许的 dtypes 是float16, float32, float64。
  • axis(可选):它是一个 int32 类型的张量。它的值应该在一个 int32 类型的张量的范围内(默认:0)。必须在[-rank(x), rank(x)]范围内。默认值是0。
  • exclusive(可选):它的类型是 bool 。默认值是False。
  • reverse(可选):它的类型是 bool 。默认值是False。
  • name(可选):它定义了操作的名称。

返回值:

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

示例 1:

# importing the library
import tensorflow as tf

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

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

# Cumulative log-sum-exp
res  = tf.math.cumulative_logsumexp(a)

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

输出:

Input: tf.Tensor([1. 2. 4. 5.], shape=(4,), dtype=float64)
Output: tf.Tensor([1. 2.31326169 4.16984602 5.36184904], shape=(4,), dtype=float64)

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

# importing the library
import tensorflow as tf

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

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

# Cumulative log-sum-exp
res  = tf.math.cumulative_logsumexp(a, reverse = True, exclusive = True)

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

输出:

Input: tf.Tensor([2. 3. 4. 5.], shape=(4,), dtype=float64)
Output: tf.Tensor([ 5.40760596e+000 5.31326169e+000 5.00000000e+000 -1.79769313e+308], shape=(4,), dtype=float64)