fn

lstsq

Tensor
lstsq(A: Tensor, B: Tensor, rcond: float | None = None, driver: str | None = None)
source

Solve a least-squares linear system.

Finds XX minimising the squared residual

minXAXB22,\min_X \,\|A\,X - B\|_2^2,

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

X=(AA)1AB,X \,=\, (A^\top A)^{-1} A^\top B,

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

Parameters

ATensor
Coefficient matrix of shape (*, m, n).
BTensor
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.
driverstr or None= None
Solver choice ("gels", "gelsy", "gelsd", ...). None lets the engine pick (currently gels).

Returns

Tensor

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

Notes

Backed by LAPACK gels / gelsd on the CPU stream; GPU calls fall back to CPU. Only solution is fully populated in the current implementation; the remaining outputs exist for shape compatibility with the reference API.

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.0000],
        [3.0000]])