python-pytorchHow to perform matrix multiplication using Python and PyTorch?
Matrix multiplication can be performed using Python and PyTorch. To do so, you first need to create two matrices and define them as tensors. Then, use the torch.mm()
method to perform the matrix multiplication.
import torch
# Create two matrices and define them as tensors
matrix_a = torch.tensor([[1,2],
[3,4]])
matrix_b = torch.tensor([[5,6],
[7,8]])
# Perform the matrix multiplication
matrix_c = torch.mm(matrix_a, matrix_b)
print(matrix_c)
Output example
tensor([[19, 22],
[43, 50]])
The code above consists of the following parts:
import torch
- This imports the PyTorch library.matrix_a = torch.tensor([[1,2], [3,4]])
- This creates a matrix with the values1,2,3,4
and defines it as a tensor.matrix_b = torch.tensor([[5,6], [7,8]])
- This creates a matrix with the values5,6,7,8
and defines it as a tensor.matrix_c = torch.mm(matrix_a, matrix_b)
- This performs the matrix multiplication ofmatrix_a
andmatrix_b
and stores the result inmatrix_c
.print(matrix_c)
- This prints the result of the matrix multiplication to the console.
Helpful links
More of Python Pytorch
- How can I use a Multilayer Perceptron (MLP) with Python and PyTorch?
- How can I use Yolov5 with PyTorch?
- How can I use Python, PyTorch, and YOLOv5 to build an object detection model?
- How can I use Python and PyTorch to parse XML files?
- How do I use Pytorch with Python 3.11 on Windows?
- How do I install PyTorch on Ubuntu using Python?
- How do I install PyTorch using pip?
- How do I install a Python PyTorch .whl file?
- How do I check the version of Python and PyTorch I am using?
- How can I use PyTorch with Python 3.11?
See more codes...