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

PyTorch torch.addmm Function

PyTorch torch.addmm Function


PyTorch torch reference manual PyTorch torch reference manual

torch.addmm is a function in PyTorch used to add the result of matrix multiplication to an input matrix. It performs the matrix multiplication 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:

Return Value:


Usage examples

Example

import

torch

Create the input matrix and the 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 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

)


PyTorch torch reference manual PyTorch torch reference manual