How to make two tensors to be of the same shape

I have two tensors :
first = [A , B , 2048].
second = [C , D 2048]
Where A > C and B > D.
how can I padd the second tensor with zeros so it match the first tensor dimensions, and in generally does padding affectu accuracy ?

You could use F.pad:

A, B, C, D = 5, 4, 3, 2
a = torch.randn(A, B, 2)
b = torch.randn(C, D, 2)

out = F.pad(b, (0, 0, (B-D)//2, (B-D)//2, (A-C)//2, (A-C)//2))
print(out.shape == a.shape)

Note that F.pad pads starting from the last dimension.

This might be the case, but I think as long as you pad your tensors in a reasonable way, it shouldn’t matter.

1 Like