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.