torch.linalg.svd
- torch.linalg.svd(A, full_matrices=True, *, driver=None, out=None)
Computes the singular value decomposition (SVD) of a matrix.
Letting be or , the of a matrix , if , is defined as
Computes the singular value decomposition (SVD) of a matrix.
Letting be or , the of a matrix , if , is defined as
where , is the conjugate transpose when is complex, and the transpose when is real-valued. The matrices , (and thus ) are orthogonal in the real case, and unitary in the complex case.
When m > n (resp. m < n) we can drop the last m - n (resp. n - m) columns of U (resp. V) to form the reduced SVD:
where . In this case, and also have orthonormal columns.
Supports input of float, double, cfloat and cdouble dtypes.
Also supports batches of matrices, and if A is a batch of matrices then
the output has the same batch dimensions.
The returned decomposition is a named tuple (U, S, Vh) which corresponds to , , above.
The singular values are returned in descending order.
The parameter full_matrices chooses between the full (default) and reduced SVD.
The driver kwarg may be used in CUDA with a cuSOLVER backend to choose the algorithm used to compute the SVD.
The choice of a driver is a trade-off between accuracy and speed.
If A is well-conditioned (its condition number is not too large), or you do not mind some precision loss.
For a general matrix: ‘gesvdj’ (Jacobi method)
If A is tall or wide (m >> n or m << n): ‘gesvda’ (Approximate method)
If A is not well-conditioned or precision is relevant: ‘gesvd’ (QR based)
By default (driver= None), we call ‘gesvdj’ and, if it fails, we fallback to ‘gesvd’.
Differences with numpy.linalg.svd:
Unlike numpy.linalg.svd, this function always returns a tuple of three tensors
and it doesn’t support compute_uv argument.
Please use torch.linalg.svdvals(), which computes only the singular values,
instead of compute_uv=False.
A named tuple (U, S, Vh) which corresponds to , , above.
S will always be real-valued, even when A is complex.
It will also be ordered in descending order.
U and Vh will have the same dtype as A. The left / right singular vectors will be given by
the columns of and the rows of respectively.
Examples:
>>> A = torch.randn(5, 3)
>>> U, S, Vh = torch.linalg.svd(A, full_matrices=False)
>>> U.shape, S.shape, Vh.shape
(torch.Size([5, 3]), torch.Size([3]), torch.Size([3, 3]))
>>> torch.dist(A, U @ torch.diag(S) @ Vh)
tensor(1.0486e-06)
>>> U, S, Vh = torch.linalg.svd(A)
>>> U.shape, S.shape, Vh.shape
(torch.Size([5, 5]), torch.Size([3]), torch.Size([3, 3]))
>>> torch.dist(A, U[:, :3] @ torch.diag(S) @ Vh)
tensor(1.0486e-06)
>>> A = torch.randn(7, 5, 3)
>>> U, S, Vh = torch.linalg.svd(A, full_matrices=False)
>>> torch.dist(A, U @ torch.diag_embed(S) @ Vh)
tensor(3.0957e-06)