How to do product of matrices in PyTorch

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to do product of matrices in PyTorch in Python. So Here I am Explain to you all the possible Methods here.

How to do product of matrices in PyTorch?

1. How to do product of matrices in PyTorch?

Specifically, torch.dot() treats both a and b as 1D vectors (irrespective of their original shape) and computes their inner product.

2. product of matrices in PyTorch

Specifically, torch.dot() treats both a and b as 1D vectors (irrespective of their original shape) and computes their inner product.

Method 1

You’re looking for

torch.mm(a,b)
Note that torch.dot() behaves differently to np.dot(). There’s been some discussion about what would be desirable here. Specifically, torch.dot() treats both a and b as 1D vectors (irrespective of their original shape) and computes their inner product. The error is thrown, because this behaviour makes your a a vector of length 6 and your b a vector of length 2; hence their inner product can’t be computed. For matrix multiplication in PyTorch, use torch.mm(). Numpy’s np.dot() in contrast is more flexible; it computes the inner product for 1D arrays and performs matrix multiplication for 2D arrays.

By popular demand, the function torch.matmul performs matrix multiplications if both arguments are 2D and computes their dot product if both arguments are 1D. For inputs of such dimensions, its behaviour is the same as np.dot. It also lets you do broadcasting or matrix x matrix, matrix x vector and vector x vector operations in batches. For more info, see its docs.

1D inputs, same as torch.dot

a = torch.rand(n)
b = torch.rand(n)
torch.matmul(a, b) # torch.Size([])

2D inputs, same as torch.mm

a = torch.rand(m, k)
b = torch.rand(k, j)
torch.matmul(a, b) # torch.Size([m, j])

Method 2

Use torch.mm(a, b) or torch.matmul(a, b)
Both are same.

>>> torch.mm
<built-in method mm of type object at 0x11712a870>
>>> torch.matmul
<built-in method matmul of type object at 0x11712a870>

There’s one more option that may be good to know. That is @ operator. @Simon H.

>>> a = torch.randn(2, 3)
>>> b = torch.randn(3, 4)
>>> [email protected]
tensor([[ 0.6176, -0.6743,  0.5989, -0.1390],
[ 0.8699, -0.3445,  1.4122, -0.5826]])
>>> a.mm(b)
tensor([[ 0.6176, -0.6743,  0.5989, -0.1390],
[ 0.8699, -0.3445,  1.4122, -0.5826]])
>>> a.matmul(b)
tensor([[ 0.6176, -0.6743,  0.5989, -0.1390],
[ 0.8699, -0.3445,  1.4122, -0.5826]])

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.