简体   繁体   中英

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

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?

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]) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM