Skip to content
fn

lstsq

→Tensor
lstsq(input: Tensor, b: Tensor, rcond: float | None = None, driver: str | None = None)

Solve a least-squares linear system.

Finds XX minimising the squared residual

min⁡X ∥A X−B∥22,\min_X \,\|A\,X - B\|_2^2,

where A∈Rm×nA \in \mathbb{R}^{m \times n} may be over- or underdetermined. For full-rank AA and m≥nm \ge n the solution is unique:

X = (A⊤A)−1A⊤B,X \,=\, (A^\top A)^{-1} A^\top B,

obtained more stably via QR or SVD without forming the normal equations.

Parameters

inputTensor
Coefficient matrix of shape (*, m, n).
Right-hand side of shape (*, m, k) (or (*, m)).
rcondfloat or None= None
Cutoff for small singular values (passed to the underlying driver). None selects the default driver heuristic.
driver(str or None, keyword - only)= None
Solver choice ("gels", "gelsy", "gelsd", "gelss"). None selects "gelsy" on CPU and "gels" on Metal.

Returns

Tensor

Least-squares solution of shape (*, n, k) (or (*, n)).

Notes

The solution is A+BA^+ B, the minimum-norm least-squares solution for every shape and rank, and differentiates in input and b (twice).

"gels" and "gelsy" (so the default) factor a full-rank input with a QR decomposition, as the reference's default driver does. Every matrix is first checked for full rank from R (the singular values of the triangle for a small batch, a condition-number estimate otherwise); one that does not pass — rank deficient, ill-conditioned, non-finite — takes the SVD route, which decides the rank. "gelsd" and "gelss" return the singular values and always take the SVD route.

Examples

>>> import lucid
>>> from lucid.linalg import lstsq
>>> A = lucid.tensor([[1.0, 1.0], [1.0, 2.0], [1.0, 3.0]])
>>> b = lucid.tensor([[6.0], [9.0], [12.0]])
>>> sol, *_ = lstsq(A, b)
>>> sol
tensor([[3.], [3.]])

Used by 1