torch.diff — PyTorch 2.7 documentation (original) (raw)

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

Computes the n-th forward difference along the given dimension.

The first-order differences are given by out[i] = input[i + 1] - input[i]. Higher-order differences are calculated by using torch.diff() recursively.

Parameters

Keyword Arguments

out (Tensor, optional) – the output tensor.

Example:

a = torch.tensor([1, 3, 2]) torch.diff(a) tensor([ 2, -1]) b = torch.tensor([4, 5]) torch.diff(a, append=b) tensor([ 2, -1, 2, 1]) c = torch.tensor([[1, 2, 3], [3, 4, 5]]) torch.diff(c, dim=0) tensor([[2, 2, 2]]) torch.diff(c, dim=1) tensor([[1, 1], [1, 1]])