PyTorch torch.addmm Function
PyTorch torch Reference Manual
torch.addmmis a function in PyTorch used to add the result of matrix multiplication to the input matrix. It performs the 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): The input matrix, added to the result.mat1(Tensor): The first matrix, with shape (n, m).mat2(Tensor): The second matrix, with shape (m, p).beta(float, optional): The coefficient multiplied by input, default is 1.0.alpha(float, optional): The coefficient multiplied by the mat1 @ mat2 result, default is 1.0.out(Tensor, optional): The output tensor.
Return Value:
torch.Tensor: Returns the sum of the matrix multiplication result and the input matrix, with shape (n, p).
Usage Example
Example
import torch
# Create the 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)
# Create the 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)
The output result is:
输入矩阵形状: torch.Size([3, 3])
矩阵1形状: torch.Size([3, 4])
矩阵2形状: torch.Size([4, 3])
结果形状: 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 the alpha and beta parameters
import torch
input = torch.randn(3, 3)
mat1 = torch.randn(3, 4)
mat2 = torch.randn(4, 3)
# Use the 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)
input = torch.randn(3, 3)
mat1 = torch.randn(3, 4)
mat2 = torch.randn(4, 3)
# Use the 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)
Other Extensions