Learn practical skills, build real-world projects, and advance your career
# Jovian Commit Essentials
# Please retain and execute this cell without modifying the contents for `jovian.commit` to work
!pip install jovian --upgrade -q
import jovian
jovian.utils.colab.set_colab_file_id('1M_b_-GegiBFGJM0-39IKqIaaw9lwyEXb')

Essential Pytorch Functions for Pytorchers

A quick look at the Pytorch documentation, reveals a wealth of functions which we'll be needing as we progress in machine learning. Some of the essential functions include

  • torch.hstack()

  • torch.where()

  • torch.unsqueeze()

  • torch.div()

  • torch.acos()

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.hstack()

This function takes corresponding columns of 2 or more Tensors, and stack them horizontally.

ie, all the elements in the corresponding columns are stacked together to form a single row.

As a result of this, the total number of rows in new tensor equals the number of columns in stacked tensors.

Accordingly, the total number of columns in new tensor equals the combined number of elements in a corresponding column.

calling the torch.hstack function

the hstack function takes a tuple of tensors a,b...n and return a horizontally stacked tensor

you can call the function by running torch.hstack((a,b,...))

it's important to note that the tensors should be in a tuple. If you don't put the tensors in a tuple, your code will return an error.

Let's take a look at some examples