pytorch gradient / derivative / difference along axis like numpy.diff

A 1D convolution with a fixed filter should do the trick:

filter = torch.nn.Conv1d(in_channels=1, out_channels=1, kernel_size=2, stride=1, padding=1, groups=1, bias=False)
kernel = np.array([-1.0, 1.0])
kernel = torch.from_numpy(kernel).view(1,1,2)
filter.weight.data = kernel
filter.weight.requires_grad = False

Then use filter like you would any other layer in torch.nn.

Also, you might want to change padding to suit your specific needs.


There appears to be a simpler solution to this (as I needed a similarly), referenced here: https://discuss.pytorch.org/t/equivalent-function-like-numpy-diff-in-pytorch/35327/2

diff = x[1:] - x[:-1]

which can be done along different dimensions such as

diff = polygon[:, 1:] - polygon[:, :-1]

I would recommend writing a unit test that verifies identical behavior though.