Equivalent of np.ptp()?

Title basically. Is there an equivalent of np.ptp in Pytorch?

I think there is no direct equivalent, but you can easily implement the function with

def ptp(t, axis):
  return t.max(axis).values - t.min(axis).values
1 Like

To match Numpy’s semantics, then the following is equivalent to numpy.ptp();

def ptp(input: Tensor, dim: Optional[int] = None, keepdim=False) -> Tensor:
    if dim is None:
        return input.max() - input.min()
    return input.max(dim, keepdim).values - input.min(dim, keepdim).values

x = torch.tensor([[4, 9, 2, 10], [6, 9, 7, 12]])
ptp(x, 1, True), ptp(x, 1), ptp(x, 0), ptp(x)
...
(tensor([[8],
         [6]]),
 tensor([8, 6]),
 tensor([2, 0, 5, 2]),
 tensor(10))