5

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!

secret
  • 505
  • 4
  • 16

2 Answers2

8

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])
Dishin H Goyani
  • 7,195
  • 3
  • 26
  • 37
1

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

KarelZe
  • 1,466
  • 1
  • 11
  • 21
Shai
  • 111,146
  • 38
  • 238
  • 371