This blog will illustrate different methods to perform the subtraction operation on tensors in PyTorch.
How to Perform Subtraction Operation on Tensors in PyTorch?
To perform the subtraction operation on tensors in PyTorch, different methods are used:
However, users need to follow the provided steps first to use these methods:
Step 1: Import PyTorch Library
First, import the βtorchβ library to perform the subtraction operation:
Step 2: Create Tensors
Then, create two desired tensors and print their elements. Here, we are creating two simple tensors βtens1β and βtens2β from the list using the βtorch.tensor()β function:
tens2 = torch.tensor([3, 9, 5])
print(tens1)
print(tens2)
This has created two tensors as seen below:
Now, we will use different methods to perform subtraction on these tensors.
Method 1: Subtract Tensors Using β-β Operator
To subtract two tensors, simply use the β–β operator and store the differences in a variable. Then, print that variable. Here, we are subtracting βtens1β and βtens2β and storing the result in the βsubβ variable:
print(sub)
Upon doing so, the subtraction of the two tensors has been calculated:
Alternatively, users can directly subtract tensors and print their differences without using the third variable:
The below output shows the subtraction of two tensors:
Method 2: Subtract Tensors Using βtorch.subtract()β Method
PyTorch provides the βtorch.subtract()β method to subtract desired tensors. Here, we are subtracting βtens1β and βtens2β tensors using the βtorch.subtract()β method and storing their differences in the βsubβ variable:
print(sub)
In the below output, the subtraction of two tensors can be seen:
Alternatively, directly subtract tensors and print their differences in one step:
It can be observed that the subtraction operation has been successfully performed on two tensors:
Bonus Tip: How to Find Cumulative Sum of Differences?
Users can also calculate the sum of the values of the resultant tensor:
The below output displays the sum of β1β, β-8β and β2β which is β-5β:
We have efficiently explained the subtraction operation methods on tensors in PyTorch.
Note: You can access our Google Colab Notebook at this link.
Conclusion
To perform the subtraction operation on tensors in PyTorch, first, import the βtorchβ library and create two desired tensors. After that, use the β–β operator or βtorch.subtract()β method to subtract the tensors and display the results. This blog has illustrated different methods to perform the subtraction operation on tensors in PyTorch.