PyTorch torch.cumsum function
PyTorch torch reference manual
torch.cumsum is a PyTorch function for computing the cumulative sum. It returns the cumulative sum along a specified dimension, i.e. the sum of all elements from the start up to the current position.
Function definition
torch.cumsum(input, dim, dtype=None)
Usage examples
Example
import
torch
Compute the cumulative sum
x
=
torch.
tensor
(
[
1
,
2
,
3
,
4
,
5
]
)
result
=
torch.
cumsum
(
x
,
dim
=
0
)
(
"Input:"
,
x
)
(
"Cumulative sum:"
,
result
)
Output: tensor([1, 3, 6, 10, 15])
Note: 1, 1+2=3, 1+2+3=6, 1+2+3+4=10, 1+2+3+4+5=15
2D tensor
x
=
torch.
tensor
(
[
[
1
,
2
,
3
]
,
[
4
,
5
,
6
]
]
,
dtype
=
torch.
float32
)
Cumulative by column
result_col
=
torch.
cumsum
(
x
,
dim
=
0
)
(
"nCumulative sum by column:"
)
(
result_col
)
tensor([[ 1, 2, 3],
[ 5, 7, 9]])
Cumulative by row
result_row
=
torch.
cumsum
(
x
,
dim
=
1
)
(
"nCumulative sum by row:"
)
(
result_row
)