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

PyTorch torch.chain_matmul function

PyTorch torch.chain_matmul function


PyTorch torch reference manual PyTorch torch reference manual

torch.chain_matmul is a function in PyTorch used to compute the chained multiplication of multiple matrices. It minimizes computational cost by choosing the optimal order of matrix multiplications.

Function definition

torch.chain_matmul(*matrices, out=None)

Parameters:

Return Value:


Usage examples

Example

import

torch

Create multiple matrices

A

=

torch.

randn

(

10

,

20

)

B

=

torch.

randn

(

20

,

30

)

C

=

torch.

randn

(

30

,

40

)

D

=

torch.

randn

(

40

,

50

)

Chained matrix multiplication

result

=

torch.

chain_matmul

(

A

,

B

,

C

,

D

)

print

(

"Shape of matrix A:"

,

A.

shape

)

print

(

"Shape of matrix B:"

,

B.

shape

)

print

(

"Shape of matrix C:"

,

C.

shape

)

print

(

"Shape of matrix D:"

,

D.

shape

)

print

(

"Result shape:"

,

result.

shape

)

The output is:

矩阵 A 形状: torch.Size([10, 20])

矩阵 B 形状: torch.Size([20, 30])

矩阵 C 形状: torch.Size([30, 40])

矩阵 D 形状: torch.Size([40, 50])

结果形状: torch.Size([10, 50])

Example - Using a list

import

torch

A list of matrices

matrices

=

[

torch.

randn

(

10

,

20

)

,

            torch.

randn

(

20

,

30

)

,

            torch.

randn

(

30

,

40

)

]

Use the list as the argument

result

=

torch.

chain_matmul

(

*matrices

)

print

(

"Result shape:"

,

result.

shape

)


PyTorch torch reference manual PyTorch torch reference manual