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

5 Powerful functions of Pytorch to speed up your workflow

PyTorch is an open source machine learning framework that speeds up the process of researching, prototyping and model deployment. PyTorch is primarily developed by Facebook's AI Research lab and available for free as an open-source software. PyTorch is used for a number of applications such as computer vision and natural language processing (also called NLP for short).

PyTorch is a very powerful library and provides a number of functions that can help you prototype or research faster. PyTorch provides a large number of functions and it is very hard to memorize the statement and working of all of them but here I am going to share 5 functions that can speed up your workflow and reduce the amount of code you write.

The functions that I am going to discuss are:

  • zeros_like
  • ones_like
  • randint
  • from_numpy
  • transpose

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 - zeros_like

torch.zeros_like(input)

  • The above functions returns a tensor filled with the scalar value 0, with the same size as input.
  • The function torch.zeros_like(input) is equivalent to torch.zeros(input.size(), dtype=input.dtype, layout=input.layout, device=input.device). You can see clearly the amount of code reduced by using the above function.
input_1 = torch.tensor([[2, 3, 4],[1,2,3]])
zero_tensor_1 = torch.zeros_like(input_1)
print(zero_tensor_1)
tensor([[0, 0, 0], [0, 0, 0]])