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

PyTorch torch.diff function

PyTorch torch.diff function


PyTorch torch reference manual PyTorch torch reference manual

torch.diff is a PyTorch function for computing differences between adjacent elements of a tensor. The formula is out[i] = input[i+1] - input[i].

Function definition

torch.diff(input, n=1, dim=-1, prepend=None, append=None)

Parameter Description:


Usage examples

Example

import

torch

Creating tensors

x

=

torch.

tensor

(

[

1

,

3

,

6

,

10

]

)

Compute first-order differences

y

=

torch.

diff

(

x

)

print

(

y

)

The output is:

tensor([2, 3, 4])

Example

import

torch

Creating tensors

x

=

torch.

tensor

(

[

1

,

3

,

6

,

10

]

)

Compute second-order differences

y

=

torch.

diff

(

x

,

n

=

2

)

print

(

y

)

The output is:

tensor([1, 1])

Example

import

torch

Create a 2D tensor

x

=

torch.

tensor

(

[

[

1

,

3

,

6

,

10

]

,

[

2

,

5

,

9

,

14

]

]

)

Compute differences along the last dimension

y

=

torch.

diff

(

x

)

print

(

y

)

The output is:

tensor([[2, 3, 4],

        [3, 4, 5]])


PyTorch torch reference manual PyTorch torch reference manual