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

PyTorch torch.cumsum function

PyTorch torch.cumsum function


PyTorch torch reference manual 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

)

print

(

"Input:"

,

x

)

print

(

"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

)

print

(

"nCumulative sum by column:"

)

print

(

result_col

)

tensor([[ 1,  2,  3],

        [ 5,  7,  9]])

Cumulative by row

result_row

=

torch.

cumsum

(

x

,

dim

=

1

)

print

(

"nCumulative sum by row:"

)

print

(

result_row

)

tensor([[ 1,  3,  6],

        [ 4,  9, 15]])


PyTorch torch reference manual PyTorch torch reference manual