This article will illustrate different methods to perform matrix multiplication in PyTorch.
How to Perform Matrix Multiplication in PyTorch?
To multiply matrices in PyTorch, different methods are used:
- Method 1: Using “torch.matmul()” Method
- Method 2: Using “torch.mm()” Method
- Method 3: Using “@” Operator
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 matrix multiplication:
Step 2: Create Matrices(Tensors)
Then, create two desired matrices and print their elements. Here, we are creating “M1” and “M2” matrices (tensors) from the list using the “torch.tensor()” function:
M2 = torch.tensor([[4, 8],[5, 0],[6, 11]])
print(M1)
print(M2)
This has created two matrices as seen below:
Now, we will use different methods to multiply these matrices.
Method 1: Multiply Matrices Using “torch.matmul()” Method
The “torch.matmul()” method can handle both 2D and higher-dimensional tensors. To multiply matrices, use the “torch.matmul()” method and provide desired tensors as a parameter. Here, we are multiplying “M1” and “M2” matrices (tensors) and storing their product in the “prod” variable:
print(prod)
In the below output, the product of two matrices can be seen:
Method 2: Multiply Matrices Using “torch.mm()” Method
PyTorch provides a “torch.mm()” method that can only handle 2D tensors and performs a simple matrix multiplication. To multiply two matrices using the “torch.mm()” method, pass the desired matrices as parameter:
print(prod)
The below screenshot shows the product of “M1” and “M2” matrices:
Method 3: Multiply Matrices Using “@” Operator
Users can also use the “@” operator to multiply two matrices. It is a short form of the “torch.matmul()” method:
print(prod)
According to the below output the matrix multiplication has been performed successfully:
We have efficiently explained the methods to perform the matrix multiplication in PyTorch.
Note: You can access our Google Colab Notebook at this link.
Conclusion
To perform the matrix multiplication in PyTorch, first, import the “torch” library and create two desired matrices (tensors). Then, use the “torch.matmul()” or “torch.mm()” method or “@” operator to multiply two matrices and display the results. This article has illustrated different methods to perform matrix multiplication in PyTorch.