secret
secret

Reputation: 515

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!

Upvotes: 5

Views: 8456

Answers (3)

Mohit Burkule
Mohit Burkule

Reputation: 162

CenterCrop can do that for you [examples]

import torch
from torchvision.transforms import CenterCrop

# Initialize CenterCrop with the target size of (70, 42)
crop_transform = CenterCrop([70, 42])

# Example usage
torch.manual_seed(0)
for _ in range(5):
    X = torch.randint(50, 71, (1,)).item()  # X is in range 50 to 70
    tensor = torch.randn(X, 42)  # Random tensor with shape (X, 42)
    padded_tensor = crop_transform(tensor)  # Apply CenterCrop for padding
    print(f"Original shape: {tensor.shape}, Padded shape: {padded_tensor.shape}")

with output



Original shape: torch.Size([56, 42]), Padded shape: torch.Size([70, 42])
Original shape: torch.Size([67, 42]), Padded shape: torch.Size([70, 42])
Original shape: torch.Size([60, 42]), Padded shape: torch.Size([70, 42])
Original shape: torch.Size([52, 42]), Padded shape: torch.Size([70, 42])
Original shape: torch.Size([50, 42]), Padded shape: torch.Size([70, 42])

You can also look at Letterbox transforms but it works slightly differently

Letterbox transforms maintain the aspect ratio of the image while adding padding, so the padding is usually asymmetric and proportional to the image's dimensions. In contrast, CenterCrop either pads or crops the tensor centrally without worrying about the aspect ratio.

Upvotes: 0

Shai
Shai

Reputation: 114786

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

Upvotes: 2

Dishin H Goyani
Dishin H Goyani

Reputation: 7693

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])

Upvotes: 8

Related Questions