📘
Ridge Regression
MediumLinear Regression
Implement Ridge Regression (L2 regularization) using the regularized normal equation.
Given feature matrix X (without bias column), target vector y, and regularization parameter λ, compute: w=(XaTXa+λI′)−1XaTy
where Xa has a column of ones prepended, and 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:
- First, we prepend a column of ones to the feature matrix X to get Xa: Xa=[[1,1],[1,2],[1,3]]
- Then, we calculate XaTXa and XaTy: XaTXa=[[3,6],[6,14]] and XaTy=[[2+4+6],[2+8+12]]=[[12],[22]]
- Next, we compute the regularized matrix XaTXa+λI′, where λ=0.0 and I′ is the identity matrix with the top-left element set to 0: XaTXa+λI′=[[0,6],[6,14]]
- Finally, we calculate the weight vector w=(XaTXa+λI′)−1XaTy: w=[[0.0],[2.0]], which when rounded to 4 decimal places gives the output [0.0,2.0]
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
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.