Convert 3D Tensor to 4D Tensor in Pytorch
I had difficulty finding information on reshaping in PyTorch. Tensorflow is quite easy.

My tensor has shape torch.Size([3, 480, 480]).
I want to convert it to a 4D tensor with shape [1,3,480,480].
How do I do that?

You can use unsqueeze()

For example:

x = torch.zeros((4,4,4))   # Create 3D tensor 
x = x.unsqueeze(0)         # Add dimension as the first axis (1,4,4,4)


I've seen a few people use indexing with None to add a singular dimension as well. For example:

x = torch.zeros((4,4,4))   # Create 3D tensor 
print(x[None].shape)       #  (1,4,4,4)
print(x[:,None,:,:].shape) #  (4,1,4,4)
print(x[:,:,None,:].shape) #  (4,4,1,4)
print(x[:,:,:,None].shape) #  (4,4,4,1)


Personally, I prefer unsqueeze(), but it's good to be familiar with both.
