• For any query, contact us at
  • +91-9872993883
  • +91-8283824812
  • info@ris-ai.com

Pytorch

Pytorch is an open source machine learning library based on the torch library used for applications such as computer vision and natural language processing.

Pytorch tensors

Pytorch defines a class called tensor(torch.tensor) to store and operations on homogeneous multidimensional rectangular array of number.

Tensors

Pytorch tensor is the fundamental unit of the pytorch framework whose operation are similar to python numpy array. Convert python list to pytorch tensor.

In [1]:
 import torch
 import numpy as np
 t =torch.tensor([[15., -33.,44.], [-81., -54., 55]])
 t
                
Out[1]:
tensor([[ 15., -33.,  44.],
[-81., -54.,  55.]])
                
In [2]:
t1=torch.tensor(np.array([[45, 27, 63], [144, 549, 72]]))
t1
                
Out[2]:
tensor([[ 45,  27,  63],
        [144, 549,  72]])
                
Creating different types of pytorch tensors
Pytorch zeros tensor
In [3]:
t2 =torch.zeros([3,4])
t2
                
Out[3]:
tensor([[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]])
                
Pytorch ones tensor
In [4]:
t4 =torch.ones([3,3])
t4
                
Out[4]:
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]])
                
Pytorch random tensor
In [5]:
t3 =torch.randn([3,3])
t3
                
Out[5]:
tensor([[-1.2749,  1.9119,  0.1540],
        [ 0.2169,  1.6054,  0.0332],
        [-0.2685, -0.8797,  2.6951]])
                

Simple join the tensor

In [6]:
x = torch.tensor([[45, 27, 63], [144, 549, 45]])
y = torch.tensor([[4, 5, 9], [5.4, 6.3, 9.1]])

t1 =torch.cat([x,y],dim=1)
t1
                
Out[6]:
tensor([[ 45.0000,  27.0000,  63.0000,   4.0000,   5.0000,   9.0000],
        [144.0000, 549.0000,  45.0000,   5.4000,   6.3000,   9.1000]])
                
Mathematical operations
Simple Add two matrix
In [7]:
import torch
import numpy as np
x =torch.tensor([[32,45,86],[33,65,73]])
y =torch.tensor([[22,33,21],[45,33,35]])
x1=torch.add(x,y)
x1
                
Out[7]:
tensor([[ 54,  78, 107],
        [ 78,  98, 108]])
                
Subtract two matrix
In [8]:
x2 =torch.tensor([[20,20,20],[20,20,20]])
x3 =torch.tensor([[45,66,45],[33,55,76]])
x4 =torch.sub(x,y)
x4
                
Out[8]:
tensor([[ 10,  12,  65],
        [-12,  32,  38]])
                
Multipy two matrix
In [9]:
x5 =torch.mul(x,y)
x5
                
Out[9]:
tensor([[ 704, 1485, 1806],
        [1485, 2145, 2555]])
                
Divide two matrix
In [10]:
x6 =torch.div(x,y)
x6
                
Out[10]:
tensor([[1.4545, 1.3636, 4.0952],
        [0.7333, 1.9697, 2.0857]])
                
FashionMNIST dataset
In the we have 70,000 images.In the training data we have 60,000 images and the test data we have 10,000 images.
How we can load the FashionMNIST dataset from torchvision
We load the FashionMNIST Dataset with the following parameters:
  1. root is the path where the train/test data is stored,
  2. train specifies training or test dataset
  3. download=True downloads the data from the internet if it’s not available at root.
  4. transform and target_transform specify the feature and label transformations
In [11]:
import torch
from torchvision import datasets
from torchvision.transforms import ToTensor
training_data = datasets.FashionMNIST(
    root="data",
    train=True,
    download=True,
    transform=ToTensor(),
)
                
In [12]:
test_data = datasets.FashionMNIST(
    root="data",
    train=False,
    download=True,
    transform=ToTensor(),
)
                
Visualizing the Dataset
We use matplotlib to visualize some samples in our training data.
In [13]:
import matplotlib.pyplot as plt
labels_map = {
    0: "T-Shirt",
    1: "Trouser",
    2: "Pullover",
    3: "Dress",
    4: "Coat",
    5: "Sandal",
    6: "Shirt",
    7: "Sneaker",
    8: "Bag",
    9: "Ankle Boot",
}
figure = plt.figure(figsize=(8, 8))
cols, rows = 3, 3
for i in range(1, cols * rows + 1):
    sample_idx = torch.randint(len(training_data), size=(1,)).item()
    img, label = training_data[sample_idx]
    figure.add_subplot(rows, cols, i)
    plt.title(labels_map[label])
    plt.axis("off")
    plt.imshow(img.squeeze(), cmap="gray")
plt.show()
                
Conclusion

Firstly i learn what is pytorch than i performed the basic operation i.e convert python list to pytorch tensor then pytorch zero tensor then ones tensor than random tensor then perfomed simple mathematical operation. then i performed how we can load the dataset from torchvision. then i performed visulization on the dataset with the help of matplotlib to visulize some images in our training dataset.

Resources You Will Ever Need