PyTorch torch.addr Function
PyTorch torch Reference Manual
torch.addrIt is a function in PyTorch used to compute the outer product of two vectors and add it to an input matrix. It computes the outer product of each row of vec1 and each column of vec2, then adds it to input.
Function Definition
torch.addr(input, vec1, vec2, *, beta=1.0, alpha=1.0, out=None)
Parameters:
input(Tensor): Input matrix, added to the result.vec1(Tensor): The first vector, with shape (n,) or (n, 1).vec2(Tensor): The second vector, with shape (m,) or (m, 1).beta(float, optional): Coefficient multiplied by input, default is 1.0.alpha(float, optional): Coefficient multiplied by the outer product result, default is 1.0.out(Tensor, optional): Output tensor.
Return Value:
torch.Tensor: Returns the sum of the outer product and the input matrix, with shape (n, m).
Usage Example
Example
import torch
# Create the input matrix and two vectors
input = torch.zeros(3, 4)
vec1 = torch.tensor([1, 2, 3])
vec2 = torch.tensor([4, 5, 6, 7])
# Compute the outer product and add it to the input matrix
result = torch.addr(input, vec1, vec2)
print("Input matrix shape:", input.shape)
print("Vector 1:", vec1)
print("Vector 2:", vec2)
print("Result shape:", result.shape)
print(result)
# Create the input matrix and two vectors
input = torch.zeros(3, 4)
vec1 = torch.tensor([1, 2, 3])
vec2 = torch.tensor([4, 5, 6, 7])
# Compute the outer product and add it to the input matrix
result = torch.addr(input, vec1, vec2)
print("Input matrix shape:", input.shape)
print("Vector 1:", vec1)
print("Vector 2:", vec2)
print("Result shape:", result.shape)
print(result)
The output result is:
输入矩阵形状: torch.Size([3, 4])
向量1: tensor([1, 2, 3])
向量2: tensor([4, 5, 6, 7])
结果形状: torch.Size([3, 4])
tensor([[ 4., 5., 6., 7.],
[ 8., 10., 12., 14.],
[12., 15., 18., 21.]])
Example - Without Using Input Matrix
import torch
vec1 = torch.tensor([1, 2, 3])
vec2 = torch.tensor([4, 5, 6])
# Directly compute the outer product
result = torch.addr(torch.zeros(3, 3), vec1, vec2)
print(result)
vec1 = torch.tensor([1, 2, 3])
vec2 = torch.tensor([4, 5, 6])
# Directly compute the outer product
result = torch.addr(torch.zeros(3, 3), vec1, vec2)
print(result)
Other Extensions