This video will show you how to add a new dimension to the beginning of a PyTorch tensor by using None-style indexing.
First, we import PyTorch.
import torch
Then we print the PyTorch version we are using.
print(torch.__version__)
We are using PyTorch 0.4.0.
Let’s now create a PyTorch tensor using the PyTorch Tensor operation and we’re going to have the dimensions be 2x4x6x8, and we’re going to assign this uninitialized tensor to the Python variable pt_empty_tensor_ex.
pt_empty_tensor_ex = torch.Tensor(2,4,6,8)
Let’s check what dimensions our pt_empty_tensor_ex Python variable tensor has.
print(pt_empty_tensor_ex.size())
We see the dimensions are 2x4x6x8.
What we want to do next is we want to add a new dimension to the beginning of our PyTorch tensor.
The way we’ll do this is by using the None-style indexing.
pt_extend_beginning_tensor_ex = pt_empty_tensor_ex[None,:]
So we’re going to use a capital N, and for the first index we’re going to say None, and we say comma, and then we’re going to use a colon.
The colon notation means that we want the rest of the tensor.
The None tells PyTorch that we want a new axis for the tensor to be assigned at the very beginning.
We assign that result to the pt_extend_beginning_tensor_ex Python variable.
Let’s check the size of the tensor because we told PyTorch to create a new axis at the beginning of it.
print(pt_extend_beginning_tensor_ex.size())
When we do this, we see that the dimensions of the tensor are now 1x2x4x6x8.
Before, it was 2x4x6x8, so we see that we have the new axis here.
Perfect - We were able to add a new dimension to the beginning of a PyTorch tensor by using None-style indexing.