PyTorch torch.linalg.lstsq function
PyTorch torch reference manual
torch.linalg.lstsq is a function in PyTorch's linear algebra module used to solve linear least-squares problems. It solves argmin_x ||AX - B||_F.
Function definition
torch.linalg.lstsq(A, B, rcond=None, driver=None)
Parameters:
A(Tensor): Coefficient matrix.B(Tensor): Right-hand-side matrix or vector.rcond(float, optional): Condition number used to truncate singular values.driver(str, optional): Solver choice, one of 'gels', 'gelsd', 'gelsy'.
Return Value:
torch.Tensor: Returns the least-squares solution.
Usage examples
Example
import
torch
Create the coefficient matrix and the right-hand-side vector
A
=
torch.
tensor
(
[
[
1.0
,
1.0
]
,
[
1.0
,
2.0
]
,
[
1.0
,
3.0
]
]
,
dtype
=
torch.
float64
)
B
=
torch.
tensor
(
[
1.0
,
2.0
,
3.0
]
,
dtype
=
torch.
float64
)
Least-squares solution
X
=
torch.
linalg
.
lstsq
(
A
,
B
)
.
solution
(
"Coefficient matrix A:"
)
(
A
)
(
"nRight-hand-side vector B:"
)
(
B
)
(
"nLeast-squares solution X:"
)
(
X
)
The output is:
系数矩阵 A:
tensor([[1., 1.],
[1., 2.],
[1., 3.]], dtype=torch.float64)
右侧向量 B:
tensor([1., 2., 3.], dtype=float64)
最小二乘解 X:
tensor([0.0000, 1.0000], dtype=float64)