torch.bmm()
This method provides batched matrix multiplication for the cases where both the matrices to be multiplied are of only 3-Dimensions (x×y×z) and the first dimension (x) of both the matrices must be same. This does not support broadcasting. The syntax is as given below.
torch.bmm( Tensor_1, Tensor_2, deterministic=false, out=None)
The “deterministic” parameter takes up boolean value. A ‘false‘ does a faster calculation which is non-deterministic. A ‘true‘ does a slower calculation however, it is deterministic.
Example:
In the example below, the matrix_1 is of dimension 2×3×3. The second matrix is of dimension 2×3×4.
Python3
import torch # 3D matrices mat_1 = torch.randn( 2 , 3 , 3 ) mat_2 = torch.randn( 2 , 3 , 4 ) print ( "matrix A :\n" ,mat_1) print ( "\nmatrix B :\n" ,mat_2) print ( "\nOutput :\n" ,torch.bmm(mat_1,mat_2)) |
Output:
matrix A : tensor([[[-0.0135, -0.9197, -0.3395], [-1.0369, -1.3242, 1.4799], [-0.0182, -1.2917, 0.6575]], [[-0.3585, -0.0478, 0.4674], [-0.6688, -0.9217, -1.2612], [ 1.6323, -0.0640, 0.4357]]]) matrix B : tensor([[[ 0.2431, -0.1044, -0.1437, -1.4982], [-1.4318, -0.2510, 1.6247, 0.5623], [ 1.5265, -0.8568, -2.1125, -0.9463]], [[ 0.0182, 0.5207, 1.2890, -1.3232], [-0.2275, -0.8006, -0.6909, -1.0108], [ 1.3881, -0.0327, -1.4890, -0.5550]]]) Output : tensor([[[ 0.7954, 0.5231, -0.7752, -0.1756], [ 3.9031, -0.8274, -5.1288, -0.5915], [ 2.8488, -0.2372, -3.4850, -1.3212]], [[ 0.6532, -0.1637, -1.1251, 0.2633], [-1.5532, 0.4309, 1.6527, 2.5167], [ 0.6492, 0.8870, 1.4994, -2.3371]]])
** Note: the matrices vary for each run as random values are filled dynamically.
Python – Matrix multiplication using Pytorch
The matrix multiplication is an integral part of scientific computing. It becomes complicated when the size of the matrix is huge. One of the ways to easily compute the product of two matrices is to use methods provided by PyTorch. This article covers how to perform matrix multiplication using PyTorch.
PyTorch and tensors:
It is a package that can be used for neural network-based deep learning projects. It is an open-source library developed by Facebook’s AI research team. It can replace NumPy with its power of GPU. One of the important classes provided by this library is Tensor. It is nothing but the n-dimensional arrays as provided by the NumPy package. There are so many methods in PyTorch that can be applied to Tensor, which makes computations faster and easy. The Tensor can hold only elements of the same data type.
Matrix multiplication with PyTorch:
The methods in PyTorch expect the inputs to be a Tensor and the ones available with PyTorch and Tensor for matrix multiplication are:
- torch.mm().
- torch.matmul().
- torch.bmm()
- @ operator.
Contact Us