PyTorch torch.mv Function


Pytorch torch 参考手册Pytorch torch Reference Manual

torch.mvis a function in PyTorch used to perform matrix-vector multiplication. It computes the product of a matrix and a vector.

Function Definition

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

Parameters:

  • input(Tensor): Input matrix, shape (n, m).
  • vec(Tensor): Input vector, shape (m,) or (m, 1).
  • out(Tensor, optional): Output tensor.

Return Value:

  • torch.Tensor: Returns the matrix-vector product, shape (n,).

Usage Example

Example

import torch

# Create matrix and vector
mat = torch.randn(3, 4)
vec = torch.randn(4)

# Matrix-vector multiplication
result = torch.mv(mat, vec)

print("Matrix shape:", mat.shape)
print("Vector shape:", vec.shape)
print("Result shape:", result.shape)
print("Result:", result)

The output result is:

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

Example - Neural Network Layer Computation

import torch

# Simulate a fully connected layer of a neural network
W = torch.randn(512, 256)  # Weight matrix
x = torch.randn(256)        # Input vector

# Compute y = W @ x
y = torch.mv(W, x)

print("Weight matrix shape:", W.shape)
print("Input vector shape:", x.shape)
print("Output vector shape:", y.shape)

Pytorch torch 参考手册Pytorch torch Reference Manual

Other Extensions