Torch Transpose - Use PyTorch Transpose ( torch.transpose ) to change the order of dimensions in a tensor

Torch Transpose - Use PyTorch Transpose ( torch.transpose ) to change the order of dimensions in a tensor.

Torch Transpose - Use PyTorch Transpose ( torch.transpose ) to change the order of dimensions in a tensor.

Video Transcript


This video will show you how to Torch Transpose.


Specifically, we will use PyTorch Transpose ( torch.transpose function) to change the order of dimensions in a tensor.


First, we import PyTorch.

import torch


Then we check the PyTorch version we are using

print(torch.__version__)

We are using PyTorch version 2.0.0


Next, let's create a PyTorch Tensor full of integers numbers:

tensor = torch.tensor([[1, 2, 3],
                          [4, 5, 6]])


To confirm that it's a PyTorch integer tensor, let's use the PyTorch dtype method to check the tensor's data type attribute

tensor.dtype

We can see that it's "torch.int64" which is a 64-bit integer that is signed.


Because we wrote our tensor manually, we know the dimensions are 2 rows by 3 columns.


However, because transposing tensors in PyTorch is a common operation when working with multi-dimensional data, let's double check the dimensions to make sure.


We use the PyTorch Size operation TORCH.TENSOR.SIZE

tensor.size()

We see that we get that the size of the tensor is a 2 by 3.


When we do the Torch Transpose we should then be able to check that the new dimensions will be 3 by 2.


Great, now let's now use PyTorch Transpose ( torch.transpose function) to change the order of dimensions of our tensor.

transposed_tensor = torch.transpose(tensor, 0, 1)


Note that the parameters are - input (Tensor) – the input tensor. - dim0 (int) – the first dimension to be transposed - dim1 (int) – the second dimension to be transposed


If the tensor was 0 dimensional, then it would just return itself.

If the tensor was 1 dimensional, then it would also just return itself.

In our case, because we are transposing a multi-dimensional tensor, we need to put some numbers in.


Now that we've used torch.transpose to do a PyTorch Transpose, let's look at the results:

print(transposed_tensor)


Then print our original tensor

print(tensor)

We can see that we have transposed the tensor.


Lastly, just to double check what we are seeing, let's check the dimensions of the transposed tensor.

transposed_tensor.size()

We see that we get that the size of the tensor is a 3 by 2, where before we had a 2 by 3 tensor.


Perfect!


We used PyTorch Transpose ( torch.transpose function ) to change the order of dimensions in a tensor.

Receive the Data Science Weekly Newsletter every Thursday

Easy to unsubscribe at any time. Your e-mail address is safe.