Pytorch Torch Addr
# 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 the input.
### Function Definition
torch.addr(input, vec1, vec2, *, beta=1.0, alpha=1.0, out=None)
**Parameters**:
* `input` (Tensor): Input matrix, which is added to the result.
* `vec1` (Tensor): First vector, shape (n,) or (n, 1).
* `vec2` (Tensor): Second vector, shape (m,) or (m, 1).
* `beta` (float, optional): Coefficient for multiplying input, default is 1.0.
* `alpha` (float, optional): Coefficient for multiplying 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, shape (n, m).
* * *
## Usage Examples
## Example
import torch
# Create input matrix and two vectors
input= torch.zeros(3,4)
vec1 = torch.tensor([1,2,3])
vec2 = torch.tensor([4,5,6,7])
# Compute outer product and add to 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)
Output:
Input matrix shape: torch.Size([3, 4])Vector 1: tensor([1, 2, 3])Vector 2: tensor([4, 5, 6, 7])Result shape: torch.Size([3, 4]) tensor([[ 4., 5., 6., 7.], [ 8., 10., 12., 14.], [12., 15., 18., 21.]])
## Example - Without Input Matrix
import torch
vec1 = torch.tensor([1,2,3])
vec2 = torch.tensor([4,5,6])
# Directly compute outer product
result = torch.addr(torch.zeros(3,3), vec1, vec2)
print(result)
* * Pytorch torch reference manual](#)
YouTip