📘
Multiple Linear Regression (Normal Equation)
MediumLinear Regression
Implement multiple linear regression using the normal equation.
Given a feature matrix X (without bias column) and target vector y, compute the weight vector w that minimizes the mean squared error.
First, prepend a column of ones to X to form the augmented matrix Xa, then solve: w=(XaTXa)−1XaTy
Return the weight vector as a list, rounded to 4 decimal places. The first element is the bias/intercept.
You must implement matrix operations from scratch (transpose, multiply, invert).
Example:
Input:
X = [[1], [2], [3]] y = [2, 4, 6]
Output:
[0.0, 2.0]
Reasoning:
- First, we prepend a column of ones to X to form the augmented matrix Xa: Xa=[[1,1],[1,2],[1,3]]
- Then, we calculate XaTXa and XaTy: XaTXa=[[1,1,1],[1,2,3]]⋅[[1,1],[1,2],[1,3]]=[[3,6],[6,14]] and XaTy=[[1,1,1],[1,2,3]]⋅[2,4,6]=[12,28]
- Next, we calculate the inverse of XaTXa: (XaTXa)−1=[[3,6],[6,14]]−1=(3⋅14−6⋅6)1⋅[[14,−6],[−6,3]]=61⋅[[14,−6],[−6,3]]=[[37,−1],[−1,21]]
- Finally, we calculate the weight vector w=(XaTXa)−1XaTy=[[37,−1],[−1,21]]⋅[12,28]=[0,2]
Constraints:
- X is a 2D list (n samples x m features)
- y is a 1D list of n targets
- Return a list of (m+1) weights rounded to 4 decimal places
- First weight is the intercept (bias term)
- Implement matrix operations without numpy
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.