The Shortest Weights That Fit Best

Linear Algebra for MLMedium+20 XP+20

The Shortest Weights That Fit Best

Chapter 13's lesson When the Normal Equations Break left a fit with no single answer. When columns of the design matrix XXX repeat the same information, such as a length recorded in both feet and inches, X⊤XX^\top XX⊤X is singular, the normal equations have no unique answer, and infinitely many weight vectors www tie for the smallest squared error.

The standard way to break the tie is to choose, among all those best-fitting www, the one with the smallest length ∥w∥\|w\|∥w∥. The pseudoinverse X+X^+X+ finds it directly from the SVD X=UΣV⊤X = U\Sigma V^\topX=UΣV⊤ of Chapter 11:

X+=V Σ+ U⊤,w=X+yX^+ = V\,\Sigma^+\,U^\top, \qquad w = X^+ yX+=VΣ+U⊤,w=X+y

For an m×nm \times nm×n matrix XXX (mmm examples, nnn features), Σ\SigmaΣ is m×nm \times nm×n. Σ+\Sigma^+Σ+ is its n×mn \times mn×m counterpart: the same diagonal layout, with each nonzero singular value σ\sigmaσ replaced by 1/σ1/\sigma1/σ. Singular values that are zero stay 000.

On a computer, a singular value that should be exactly zero usually comes out as a tiny leftover such as 10−1610^{-16}10−16. So use this rule: a singular value counts as zero when it is at most 10−1010^{-10}10−10 times the largest singular value.

Task: write min_norm_weights(X, y) returning w=X+yw = X^+ yw=X+y as a list, every entry rounded to 4 decimal places.

  • X is a list of rows, one per example. Its columns may be redundant, and it may have more columns than rows.
  • When the columns of XXX are independent, this matches the normal-equations answer exactly; the pseudoinverse only changes things when that answer isn't unique.

Examples

X = [[1, 1], [1, 2], [1, 3], [1, 4]]
y = [2.1, 3.9, 6.2, 7.8]
returns [0.15, 1.94]
X = [[1, 2, 24], [1, 3, 36], [1, 5, 60], [1, 6, 72]]
y = [150, 185, 260, 290]
returns [79.25, 0.2448, 2.9379]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run