6/02/2023

torch tensor padding example code:

 refer to code:


.

import torch
import torch.nn.functional as F

tensor = torch.randn(2, 3, 4) # Original tensor
print("Original tensor shape:", tensor.shape)

# Case 1: Pad the last dimension (dimension -1) -> resulting shape: [2, 3, 8]
padding_size = 4
padded_tensor = F.pad(tensor, (padding_size, 0)) # Add padding to the left of the last dimension
print("Case 1 tensor shape:", padded_tensor.shape)

# Case 2: Pad the second-to-last dimension (dimension -2) -> resulting shape: [2, 8, 4]
padding_size = 5
padded_tensor = F.pad(tensor, (0, 0, padding_size, 0)) # Add padding to the left of the second-to-last dimension
print("Case 2 tensor shape:", padded_tensor.shape)

# Case 3: Pad the first dimension (dimension 0) -> resulting shape: [7, 3, 4]
padding_size = 5
padded_tensor = F.pad(tensor, (0, 0, 0, 0, padding_size, 0)) # Add padding to the left of the first dimension
print("Case 3 tensor shape:", padded_tensor.shape)

..


www.marearts.com

Thank you. ๐Ÿ™‡๐Ÿป‍♂️

No comments:

Post a Comment