In PyTorch, transposing a tensor is a common operation that can be easily done using the torch.transpose() function or the T attribute for 2D tensors. The transpose() function is more versatile as it works with tensors of any dimension, allowing you to specify which dimensions to swap.
torch.transpose()For a tensor of any dimension, use torch.transpose(input, dim0, dim1), where input is the tensor you want to transpose, and dim0 and dim1 are the dimensions you want to swap.
import torch # Create a tensor x = torch.randn(2, 3, 4) # Example tensor of shape [2, 3, 4] # Transpose the tensor y = torch.transpose(x, 0, 1) # Swaps dimension 0 with dimension 1 print("Original shape:", x.shape) print("Transposed shape:", y.shape) In this example, x is a 3D tensor, and torch.transpose(x, 0, 1) swaps the first and second dimensions, resulting in a tensor of shape [3, 2, 4].
.T for 2D TensorsFor 2D tensors, you can use the T attribute, which is a shorthand for transposing 2D tensors. It's equivalent to torch.transpose(input, 0, 1) but can only be used for 2D tensors.
# Create a 2D tensor x = torch.randn(2, 3) # Example tensor of shape [2, 3] # Transpose the tensor y = x.T print("Original shape:", x.shape) print("Transposed shape:", y.shape) In this case, x.T transposes the 2D tensor x, changing its shape from [2, 3] to [3, 2].
torch.permute, which allows you to rearrange the dimensions of a tensor in any order.azure-cosmosdb uidatepicker thumbnails urlconnection database ios9 text var tcp npm