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

5 Simple yet pretty useful Pytorch functions.

"Pytorch. An open source machine learning framework that accelerates the path from research prototyping to production deployment."1

As modern fields move toward artificial intelligence, more powerful, fast, and flexible computing is required. Pytorch has been designed to be a booster library to perform dynamic models and large-scale deep learning frameworks. Pytorch has been portrayed by thousands of artificial intelligence experts as the most optimized high-performance tensor library for deep learning tasks.
The Pytorch library can be used in the Python environment or C++. It was created based on the Torch tool provided by Facebook's Artificial Intelligence Research Group.
The most frequent applications that use this library are neural networks, natural language processing, computer vision including image processing, sensor data processing, among many others.

The following five torch functions are simple yet very practical and useful that we can deploy at the time of modeling a process or optimize a task.

  • torch.unbind()
  • torch.full()
  • torch.ones_like()
  • torch.view()
  • torch.view_as()

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.unbind()

This function splits a given tensor in a specific number of small tensors according to its original dimension. By default, the torch.unbind( ) function splits a tensor according to the number of rows, but we can select along which dimension we want it to work.

a=torch.tensor([[1,2],[3,4],[5,6]])
a, a.shape
(tensor([[1, 2],
         [3, 4],
         [5, 6]]), torch.Size([3, 2]))