PyTorch torch.diff Function
PyTorch torch Reference Manual
torch.diffis a function in PyTorch used to calculate the differences between adjacent elements of a tensor. The calculation 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: input tensorn: number of differences, defaults to 1dim: dimension along which to calculate differencesprepend: prepend to input before calculationappend: append to input after calculation
Usage Examples
Example
import torch
# Create tensor
x = torch.tensor([1, 3, 6, 10])
# Calculate first-order difference
y = torch.diff(x)
print(y)
# Create tensor
x = torch.tensor([1, 3, 6, 10])
# Calculate first-order difference
y = torch.diff(x)
print(y)
The output result is:
tensor([2, 3, 4])
Example
import torch
# Create tensor
x = torch.tensor([1, 3, 6, 10])
# Calculate second-order difference
y = torch.diff(x, n=2)
print(y)
# Create tensor
x = torch.tensor([1, 3, 6, 10])
# Calculate second-order difference
y = torch.diff(x, n=2)
print(y)
The output result is:
tensor([1, 1])
Example
import torch
# Create a 2D tensor
x = torch.tensor([[1, 3, 6, 10], [2, 5, 9, 14]])
# Calculate differences along the last dimension
y = torch.diff(x)
print(y)
# Create a 2D tensor
x = torch.tensor([[1, 3, 6, 10], [2, 5, 9, 14]])
# Calculate differences along the last dimension
y = torch.diff(x)
print(y)
The output result is:
tensor([[2, 3, 4],
[3, 4, 5]])
Other Extensions