Introduction to PyTorch

One of the most buzzing word now, Pytorch is an open source machine learning framework. It really helps ML Engineers to speed up the path from scientific research, prototyping to production deployment.
Primarily developed by artificial intelligence research group at Facebook.

Features

  1. Python First – Deep integration with python.
  2. TorchScript – TorchScript provides easy trasition between eager and graph mode.
  3. Distributed Training – Provides scalable distributed training.
  4. Tools & Libraries – Supports rich ecosystem of tools and libraries.

For installing it in your local environment, follow the link Pytorch Installation.

Now let us write some code.

Like in Tensorflow, tensors are the basic building block in Pytorch as well. It just does operations on these tensors. They are in simple terms arrays.

So let’s play with tenors first.

import pytorch    #Importing

x = torch.tensor([7,8])    #tensor of shape (7,8)
y = torch.tensor([1,3])

print(x*y)
tensor([7, 24])

Create an array with random values.

y = torch.rand([4,8])   

print(y)
tensor([[0.9544, 0.0342, 0.6851, 0.5822, 0.7935, 0.4456, 0.1526, 0.8647],
        [0.6902, 0.0097, 0.2952, 0.1352, 0.0959, 0.5416, 0.0672, 0.4175],
        [0.6413, 0.9672, 0.8147, 0.9910, 0.4149, 0.8251, 0.1746, 0.1744],
        [0.4711, 0.3098, 0.4967, 0.3206, 0.8353, 0.2429, 0.7968, 0.3986]])

Create an empty array.

x = torch.zeros([3,4]) 
print(x) 
tensor([[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]])

To look at the size of an array.

 x.shape 
torch.Size([3, 4])

Let see how we can modify the shape array.

y = torch.rand([4,8])
print(y) 
tensor([[0.9544, 0.0342, 0.6851, 0.5822, 0.7935, 0.4456, 0.1526, 0.8647],         
        [0.6902, 0.0097, 0.2952, 0.1352, 0.0959, 0.5416, 0.0672, 0.4175],         
        [0.6413, 0.9672, 0.8147, 0.9910, 0.4149, 0.8251, 0.1746, 0.1744],         
        [0.4711, 0.3098, 0.4967, 0.3206, 0.8353, 0.2429, 0.7968, 0.3986]]) 
y.view([2,16])
tensor([[0.9544, 0.0342, 0.6851, 0.5822, 0.7935, 0.4456, 0.1526, 0.8647,           
           0.6902, 0.0097, 0.2952, 0.1352, 0.0959, 0.5416, 0.0672, 0.4175],               
        [0.6413, 0.9672, 0.8147, 0.9910, 0.4149, 0.8251, 0.1746, 0.1744, 
           0.4711, 0.3098, 0.4967, 0.3206, 0.8353, 0.2429, 0.7968,0.3986]]) 

This will not actually modify the array y to shape (2,16). To save the new shape you need to reassign it to the original variable y.

y = y.view([2,16]) 
print(y) 

That’s all about its introduction, we will continue with more advance operation in the next article.

Thank you for reading.

You can read more on how Pytorch is different from Tensorflow in our article Tensorflow vs Pytorch.

Spread the knowledge

xpertup

Let's Expert Up

Leave a Reply

Your email address will not be published. Required fields are marked *