# Matrix multiplication in Python using Pytorch

Hey guys, in this post we will see the matrix multiplication in Python using Pytorch. A general way to multiply matrices is by using nested loops. We can also use NumPy arrays for matrix multiplication. In this tutorial, however, we will learn about the multiplication of matrices using the Python library Pytorch.

## Multiplication of matrices in Python using Pytorch

Pytorch has some built-in methods that can be used to directly multiply two matrices. Some of these have been discussed here.

### Using torch.mm()

Have a look at the below Python Program for matrix multiplication.

import torch li1 = [ [1, 3, 5], [2, 4, 6], [7, 8, 9]] li2 = [ [1, 3, 5], [2, 4, 6], [7, 8, 9]] li1 = torch.Tensor(li1).view(3,3) li2 = torch.Tensor(li2).view(3,3) print(li1) print(li2) print(torch.mm(li1,li2))

Output:

tensor([[1., 3., 5.], [2., 4., 6.], [7., 8., 9.]]) tensor([[1., 3., 5.], [2., 4., 6.], [7., 8., 9.]]) tensor([[ 42., 55., 68.], [ 52., 70., 88.], [ 86., 125., 164.]])

Now let’s try to understand every bit of the above code. First, we have imported the torch module which we will need to use in our program. Then we have initialized two 2-dimensional lists to store elements of the matrices that are to be multiplied. Then we convert these lists into tensors as torch methods work for tensor objects. Now that we have the matrix in the proper format, all we have to use the built-in method ** torch.mm()** to do the matrix multiplication operation on these matrices. You can see the output and verify it to clear any doubt.

We can also use this method in the following way as shown in the below code.

print(li1.mm(li2))

This will produce the same result.

### Using torch.matmul()

The same output can be generated using the torch.matmul() method. See the given example program for a better understanding.

import torch li1 = [ [1, 3, 5], [2, 4, 6], [7, 8, 9]] li2 = [ [1, 3, 5], [2, 4, 6], [7, 8, 9]] li1 = torch.Tensor(li1).view(3,3) li2 = torch.Tensor(li2).view(3,3) print(li1) print(li2) #print(li1.matmul(li2)) or print(torch.matmul(li1,li2))

Output:

tensor([[1., 3., 5.], [2., 4., 6.], [7., 8., 9.]]) tensor([[1., 3., 5.], [2., 4., 6.], [7., 8., 9.]]) tensor([[ 42., 55., 68.], [ 52., 70., 88.], [ 86., 125., 164.]])

### Using @

To keep things simple, we can also use the following approach to achieve the above. This is an easy and short way to multiply two matrices. Have a look at this code.

import torch li1 = [ [1, 3, 5], [2, 4, 6], [7, 8, 9]] li2 = [ [1, 3, 5], [2, 4, 6], [7, 8, 9]] li1 = torch.Tensor(li1).view(3,3) li2 = torch.Tensor(li2).view(3,3) print(li1) print(li2) print([email protected])

Output:

tensor([[1., 3., 5.], [2., 4., 6.], [7., 8., 9.]]) tensor([[1., 3., 5.], [2., 4., 6.], [7., 8., 9.]]) tensor([[ 42., 55., 68.], [ 52., 70., 88.], [ 86., 125., 164.]])

Hope you learned something.

Thank you.

Also read: How to Perform Matrix Multiplication of given dimension in Python

## Leave a Reply