PyTorch torch.diff Function


Pytorch torch 参考手册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 tensor
  • n: number of differences, defaults to 1
  • dim: dimension along which to calculate differences
  • prepend: prepend to input before calculation
  • append: 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)

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)

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)

The output result is:

tensor([[2, 3, 4],
        [3, 4, 5]])

Pytorch torch 参考手册PyTorch torch Reference Manual

Other Extensions