How to pad a tensor? (AssertionError: Padding length must be divisible by 2)


(torrable) #1

Hi,

I have a tensor, t = torch.Size([71, 32, 1])

This means I have 32 , 71 dimensional vectors or 32 x 71, 1 dimensional vectors.

I want to create 32, 100 dimensional vectors i.e. 32 x 100, 1 dimensional vectors.

The padding, F.pad, how should it be used in this case?

I Keep getting:

AssertionError: Padding length must be divisible by 2.


(Vahid Mirjalili) #2

The pad argument needs to be a tuple whose size is divisible by 2. Also, note that it operates on dimensions of the input tensor in a backward fashion (from last dimension to the first dimension). For example, if you pass pad=(1, 1) it will pad the last dimension by 1 on each side, so that will result in size [71, 32, 3].

So, since you have [71, 32, 1] and you want to pad this tensor by 29 on the first dimension, then you should use pad=(0, 0, 0, 0, 14, 15):

a = torch.randn((71, 32, 1))
# a.shape --> torch.Size([71, 32, 1])
F.pad(a, pad=(0, 0, 0, 0, 14,15), mode="constant", value=0).shape

which will result in the following size:

torch.Size([100, 32, 1])