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

5 useful PyTorch function

Here are some basic PyTorch function for beginner Data Scientists

  • count_nonzero
  • Argmin/max
  • rsqrt
  • unique
  • chunk

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
Requirement already satisfied: numpy in /Users/EricTang/opt/anaconda3/lib/python3.8/site-packages (1.18.5) Requirement already satisfied: torch in /Users/EricTang/opt/anaconda3/lib/python3.8/site-packages (1.7.0) Requirement already satisfied: torchvision in /Users/EricTang/opt/anaconda3/lib/python3.8/site-packages (0.8.1) Requirement already satisfied: torchaudio in /Users/EricTang/opt/anaconda3/lib/python3.8/site-packages (0.7.0) Requirement already satisfied: dataclasses in /Users/EricTang/opt/anaconda3/lib/python3.8/site-packages (from torch) (0.6) Requirement already satisfied: future in /Users/EricTang/opt/anaconda3/lib/python3.8/site-packages (from torch) (0.18.2) Requirement already satisfied: typing-extensions in /Users/EricTang/opt/anaconda3/lib/python3.8/site-packages (from torch) (3.7.4.2) Requirement already satisfied: pillow>=4.1.1 in /Users/EricTang/opt/anaconda3/lib/python3.8/site-packages (from torchvision) (7.2.0)
# Import torch and other required modules
import torch

Function 1 - torch.count_nonzero (change this)

This function counts the numbers of non zero elements in the tensor

# Example 1 - working 
t1= torch.tensor([[1,2,3.,0,5,0], 
                  [3, 4.,0,0,1,3],
                 [3, 4.,0,0,1,3]])
torch.count_nonzero(t1)
tensor(12)