Pytorch - Basics

[This Tutorial is under development....... Please don't use it right now]


This Tutorial is about Pytorch Basics : No other prereqisite is expected beyond basic python programming

 

Install using instuction given here : https://pytorch.org/

 

To check which version of pytorch you have installed 

import torch
print(torch.__version__)

Output:

1.7.0+cu110

As you can see above i have installed PyTorch 1.7.0 (with cuda support). In case you don't have a GPU in your machine you can still follow this tutorial even with CPU version.

 

Tensor is a multi dimensional matrix similar to numpy ndarray

scalar = zero dimnesional tensor

vector = 1-D tensor

2D matrix  = 2D tensor

Multi Dimensional matrix =  Multi dimensional tensor

A colored image can be considered as 3D tensor = (height) x (width) x (3 color channel)

A grayscale image can be considered as 2D tensor = (height) x (width) x(1 channel) 

 

How to initialize a tensor

import torch
x = torch.tensor([1,2])
y = torch.tensor([[3,4], [5,6]])

Get shape of the tensor objects

print(x.shape)
print(y.shape)

Output:

torch.Size([2])
torch.Size([2, 2])

 

The datatype of all elements of a tensor is always same that mean if some tensor contain data of different data type it will be coerced into most generic type

Other ways to initialize a tensor

1.  Using inbuilt function

(a) zeros

import torch
print(torch.zeros((2,3)))

Ouput

tensor([[0., 0., 0.],
        [0., 0., 0.]])

(b) Ones

import torch
print(torch.ones((2,3)))

Output:

tensor([[1., 1., 1.],
        [1., 1., 1.]])

(c) Random Integer

import torch
print(torch.randint(low=0, high=5, size=(2,3)))

Output:

tensor([[4, 1, 3],
        [3, 0, 1]])

Low value is inclusive

High is not inclusive

(d) Normal random distribution

import torch
print(torch.rand((2,3)))

Output:

tensor([[0.7927, 0.7731, 0.0402],
        [0.8214, 0.2021, 0.5342]])

 

2. By converting a numpy array into a tensor

import torch
import numpy as np

x = np.array([[2,4,6], [3,5,7]])
y = torch.tensor(x)
print(x)
print(y)

Output:

[[2 4 6]
 [3 5 7]]
tensor([[2, 4, 6],
        [3, 5, 7]])