Learn practical skills, build real-world projects, and advance your career

Five handy tensor operations with PyTorch to use in every project

Tensors and the operations between them are the basis for PyTorch, and any library focussed on deep learning. This short notebook aims to provide examples for five simple functions integrated in PyTorch that allow for some useful tensor operations.

  • torch.cat
  • torch.stack
  • torch.unsqueeze
  • torch.reshape
  • torch.as_tensor
# Uncomment and run the appropriate command for your operating system, if required

# Linux / Binder
# !pip install numpy torch==1.7.0+cpu torchvision==0.8.1+cpu torchaudio==0.7.0 -f https://download.pytorch.org/whl/torch_stable.html

# Windows
# !pip install numpy torch==1.7.0+cpu torchvision==0.8.1+cpu torchaudio==0.7.0 -f https://download.pytorch.org/whl/torch_stable.html

# MacOS
# !pip install numpy torch torchvision torchaudio
# Import torch and other required modules
import torch

Function 1 - torch.cat

This function concatenates a sequence of tensors over the specified dimension. All the tensors must be of the same shape, except in the concatenating dimension.

# Example 1 - working (change this)
x = torch.full((2,2), fill_value=0)
y = torch.full((2,2), fill_value=1)
torch.cat((x, y), dim=0)
tensor([[0, 0],
        [0, 0],
        [1, 1],
        [1, 1]])