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

Pytorch Tensors

As a Deep Neural Networks library, Pytorch provides us automatic differentiation and GPU support for parallel operations on multidimensional arrays, in addition to all that Numpy provides.

Tensors in pytorch are basically what arrays in numpy are. We will explore some interesting tensor functions here.

  • torch.take
  • torch.unbind
  • torch.gather
  • torch.normal
  • torch.masked_select

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.take

Returns a new tensor with the elements of input at the given indices. The input tensor is treated as if it were viewed as a 1-D tensor. The result takes the same shape as the indices.

Explanation about example 1

T is a (2,4) tensor with integer values to be indexed and indices is a 1D tensor with the index locations we want the values at.

Torch.take() takes in these two as arguments and returns a new 1D tensor with the desired values.