Learn practical skills, build real-world projects, and advance your career
Updated 3 years ago
Learn Five Interesting Functions in PyTorch
We will check 5 interesting functions from PyTorch Documentation with several use cases each.
PyTorch is an open source machine learning library based on the Torch library, used for applications such as computer vision and natural language processing, primarily developed by Facebook's AI Research lab.( and about the chosen functions. )
- torch.zeros_like()
- torch.arange()
- torch.where()
- torch.randperm()
- torch.save()
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
Looking in links: https://download.pytorch.org/whl/torch_stable.html
Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (1.18.5)
Requirement already satisfied: torch==1.7.0+cpu in /usr/local/lib/python3.6/dist-packages (1.7.0+cpu)
Requirement already satisfied: torchvision==0.8.1+cpu in /usr/local/lib/python3.6/dist-packages (0.8.1+cpu)
Requirement already satisfied: torchaudio==0.7.0 in /usr/local/lib/python3.6/dist-packages (0.7.0)
Requirement already satisfied: dataclasses in /usr/local/lib/python3.6/dist-packages (from torch==1.7.0+cpu) (0.8)
Requirement already satisfied: typing-extensions in /usr/local/lib/python3.6/dist-packages (from torch==1.7.0+cpu) (3.7.4.3)
Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from torch==1.7.0+cpu) (0.16.0)
Requirement already satisfied: pillow>=4.1.1 in /usr/local/lib/python3.6/dist-packages (from torchvision==0.8.1+cpu) (7.0.0)
# Import torch and other required modules
import torch
Function 1 - torch.zeros_like
Returns a tensor filled with the scalar value 0, with the same size as input
# Example 1 - This examples create a Tensor t1 manually and then uses zeros_like to replicate it into a zeros tensor of same shape as the t1
t1 = torch.Tensor([[1, 2], [3, 4.]])
print(t1)
torch.zeros_like(t1)
tensor([[1., 2.],
[3., 4.]])
tensor([[0., 0.],
[0., 0.]])