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

Pytorch🔦 101 with torch tensors:

This tutorial basically covers different PyTorch tensor functions which are really very essential when you are using Pytorch to perform different Deep Learning tasks. Actually Any PyTorch model(like- ANNs, CNNs) or operation can not process any array which is not a torch tensor. So, to convert those arrays, especially I am considering NumPy arrays we need to use some functions and there are also some fantastic and sssuuupppeeerr simple functions for mathematical operations and some deep learning utilities. So, much os talking, let's get the ball rolling with the table of contents-

Table of Content:

  1. torch.Tensor()
  2. torch.ones()
  3. torch.zeros()
  4. torch.rand()
  5. torch.manual_seed()
alt

Image from Unsplash by Hitesh Choudhary

Importing the required libraries:

import numpy as np
import torch 

torch.Tensor()

This is a PyTorch function which helps us to create PyTorch tensors or arrays. We just need to pass a NumPy array or a list inside the torch.Tensor() and boom, your PyTorch tensor is ready. Here I 1st created a list(CELL NO. 6) and then created a NumPy array(CELL NO. 7), after that, I converted the list and the disarray into torch tensors.

torch.from_numpy() is another method for converting a numpy array to torch tensors, we just need to pass that numpy array in that function to make it work.

We covered almost all the aspects of creating torch tensors from numpy array and lists,what if we need to create a numpy arrays from torch tensors? It is very simple, we just need to add .numpy() with the torch tensor.