Mathematical Operations on Tensors in PyTorch
We can perform various mathematical operations on tensors using Pytorch. The code for performing Mathematical operations is the same as in the case with NumPy arrays. Below is the code for performing the four basic operations in tensors.
Example 4:
Python3
# import torch module import torch # defining two tensors t1 = torch.tensor([ 1 , 2 , 3 , 4 ]) t2 = torch.tensor([ 5 , 6 , 7 , 8 ]) # adding two tensors print ( "tensor2 + tensor1" ) print (torch.add(t2, t1)) # subtracting two tensor print ( "\ntensor2 - tensor1" ) print (torch.sub(t2, t1)) # multiplying two tensors print ( "\ntensor2 * tensor1" ) print (torch.mul(t2, t1)) # diving two tensors print ( "\ntensor2 / tensor1" ) print (torch.div(t2, t1)) |
Output:
tensor2 + tensor1
tensor([ 6, 8, 10, 12])
tensor2 - tensor1
tensor([4, 4, 4, 4])
tensor2 * tensor1
tensor([ 5, 12, 21, 32])
tensor2 / tensor1
tensor([5.0000, 3.0000, 2.3333, 2.0000])
For getting into further in-depth matrix multiplication using Pytorch . You can refer to this article –
What is PyTorch ?
Deep Learning is a branch of Machine Learning where algorithms are written that mimic the functioning of a human brain. The most commonly used libraries in deep learning are Tensorflow and PyTorch. Pytorch is an open-source deep learning framework available with a Python and C++ interface. The PyTorch resides inside the torch module. In PyTorch, the data that has to be processed is input in the form of a tensor.