'Padding a tensor until reaching required size

I'm working with certian tensors with shape of (X,42) while X can be in a range between 50 to 70. I want to pad each tensor that I get until it reaches a size of 70. so all tensors will be (70,42). is there anyway to do this when I the begining size is a variable X? thanks for the help!



Solution 1:[1]

Use torch.nn.functional.pad - Pads tensor.

import torch
import torch.nn.functional as F

source = torch.rand((3,42))
source.shape
>>> torch.Size([3, 42])
# here, pad = (padding_left, padding_right, padding_top, padding_bottom)
source_pad = F.pad(source, pad=(0, 0, 0, 70 - source.shape[0]))
source_pad.shape
>>> torch.Size([70, 42])

Solution 2:[2]

You can easily do so by:

pad_x = torch.zeros((70, x.size(1)), device=x.device, dtype=x.dtype)
pad_x[:x.size(0), :] = x

This will give you x_pad with zero padding at the end of x

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 KarelZe