Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.addr Function

PyTorch torch.addr Function


PyTorch torch reference manual 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:

Return Value:


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

)

print

(

"Input matrix shape:"

,

input

.

shape

)

print

(

"Vector 1:"

,

vec1

)

print

(

"Vector 2:"

,

vec2

)

print

(

"Result shape:"

,

result.

shape

)

print

(

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

)

print

(

result

)


PyTorch torch reference manual PyTorch torch reference manual