A Beginner-Friendly Guide to PyTorch Library ,PyTorch Tensor functions and How it Works from Scratch

Getting started with PyTorch and Basic PyTorch Tensor operations

An short introduction about PyTorch and about the chosen functions.PyTorch is an open-source machine learning library for Python, based on Torch, used for applications such as natural language processing. It is primarily developed by Facebook's artificial-intelligence research group, and Uber's "Pyro" Probabilistic programming language software is built on it.

Below are some Tensor functions in PyTorch Library:

  • torch.add
  • torch.ceil
  • torch.ones
  • torch.eye
  • torch.clamp
# Import torch and other required modules
import torch

Function 1 - torch.add

PyTorch torch.add() method adds a constant value to each element of the input tensor and returns a new modified tensor.

# Example 1 - working (change this)
x = torch.Tensor(2, 3)  # An un-initialized Tensor object. x holds garbage data.
y = torch.rand(2, 3)    # Initialize with random values
z = torch.add(x, y)
print(x)
print(y) 
print(z)  
tensor([[6.4450e-36, 0.0000e+00, 3.3631e-44], [0.0000e+00, nan, 6.1657e-44]]) tensor([[0.6001, 0.5941, 0.9597], [0.4083, 0.8170, 0.6761]]) tensor([[0.6001, 0.5941, 0.9597], [0.4083, nan, 0.6761]])

The above example returns a new modified tensor 'z' with the sum of elements in the unintialised tensor objects 'x' , 'y'