Pytorch Torch Addmm
# PyTorch torch.addmm Function
* * Pytorch torch reference manual](#)
`torch.addmm` is a function in PyTorch used to add the result of matrix multiplication to an input matrix. It performs matrix multiplication of mat1 @ mat2 and then adds the result to input.
### Function Definition
torch.addmm(input, mat1, mat2, *, beta=1.0, alpha=1.0, out=None)
**Parameters**:
* `input` (Tensor): Input matrix, which is added to the result.
* `mat1` (Tensor): First matrix with shape (n, m).
* `mat2` (Tensor): Second matrix with shape (m, p).
* `beta` (float, optional): Coefficient for multiplying input, default is 1.0.
* `alpha` (float, optional): Coefficient for multiplying the result of mat1 @ mat2, default is 1.0.
* `out` (Tensor, optional): Output tensor.
**Return Value**:
* `torch.Tensor`: Returns the sum of the matrix multiplication result and the input matrix with shape (n, p).
* * *
## Usage Examples
## Example
import torch
# Create input matrix and two matrices
input= torch.randn(3,3)
mat1 = torch.randn(3,4)
mat2 = torch.randn(4,3)
# Perform addmm
result = torch.addmm(input, mat1, mat2)
print("Input matrix shape:",input.shape)
print("Matrix 1 shape:", mat1.shape)
print("Matrix 2 shape:", mat2.shape)
print("Result shape:", result.shape)
print(result)
Output result is:
Input matrix shape: torch.Size([3, 3])Matrix 1 shape: torch.Size([3, 4])Matrix 2 shape: torch.Size([4, 3])Result shape: torch.Size([3, 3]) tensor([[ 0.4692, -0.2864, -0.6013], [ 1.5525, 0.1233, -0.0182], [-0.3956, 0.6267, 0.3580]])
## Example - Using alpha and beta parameters
import torch
input= torch.randn(3,3)
mat1 = torch.randn(3,4)
mat2 = torch.randn(4,3)
# Use alpha and beta parameters
result = torch.addmm(input, mat1, mat2, beta=0.5, alpha=2.0)
# Equivalent to: result = 0.5 * input + 2.0 * (mat1 @ mat2)
print(result)
* * Pytorch torch reference manual](#)
YouTip