Skip to content
Lambdian

Linear regression

Fit the straight line (or hyperplane) that predicts a number with the least squared error.

Animated explanation

The idea

You want to predict a number: a flat's rent from its area, tomorrow's demand from today's sales. Linear regression assumes the answer moves in a straight line with each input: every extra square metre adds roughly the same rent.

So the model is a weighted sum y^=w1x1+⋯+wdxd+b\hat{y} = w_1x_1 + \dots + w_dx_d + b. Learning means choosing the weights. We call a choice good when its predictions sit close to the true values on the training data, and we measure "close" with the mean squared error.

Why squared error?

Squaring makes every error positive and punishes large misses far more than small ones: being off by 4 costs sixteen times as much as being off by 1. It is also smooth, so calculus gives a clean minimum. And if the noise around the line is Gaussian, minimising squared error is exactly maximum likelihood.

The price: a few extreme outliers can drag the line towards them. When the data has heavy outliers, absolute error or the Huber loss is more robust.

Two ways to fit

Closed form. Setting the gradient to zero gives the normal equation w∗=(X⊤X)−1X⊤y\mathbf{w}^\ast = (X^\top X)^{-1}X^\top\mathbf{y}. It is exact and needs no learning rate, but solving it costs about O(d3)O(d^3), so it gets slow when there are many thousands of features. In practice use a least-squares solver (QR or SVD), not an explicit inverse.

Gradient descent. Start anywhere and repeat w←w−η∇J\mathbf{w} \leftarrow \mathbf{w} - \eta\nabla J. Each step costs O(nd)O(nd), it scales to huge data (mini-batches), and the same idea trains neural networks. You must pick the learning rate η\eta and scale the features so the bowl is round, not a long thin valley.

Reading the model

Each weight wjw_j is the change in y^\hat{y} when xjx_j goes up by one and the other features stay fixed. That makes linear models easy to explain, but only if the features are not strongly correlated with each other (multicollinearity makes weights unstable).

Judge the fit with R2=1−∑(yi−y^i)2∑(yi−yˉ)2R^2 = 1 - \frac{\sum (y_i-\hat{y}_i)^2}{\sum (y_i-\bar{y})^2}, the share of variance explained, always on a held-out test set. Then plot the residuals: a curve or a funnel in the residuals means the straight-line assumption is wrong.

The algorithm, step by step

  1. 1
    Put the features in a matrix XX (one row per example) and add a column of ones for the bias.
  2. 2
    Closed form: solve X⊤X w=X⊤yX^\top X\,\mathbf{w} = X^\top\mathbf{y} with a least-squares solver.
  3. 3
    Or gradient descent: start with w=0\mathbf{w} = 0 and repeat w←w+2ηnX⊤(y−Xw)\mathbf{w} \leftarrow \mathbf{w} + \frac{2\eta}{n}X^\top(\mathbf{y} - X\mathbf{w}) until the loss stops falling.
  4. 4
    Predict with y^=Xw\hat{\mathbf{y}} = X\mathbf{w}; report MSE and R2R^2 on a test set.

The maths

Model

y^=w⊤x+b\hat{y} = \mathbf{w}^\top\mathbf{x} + b

Loss (MSE)

J(w)=1n∥y−Xw∥2J(\mathbf{w}) = \frac{1}{n}\lVert \mathbf{y} - X\mathbf{w} \rVert^2

Gradient

∇J=−2nX⊤(y−Xw)\nabla J = -\frac{2}{n}X^\top(\mathbf{y} - X\mathbf{w})

Normal equation

w∗=(X⊤X)−1X⊤y\mathbf{w}^\ast = (X^\top X)^{-1}X^\top\mathbf{y}
Requires X⊤XX^\top X to be invertible: no feature may be an exact combination of the others.

Coefficient of determination

R2=1−∑i(yi−y^i)2∑i(yi−yˉ)2R^2 = 1 - \frac{\sum_i (y_i - \hat{y}_i)^2}{\sum_i (y_i - \bar{y})^2}

Strengths and weaknesses

Strengths

  • Fast to train and to predict
  • Weights are directly interpretable
  • Closed-form solution; no hyperparameters
  • A strong baseline for any regression task

Weaknesses

  • Only captures straight-line relationships unless you engineer features
  • Sensitive to outliers (squared loss)
  • Unstable weights when features are highly correlated

Reach for it when…

The target is a number, the relationship is roughly linear (or can be made linear with transformed features), and you want a model you can explain.

Check your understanding

Question 1

Q1A weight wj=3w_j = 3 in a linear regression means…

Question 2

Q2Why might you prefer gradient descent over the normal equation?

Question 3

Q3The residual plot shows a clear U-shape. What does it tell you?

Lambdian Lab

Least squares from scratch

Implement linear regression two ways and check both against scikit-learn.

  • add_bias(X): add a column of ones as the first column.
  • fit_normal(X, y): return the weight vector (bias first) using the normal equation. Use np.linalg.lstsq or np.linalg.solve, not an explicit inverse.
  • fit_gd(X, y, lr, epochs): the same weights by batch gradient descent, starting from zeros.
  • predict(X, w) and r2(y, y_hat).
Open the labPython + NumPy + scikit-learn runs in your browser. Sign-in keeps your code and attempts.