v9.1.1
Menu

Ridge Regression

mediumFREELinear RegressionMachine Learning 1

Implement Ridge Regression (L2 regularization) using the regularized normal equation.

Given feature matrix XX (without bias column), target vector yy, and regularization parameter λ\lambda, compute: w=(XaTXa+λI′)−1XaTyw = (X_a^T X_a + \lambda I')^{-1} X_a^T y

where XaX_a has a column of ones prepended, and I′I' is the identity matrix with the top-left element set to 0 (we don't regularize the bias).

Return the weight vector as a list, rounded to 4 decimal places.

Example

Input
X = [[1], [2], [3]]
y = [2, 4, 6]
lambda_reg = 0.0
Output
[0.0, 2.0]
Reasoning
  • Inputs: XX holds 3 samples with one feature each (x=1,2,3x = 1, 2, 3), yy holds their targets 2,4,62, 4, 6, and λ=0\lambda = 0 (no penalty).
  • Augment: prepending the ones column gives rows (1,1),(1,2),(1,3)(1, 1), (1, 2), (1, 3). Weights are intercept bb, then slope w1w_1.
  • Build the system: XaTXa=(36614)X_a^T X_a = \begin{pmatrix} 3 & 6 \\ 6 & 14 \end{pmatrix} (count, ∑x\sum x, ∑x2\sum x^2) and XaTy=(12,28)X_a^T y = (12, 28) (∑y\sum y, ∑xy\sum x y). λI′\lambda I' would add to the bottom-right entry only.
  • Solve: the determinant is 3⋅14−6⋅6=63 \cdot 14 - 6 \cdot 6 = 6, so the inverse is 16(14−6−63)\frac{1}{6}\begin{pmatrix} 14 & -6 \\ -6 & 3 \end{pmatrix}. Then b=14⋅12−6⋅286=0b = \frac{14 \cdot 12 - 6 \cdot 28}{6} = 0 and w1=−6⋅12+3⋅286=2w_1 = \frac{-6 \cdot 12 + 3 \cdot 28}{6} = 2, giving [0.0, 2.0].
  • Notice: the data lies exactly on y=2xy = 2x. With λ=1\lambda = 1 the bottom-right entry becomes 1515, the slope shrinks to 129≈1.3333\frac{12}{9} \approx 1.3333, and the unpenalised intercept rises to 1.33331.3333 to compensate.

Constraints

  • X is a 2D list (n x m), y is a 1D list of n targets
  • lambda_reg is a positive float
  • Return list of (m+1) weights rounded to 4 decimal places
  • First weight is the intercept (not regularized)
  • Implement without numpy

Learn this in

More from Machine Learning 1

solution.py

Test results

Sign in to run your code against the test cases.