This blog will illustrate different methods to perform the multiplication operation on tensors in PyTorch.
How to Perform Multiplication Operation on Tensors in PyTorch?
To perform the multiplication 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 multiplication 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 multiply these tensors’ values.
Method 1: Multiply Tensors Using “*” Operator
To multiply two tensors, simply use the “*” operator and store their product in a variable. Then, print that variable. Here, we are multiplying “tens1” and “tens2” and storing their product in the “mul” variable:
print(mul)
Subsequently, the product of two tensors has been calculated:
Alternatively, users can directly multiply and print their product without using the third variable:
The below output shows the product of two tensors:
Method 2: Multiply Tensors Using “torch.mul()” Method
PyTorch provides the “torch.mul()” method to multiply desired tensors. Here, we are multiplying “tens1” and “tens2” tensors using the “torch.mul()” method and storing their product in the “mul” variable:
print(mul)
In the below output, the product of two tensors can be seen:
Alternatively, multiply tensors and print their product at once:
It can be observed that the multiplication operation has been performed on two tensors:
Bonus Tip: How to Find Dot Product for Tensors?
Users can also calculate the dot product of the tensors using the “dot()” method:
The below output shows the dot product of “tens1” and “tens2” tensors:
We have efficiently explained the methods to perform the multiplication operation on tensors in PyTorch.
Note: You can access our Google Colab Notebook at this link.
Conclusion
To perform the multiplication operation on tensors in PyTorch, first, import the “torch” library and create two desired tensors. After that, use the “*” operator or “torch.mul()” method to multiply two tensors and display the results. This blog has illustrated different methods to perform the multiplication operation on tensors in PyTorch.