PyTorch torch.linalg.svd function
PyTorch torch reference manual
torch.linalg.svd is a function in PyTorch's linear algebra module used to compute the singular value decomposition (SVD) of a matrix. SVD factors a matrix as A = U * diag(S) * V^T.
Function definition
torch.linalg.svd(A, full_matrices=False, out=None)
Parameters:
A(Tensor): Input matrix.full_matrices(bool, optional): If True, return the full U and V matrices. Defaults to False.out(tuple, optional): Output tuple.
Return Value:
tuple: Returns a tuple (U, S, Vh), where Vh is the transpose of V.
Usage examples
Example
import
torch
Create a matrix
A
=
torch.
tensor
(
[
[
1.0
,
2.0
,
3.0
]
,
[
4.0
,
5.0
,
6.0
]
,
[
7.0
,
8.0
,
9.0
]
,
[
10.0
,
11.0
,
12.0
]
]
)
SVD decomposition
U
,
S
,
Vh
=
torch.
linalg
.
svd
(
A
)
(
"Matrix A:"
)
(
A
)
(
"nU shape:"
,
U.
shape
)
(
"Singular values S:"
,
S
)
(
"Vh shape:"
,
Vh.
shape
)
(
"nVerify: U @ diag(S) @ Vh ="
)
(
U
@
torch.
diag
(
S
)
@
Vh
)
The output is:
矩阵 A:
tensor([[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.],
[10., 11., 12.]])
U 形状: torch.Size([4, 4])
奇异值 S: tensor([25.4627, 1.2907, 0.0000])
Vh 形状: torch.Size([3, 3])
验证: U @ diag(S) @ Vh =
tensor([[ 1.0000, 2.0000, 3.0000],
[ 4.0000, 5.0000, 6.0000],
[ 7.0000, 8.0000, 9.0000],
[10.0000, 11.0000, 12.0000]])