PyTorch torch.mv function
PyTorch torch reference manual
torch.mv is 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): the input matrix, with shape (n, m).vec(Tensor): the input vector, with shape (m,) or (m, 1).out(Tensor, optional): the output tensor.
Return Value:
torch.Tensor: Returns the matrix-vector product, with shape (n,).
Usage examples
Example
import
torch
Create a matrix and a vector
mat
=
torch.
randn
(
3
,
4
)
vec
=
torch.
randn
(
4
)
Matrix-vector multiplication
result
=
torch.
mv
(
mat
,
vec
)
(
"Matrix shape:"
,
mat.
shape
)
(
"Vector shape:"
,
vec.
shape
)
(
"Result shape:"
,
result.
shape
)
(
"Result:"
,
result
)
The output 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
Simulating 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
)
(
"Weight matrix shape:"
,
W.
shape
)
(
"Input vector shape:"
,
x.
shape
)
(
"Output vector shape:"
,
y.
shape
)