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

A beginner's guide to PyTorch

PyTorch is a Python-based library and is a powerful framework for deep learning. It is quite similar to Numpy so it will be easier to understand if you are familiar with Numpy. There are two main features which makes PyTorch a better framework for scientific computation and deep learning. These are accelerated computation and autograd property. Since in PyTorch everything is a tensor and unlike numpy array, tensors works with GPU which accelerate the computations and it also support numeric optimizations on mathematical expressions. It has the ability to automatically compute gradients (i.e., automatic differentiation) which is essential in training any DL model. This property is known as 'Autograd'. Like any other library, it comprises of a lot of functions and operations, which are mainly useful in executing deep learning tasks. In this blog, I will be covering some basic operations related to tensor (which are mentioned below).

  • torch.tensor()

  • torch.tensor.item()

  • tensor.view()

  • torch.from_numpy()

  • mm

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
import numpy as np
import pandas as pd

Function 1 - torch.tensor

Since every data is represented as a tensor, we will start by creating tensor. So, to create a tensor, one can use torch.tensor().

# Example 1 - Creating a 1-D tensor from a list
our_tensor = torch.tensor([i for i in range(6)])
our_tensor
tensor([0, 1, 2, 3, 4, 5])