PyTorch torch.mv 関数


Pytorch torch 参考手册Pytorch torch リファレンスマニュアル

torch.mvPyTorch で行列ベクトル乗算を実行するための関数です。行列とベクトルの積を計算します。

関数定義

torch.mv(input, vec, out=None)

パラメータ:

  • input(Tensor): 入力行列、形状は (n, m) です。
  • vec(Tensor): 入力ベクトル、形状は (m,) または (m, 1) です。
  • out(Tensor, オプション): 出力テンソル。

戻り値:

  • torch.Tensor: 行列ベクトル積を返します。形状は (n,) です。

使用例

例

import torch

# 行列とベクトルを作成
mat = torch.randn(3, 4)
vec = torch.randn(4)

# 行列ベクトル乗算
result = torch.mv(mat, vec)

print("行列形状:", mat.shape)
print("ベクトル形状:", vec.shape)
print("結果形状:", result.shape)
print("結果:", result)

出力結果は次のとおりです。

矩阵形状: torch.Size([3, 4])
向量形状: torch.Size([4])
结果形状: torch.Size([3])
tensor([-0.1861,  0.2482, -0.4375])

例 - ニューラルネットワーク層の計算

import torch

# ニューラルネットワークの全結合層をシミュレートする
W = torch.randn(512, 256)  # 重み行列
x = torch.randn(256)        # 入力ベクトル

# y = W @ x を計算
y = torch.mv(W, x)

print("重み行列形状:", W.shape)
print("入力ベクトル形状:", x.shape)
print("出力ベクトル形状:", y.shape)

Pytorch torch 参考手册Pytorch torch リファレンスマニュアル

その他の拡張