Learn practical skills, build real-world projects, and advance your career
Updated 3 years ago
5 Simple Functions to get started with PyTorch
PyToarch is an open-source machine learning library, which is primarily developed by Facebook's AI Research Lab. It has a wide array of applications, ranging from Computer Vision to Natural Language Processing etc.
In this notebook, a few important functions from the library is introduced, that helps with creating and modifying Tensors.
- torch.linspace
- torch.zeros_like
- torch.reshape
- torch.split
- torch.stack
Before we begin, let's install and import PyTorch
#@title
# 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
#@title
# Import torch and other required modules
import torch
Function 1 - torch.linspace
This is one of the most important function if you have to create a range of data.
Let us say you want a Tensor populated by integers from 1 to 10. Instead of typing them one by one like,
torch.tensor([1.,2.,3.,4.,5.,6.,7.,8.,9.,10.])
you can just use the torch.linspace()
to make one.
It takes the arguments, starting value, last value and the number of elements needed in the tensor.
# Example 1 - working
torch.linspace(1,10,10)
tensor([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])