Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.logcumsumexp function

PyTorch torch.logcumsumexp function


PyTorch torch reference manual PyTorch torch reference manual

torch.logcumsumexp is a function in PyTorch used to compute the log of the cumulative sum of exponentials. It exponentiates the elements, then cumulatively sums them, and finally takes the logarithm, which avoids numerical overflow.

Function definition

torch.logcumsumexp(input, dim)

Parameter Description:


Usage examples

Example

import

torch

Creating tensors

x

=

torch.

tensor

(

[

1.0

,

2.0

,

3.0

]

)

Compute the log of the cumulative sum of exponentials

y

=

torch.

logcumsumexp

(

x

,

dim

=

0

)

print

(

y

)

The output is:

tensor([1.0000, 2.3133, 3.1000])

Example

import

torch

Verify: log(exp(1) + exp(2)) = log(exp(1) + exp(2))

log(e^1 + e^2) = log(e^1 + e^2) ≈ 2.3133

x

=

torch.

tensor

(

[

1.0

,

2.0

]

)

y

=

torch.

logcumsumexp

(

x

,

dim

=

0

)

Compare with direct computation

import

math

direct

=

math

.

log

(

math

.

exp

(

1

)

math

.

exp

(

2

)

)

print

(

"logcumsumexp:"

,

y

[

1

]

.

item

(

)

)

print

(

"direct:"

,

direct

)

The output is:

logcumsumexp: 2.313261505126953

direct: 2.313261505126953


PyTorch torch reference manual PyTorch torch reference manual