PyTorch torch.chain_matmul 関数
torch.chain_matmulPyTorch で複数の行列の連鎖乗算を計算するための関数です。最適な行列乗算の順序を使用して計算コストを最小化します。
関数定義
torch.chain_matmul(*matrices, out=None)
パラメータ:
matrices(Tensor): 入力となる行列のシーケンス。out(Tensor, オプション): 出力テンソル。
戻り値:
torch.Tensor: すべての行列を乗算した結果を返します。
使用例
例
import torch
# 複数の行列を作成
A = torch.randn(10, 20)
B = torch.randn(20, 30)
C = torch.randn(30, 40)
D = torch.randn(40, 50)
# 行列の連鎖乗算
result = torch.chain_matmul(A, B, C, D)
print("行列 A の形状:", A.shape)
print("行列 B の形状:", B.shape)
print("行列 C の形状:", C.shape)
print("行列 D の形状:", D.shape)
print("結果の形状:", result.shape)
# 複数の行列を作成
A = torch.randn(10, 20)
B = torch.randn(20, 30)
C = torch.randn(30, 40)
D = torch.randn(40, 50)
# 行列の連鎖乗算
result = torch.chain_matmul(A, B, C, D)
print("行列 A の形状:", A.shape)
print("行列 B の形状:", B.shape)
print("行列 C の形状:", C.shape)
print("行列 D の形状:", D.shape)
print("結果の形状:", result.shape)
出力結果は次のとおりです:
矩阵 A 形状: torch.Size([10, 20]) 矩阵 B 形状: torch.Size([20, 30]) 矩阵 C 形状: torch.Size([30, 40]) 矩阵 D 形状: torch.Size([40, 50]) 结果形状: torch.Size([10, 50])
例 - リストを使用
import torch
# 行列のリスト
matrices = [torch.randn(10, 20),
torch.randn(20, 30),
torch.randn(30, 40)]
# リストをパラメータとして使用
result = torch.chain_matmul(*matrices)
print("結果の形状:", result.shape)
# 行列のリスト
matrices = [torch.randn(10, 20),
torch.randn(20, 30),
torch.randn(30, 40)]
# リストをパラメータとして使用
result = torch.chain_matmul(*matrices)
print("結果の形状:", result.shape)
その他の拡張
Pytorch torch リファレンスマニュアル