v9.1.1
Menu

Multiple Linear Regression (Normal Equation)

mediumFREELinear RegressionMachine Learning 1

Implement multiple linear regression using the normal equation.

Given a feature matrix XX (without bias column) and target vector yy, compute the weight vector ww that minimizes the mean squared error.

First, prepend a column of ones to XX to form the augmented matrix XaX_a, then solve: w=(XaTXa)−1XaTyw = (X_a^T X_a)^{-1} X_a^T y

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
  • Inputs: X holds n=3n = 3 samples with m=1m = 1 feature each (1,2,31, 2, 3), and y holds their targets 2,4,62, 4, 6. We want weights [w0,w1][w_0, w_1] so that y^=w0+w1x\hat y = w_0 + w_1 x.
  • The column of ones turns the intercept into an ordinary weight: Xa=(111213)X_a = \begin{pmatrix}1&1\\1&2\\1&3\end{pmatrix} (3×23 \times 2).
  • XaTXa=(36614)X_a^T X_a = \begin{pmatrix}3&6\\6&14\end{pmatrix}: the top-left entry counts the samples, the off-diagonal is ∑xi=6\sum x_i = 6, and the bottom-right is ∑xi2=14\sum x_i^2 = 14. Likewise XaTy=(1228)X_a^T y = \begin{pmatrix}12\\28\end{pmatrix}, i.e. ∑yi\sum y_i and ∑xiyi\sum x_i y_i.
  • Its 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}.
  • Multiplying: w0=14⋅12−6⋅286=0w_0 = \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] after rounding to 4 decimal places.
  • Notice the data lie exactly on y=2xy = 2x, so the fit is perfect: zero intercept, slope 22. Shifting every target up by 11 would change only w0w_0.

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

Learn this in

More from Machine Learning 1

solution.py

Test results

Sign in to run your code against the test cases.