Search code examples
pythonpytorchtensorzero-padding

padding zeroes to a tensor on both dimensions


I have a tensor t

1 2
3 4
5 6
7 8

And I would like to make it

0 0 0 0
0 1 2 0
0 3 4 0
0 5 6 0
0 7 8 0
0 0 0 0 

I tried stacking with new=torch.tensor([0. 0. 0. 0.]) tensor four times but that did not work.

t = torch.arange(8).reshape(1,4,2).float()
print(t)
new=torch.tensor([[0., 0., 0.,0.]])
print(new)
r = torch.stack([t,new])  # invalid argument 0: Tensors must have same number of dimensions: got 4 and 3
new=torch.tensor([[[0., 0., 0.,0.]]])
print(new)
r = torch.stack([t,new])  # invalid argument 0: Sizes of tensors must match except in dimension 0.

I also tried cat, that did not work either.


Solution

  • It is probably better to initialize an array of the desired shape first, and then add the data at the appropriate indices.

    import torch
    
    t = torch.arange(8).reshape(1,4,2).float()
    x = torch.zeros((1, t.shape[1]+2, t.shape[2]+2))
    x[:, 1:-1, 1:-1] = t
    
    print(x)
    

    On the other hand, if you just want to pad your tensor with zeroes (and not just add extra zeroes somewhere), you can use torch.nn.functional.pad:

    import torch
    
    t = torch.arange(8).reshape(1, 4, 2).float()
    x = torch.nn.functional.pad(t, (1, 1, 1, 1))
    
    print(x)