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

All about PyTorch tensor operations

Pytorch is a python based scientific computing package that replaces numpy to use the power of GPUs and a deep learning research platform that provides maximum flexibility and speed.
In this article we will focus on tensors which are similar to NumPy’s ndarrays, with the addition being that Tensors can also be used on a GPU to accelerate computing.

We will illustrate five different tensor operations with examples on how various mathematical computations are performed.

  • torch.eye()
  • torch.arange()
  • torch.complex()
  • torch.mm()
  • torch.matrix_power()

Before we begin, let's install and import PyTorch

# 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.eye

In this function we will return a 2D tensor with the values of diagonals as 1 and other values as 0.
Here,the function expects two parameters — n and m .
If m is not specified, then it returns a 2D tensor of size nxn


torch.eye(3)
tensor([[1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.]])