PyTorch torch.addr Function
PyTorch torch reference manual
torch.addr 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 with 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): the input matrix, which is 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): a coefficient by which input is multiplied, defaulting to 1.0.alpha(float, optional): a coefficient by which the outer product result is multiplied, defaulting to 1.0.out(Tensor, optional): the output tensor.
Return Value:
torch.Tensor: returns the sum of the outer product and the input matrix, with shape (n, m).
Usage examples
Example
import
torch
Create the input matrix and the 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
)
(
"Input matrix shape:"
,
input
.
shape
)
(
"Vector 1:"
,
vec1
)
(
"Vector 2:"
,
vec2
)
(
"Result shape:"
,
result.
shape
)
(
result
)
The output 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 an input matrix
import
torch
vec1
=
torch.
tensor
(
[
1
,
2
,
3
]
)
vec2
=
torch.
tensor
(
[
4
,
5
,
6
]
)
Compute the outer product directly
result
=
torch.
addr
(
torch.
zeros
(
3
,
3
)
,
vec1
,
vec2
)
(
result
)