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

Some Interesting Pytorch Functions

PyTorch is an open source machine learning library based on the Torch library, used for applications such as computer vision and natural language processing. It is a free and open source software. The functions I have chosen to describe and varied ones but are useful in many cases like problem solving, math functions etc.

  • torch.combinations
  • torch.linspace
  • torch.reshape
  • torch.where
  • torch.unique

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.combinations(input, r=2, with_replacement=False)

This function computes combinations of length r of the given tensor input and returns a tensor of all those combinations.

Parameters:

  • input (Tensor) – 1D vector.

  • r (int, optional) – number of elements to combine (default = 2)

  • with_replacement (boolean, optional) – whether to allow duplication in combination (default = False)

Return Type : Tensor

# Example 1 - working
a = [5, 8, 10, 14]
tensor_a = torch.tensor(a) # converts the list to a tensor using the torch.tensor function
torch.combinations(tensor_a, r=3)
#torch.combinations(tensor_a, with_replacement=True)
tensor([[ 5,  8, 10],
        [ 5,  8, 14],
        [ 5, 10, 14],
        [ 8, 10, 14]])