Solve least squares with an SVD pseudo-inverse that drops tiny singular values

Real feature matrices often have duplicated or nearly duplicated columns. Inverting the normal equations then blows up. The SVD pseudo-inverse handles it by ignoring directions with tiny singular values, giving the minimum-norm solution.

Write lstsq_svd(A, b, rcond=1e-10). A has shape (m, d), b has shape (m,). Compute the thin SVD A = U diag(s) Vt. Keep only singular values with s_i > rcond * max(s). Return x of shape (d,) equal to V diag(1 / s_kept) U^T b over the kept directions. If A is all zeros, return zeros of shape (d,).

Signaturedef lstsq_svd(A, b, rcond=1e-10)

Example

A = [[1, 0], [0, 1], [0, 0]], b = [1, 2, 3] gives [1.0, 2.0].

Understand the idea

When a feature matrix has duplicate or nearly duplicate columns, the normal equations become singular and the solution can explode. The SVD pseudo-inverse fixes this by using only directions with meaningful singular values and ignoring the rest, which also gives the shortest possible solution vector. Like ignoring a measurement whose signal is pure rounding noise. Worked example: A = [[1, 1], [1, 1]] (two identical columns), b = [2, 2]. Infinitely many x fit, such as [2, 0] or [1, 1]. SVD: singular values [2, 0], first directions u1 = v1 = [0.707, 0.707]. Keep only s = 2. u1 . b = 2.828, divided by 2 gives 1.414, times v1 gives x = [1, 1], the minimum-norm answer. Inverting the zero singular value would blow up. Rule: A = U diag(s) Vt; keep s_i > rcond x max(s); x = sum over kept i of (u_i . b / s_i) v_i. All-zero A returns zeros. np.linalg.lstsq and many regression libraries work this way.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplelstsq_svd([[1, 0], [0, 1], [0, 0]], [1, 2, 3])
  • Sample 2: full rank randomlstsq_svd(_A, _b)
  • Test 3: duplicated column gives minimum normlstsq_svd(_D, _bd)
  • Test 4: zero matrixlstsq_svd(np.zeros((3, 2)), [1.0, 2.0, 3.0])