Keeping the dimensions when using torch.diff on a tensor in pytorch

Question:

Suppose the following code:

a=torch.rand(size=(3,3,3), dtype=torch.float32)
a_diff=torch.diff(a, n=1, dim= 1, prepend=None, append=None).shape


print(a_diff)

torch.Size([3, 2, 3])

I would like to keep the dimensions like the original a with (3,3,3). How can I
append 0 to the beginning of the sequence so that the dimensions remain the same?

Asked By: freak11

||

Answers:

You can simply use the "prepend" parameter.

a = torch.rand(size = (3,3,3), dtype = torch.float32)
a_diff = torch.diff(a, n=1, dim= 1, prepend=torch.zeros((3,1,3)), append=None).shape

print(a_diff)

The result is torch.Size([3, 3, 3]).

Answered By: Ben Grossmann
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.