3 years ago

# Matrix Calculations in PyTorch

• function 1: torch.mm(input, mat2, *, out=None)

Performs multiplication of two matrices.
This function takes two parameters namely: input -> first matrix to be multiplied and mat2-> second matrix to be multiplied.
The out keyword argument is optional.
Unlike the torch.matmul() function, this function does not broadcast matrix products.

• function 2: torch.mv(input, vec)

Performs a matrix-vector product of the matrix 'input' and the vector 'vec'.
This function takes two parameters namely: input -> matrix to be multiplied and vec-> vector to be multiplied.
Just like the torch.mm() function, it does not support broadcasting.

• function 3: torch.bmm(input, mat2, *, deterministic=False, out=None)

Performs a batch matrix-matrix product of matrices stored in input and mat2.
input -> first matrix to be multiplied and mat2-> second matrix to be multiplied.
input and mat2 must be 3-D tensors each containing the same number of matrices.
It does not support broadcasting. The out keyword argument is optional.

• function 5: torch.dot(input, tensor)

Performs an elementwise dot product of two tensors (input and tensor). This function does not broadcast.

• function 5: torch.inverse((input, *, out=None) )

Computes the inverse of a square matrix input.
input -> can be batches of 2D square tensors, in which case this function would return a tensor composed of individual inverses.

# Import torch and other required modules
import torch

### Function 1 - torch.mm(input, mat2)

This function performs a multiplication of two given matrices as illustrated by the examples below

# Example 1

# We create our first matrix for multiplication

tensor1 = torch.Tensor(
[
[1, 1],
[2, 2]
])
tensor1
tensor([[1., 1.],
[2., 2.]])
# We create our second matrix for multiplication

tensor2 = torch.Tensor(
[
[3, 4],
[3, 4]
])
tensor2
tensor([[3., 4.],
[3., 4.]])