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

Introduction to Pytorch

Pytorch is an open source machine learning library based on the torch package. It was primarily developed by FaceBook's AI research team. They provide with end to end research framework. In addition to the framework they allow chaining of high-level nueral network modules since it supports Keras like API in its torch.nn (help in creating and training of the neural network) package.
Pytorch is mainly employed for application such as the Computer Vision (use of image processing algorithms to gain high-level understanding from digital images or videos) and Natural Language Processing (ability of a computer program to understand human language).

Some interesting functions used in torch package:-

  • torch.set_default_tensor_type(t)
  • torch.arange(start=0, end, step=1, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
  • torch.eye(n, m=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
  • new_full(size, fill_value, dtype=None, device=None, requires_grad=False)
  • torch.max(input, other, out=None)
# Import torch and other required modules
import torch

torch.set_default_tensor_type(t)

The tensor when declared by default will have the floating point (float32) datatype. This function in torch package can be used set other datatypes to the declared tensor.The torch package by default has nine CPU and nine GPU tensor types.

The parameters of the function are :-

  • t :- specify the datatype to which the tensor is to be converted.
import torch 
t1= torch.tensor([1,2., 3]).dtype
print("The datatype of tensor when declared is ",t1)
torch.set_default_tensor_type(torch.DoubleTensor)
t1=torch.tensor([1,2., 3]).dtype
print ("The datatype of tensor after default datatype is set ", t1)
The datatype of tensor when declared is torch.float64 The datatype of tensor after default datatype is set torch.float64

From the above block of code we can see that initially when a tensor is defined it is of type torch.float32. But after using the torch.set_default_tensor_type(t) function we set the datatype to torch.DoubleTensor.