PyTorch torch.diff function
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:
input: the input tensorn: Number of differences, defaults to 1dim: Dimension along which to compute differencesprepend: Prepend to the input before computingappend: Append to the input after computing
Usage examples
Example
import
torch
Creating tensors
x
=
torch.
tensor
(
[
1
,
3
,
6
,
10
]
)
Compute first-order differences
y
=
torch.
diff
(
x
)
(
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
)
(
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
)
(
y
)
The output is:
tensor([[2, 3, 4],
[3, 4, 5]])