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

Exploring the pytorch functions

Exploring and learning various functions of pytorch.

Pytorch is a open source python library used for various machine learning applications such as Natural language processing, Image processing etc. Now days pytorch is most popular machine learning library of the python to create small scale model. As we all know pytorch is created by and strongly supported by facebook but as pytorch is open sourse it can be used by anyone with knowledge of the pytorch. Pytorch library is generally used for small working model of the algorithm and tensorflow is used for bigger model. But this is changing now days because there is big change in pytorch since its inception.

  • index_copy()
  • index_fill()
  • torch.pow()
  • torch.max()
  • torch.bitwise_and()
# Import torch and other required modules
import torch

Function 1 - tensor.index_copy()

index_copy() function fills the element of one tensor into another tensor index wise. This function takes three arguments; first one is dim, this argument is used to determine weather we want to copy element column wise or row wise. when dim=0 elements are copied row wise and when dim=1 elements are copied column wise. second argument is index, this argument gives index of tensor to the function in which we want to copy the elements. Generally index is another tensor which gives either column index or the row index. Third argument is actual tensor from which we want to copy aur elements or row or columns. This function takes row or column on the original tensor indexed by index tensor and copy that into new tensor. To work this function respective rows of both tensor should be same if we want to copy rows otherwise column need to be equal

# Example 1 - working (change this)
temp=torch.zeros(5,3)
print('temp tensor of zeros\n',temp)
k=torch.tensor([[1,2,3],[4,5,6],[7,8,9]],dtype=torch.float)
index=torch.tensor([0,4,2])
print('\nAfter index_copy() function')
temp.index_copy(0,index,k)
temp tensor of zeros tensor([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]) After index_copy() function
tensor([[1., 2., 3.],
        [0., 0., 0.],
        [7., 8., 9.],
        [0., 0., 0.],
        [4., 5., 6.]])

In this example we copy content of the tensor k into tensor temp. index_copy() method cant create new tensor it copy elements into self tensor which means we need to provide the tensor to the method. In this example we copy first row of k into first row of the temp and then second row of k into fifth row of the temp tensor. Index of the temp tensor is given in the index tensor.