PyTorch torch.mv 函数
torch.mv 是 PyTorch 中用于执行矩阵向量乘法的函数。它计算矩阵与向量的乘积。
函数定义
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)
# 创建矩阵和向量
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)
# 模拟神经网络全连接层
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 参考手册