PyTorch torch.linalg.pinv function
PyTorch torch reference manual
torch.linalg.pinv is a function in PyTorch's linear algebra module used to compute the Moore-Penrose pseudoinverse of a matrix. For non-square or singular matrices, the pseudoinverse is an important tool.
Function definition
torch.linalg.pinv(A, rcond=None, hermitian=False, out=None)
Parameters:
A(Tensor): Input matrix.rcond(float, optional): Singular value truncation threshold.hermitian(bool, optional): If True, the matrix is considered Hermitian. Defaults to False.out(Tensor, optional): the output tensor.
Return Value:
torch.Tensor: Returns the pseudoinverse of the matrix.
Usage examples
Example
import
torch
Create a non-square matrix
A
=
torch.
tensor
(
[
[
1.0
,
2.0
,
3.0
]
,
[
4.0
,
5.0
,
6.0
]
]
,
dtype
=
torch.
float64
)
Compute the pseudoinverse
A_pinv
=
torch.
linalg
.
pinv
(
A
)
(
"Matrix A:"
)
(
A
)
(
"nPseudoinverse A^+:"
)
(
A_pinv
)
(
"nVerify: A @ A^+ @ A ~= A"
)
(
A
@
A_pinv
@
A
)
The output is:
矩阵 A:
tensor([[1., 2., 3.],
[4., 5., 6.]], dtype=torch.float64)
伪逆 A^+:
tensor([[-0.9444, 0.4444],
[-0.2778, 0.2778],
[ 0.3889, 0.1111]], dtype=float64)
验证: A @ A^+ @ A ≈ A
tensor([[ 1.0000e+00, 2.0000e+00, 3.0000e+00],
[ 4.0000e+00, 5.0000e+00, 6.0000e+00]], dtype=float64)