Linear regression
Fit a line to data: the model ŷ = w·x + b, residuals and mean squared error, the closed-form least-squares solution, and ridge/lasso regularisation — with a draggable scatter plot.
[[linear-regression|Linear regression]] predicts a number by drawing the best straight line (or flat plane) through data. It is over 200 years old, yet it is still the first model to try for any Regression problem: it trains in milliseconds, its parameters are directly interpretable, and it is the building block of neurons in neural networks. If a fancy model cannot beat linear regression, the fancy model is not worth it[1].
The model
- ŷ
- y-hat — the predicted value (e.g. a price)
- w
- weight (slope): how much ŷ changes per unit of x
- x
- the input Feature (one number, or the feature vector)
- ·
- multiplication (dot product when w and x are vectors)
- b
- bias (intercept): the prediction when every feature is 0
- w₁x₁
- weight of feature 1 times the value of feature 1 — that feature's contribution
- …
- the same pattern for every feature in between
- wₙxₙ
- the last feature's contribution; n = number of features
- wᵀx
- “w transpose x”: the dot product of the weight vector and feature vector, i.e. the whole sum w₁x₁ + … + wₙxₙ
▸Worked example
Each weight has a concrete meaning: wᵢ is how much ŷ changes when feature xᵢ increases by one unit, holding the others fixed. If a house-price model learns ŷ = 12·area + 150·bedrooms + 50 (million Rp), then one extra m² adds about Rp 12 million, and the bias 50 is the prediction when every feature is 0 (often not meaningful by itself).
Measuring how wrong the line is
For each example, the residual is eᵢ = yᵢ − ŷᵢ (actual minus predicted). We summarise all residuals with a loss function. The standard choice is the [[mse|mean squared error (MSE)]]. Squaring makes all errors positive, penalises big errors much more than small ones (an error of 10 counts 100× an error of 1), and gives a smooth bowl-shaped loss that is easy to minimise.
- MSE
- mean squared error: units of y squared (e.g. Rp²)
- RMSE
- root mean squared error (Root Mean Squared Error (RMSE)): same units as y
- MAE
- mean absolute error (Mean Absolute Error (MAE)): same units as y, robust to outliers
- (1/n)
- divide by the number of examples n: turns a sum into an average
- Σᵢ
- sum over all examples i = 1…n
- yᵢ
- true value of example i
- ŷᵢ
- predicted value of example i
- ²
- squared: makes errors positive and punishes big errors much more
- √
- square root
- |yᵢ − ŷᵢ|
- absolute error: the size of the miss, sign dropped (|−1| = 1)
▸Worked example
Finding the best line
Because MSE is a convex bowl in (w, b), it has exactly one minimum, and we can solve for it directly. Setting the derivatives to zero gives the ordinary least squares (OLS) solution. For one feature it has a beautiful form: the slope is the covariance of x and y divided by the variance of x, and the line always passes through the point of means (x̄, ȳ).
- w
- the best-fit slope (weight)
- Σ
- sum over all examples i = 1…n
- xᵢ
- feature value of example i
- x̄
- “x-bar”: the mean of all x values
- yᵢ
- target value of example i
- ȳ
- “y-bar”: the mean of all y values
- b
- the best-fit intercept (bias)
- X
- the data Matrix: n rows (examples) × d columns (features), plus a column of 1s for the bias
- XᵀX
- X transposed times X: a d×d matrix of feature-feature products (like the variance term)
- ⁻¹
- matrix inverse: the matrix version of “divide by”
- Xᵀy
- X transposed times the target vector y: feature-target products (like the covariance term)
▸Worked example
The alternative is [[gradient-descent|gradient descent]]: start from any line and repeatedly nudge w and b downhill on the loss. It reaches the same answer here, and unlike the closed form it scales to huge datasets and to models (like neural networks) that have no closed-form solution[3][4].
- Use the slope and intercept sliders to beat the least-squares MSE. You can get close but never lower — OLS is the exact minimum.
- Drag one point far above the others (an outlier). The line tilts toward it and MSE jumps: squared error gives that single point a lot of influence.
- Watch the residual segments: the best line balances them so positive and negative residuals cancel out (they sum to zero).
- Press ‘Run gradient descent’: w and b start somewhere wrong, the loss curve falls quickly then flattens, and the line settles on the same answer as the closed form.
Regularisation: ridge and lasso
With many features, correlated features, or few examples, OLS weights can become huge and unstable — a sign of Overfitting. [[regularization|Regularisation]] adds a penalty on weight size to the loss. Ridge (L2) shrinks all weights smoothly toward 0[5]. Lasso (L1) can set some weights exactly to 0, performing automatic feature selection[6]. Elastic Net mixes both[2].
- L
- the total loss that training minimises
- MSE
- the usual data-fit term (Mean squared error (MSE))
- α
- alpha — regularisation strength, a Hyperparameter (e.g. 0.01–100). 0 = plain linear regression
- Σⱼ
- sum over all weights j (the bias b is not included)
- wⱼ²
- weight j squared — the L2 penalty (Regularisation)
- |wⱼ|
- absolute value of weight j — the L1 penalty
▸Worked example
- What it is
- How strongly large weights are penalised.
alpha=0is plain least squares. - ↑ If you increase it
- Weights shrink toward 0 (Lasso: more become exactly 0). The model gets simpler and more stable, variance drops; too large → the line flattens toward the mean and the model underfits.
- ↓ If you decrease it
- Approaches ordinary least squares. Fits the training data more closely; with many or correlated features, weights can blow up and the model overfits.
- Typical values
- Search a log grid such as 10⁻³ … 10³ with cross-validation (
RidgeCV,LassoCV). Always scale features first — the penalty treats all weights equally.
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression, RidgeCV
from sklearn.metrics import mean_squared_error
X, y = fetch_california_housing(return_X_y=True) # target: median value, $100k
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=0)
ols = make_pipeline(StandardScaler(), LinearRegression()).fit(X_tr, y_tr)
ridge = make_pipeline(StandardScaler(),
RidgeCV(alphas=np.logspace(-3, 3, 13))).fit(X_tr, y_tr)
for name, m in [("OLS", ols), ("Ridge", ridge)]:
rmse = mean_squared_error(y_te, m.predict(X_te)) ** 0.5
print(name, "test RMSE:", round(rmse, 3))
print("chosen alpha:", ridge[-1].alpha_)
print("weights:", ridge[-1].coef_.round(2))HuberRegressor). Correlated features make individual weights unstable and hard to interpret. Extrapolation: the line keeps going forever; predictions far outside the training range are unreliable. Correlation ≠ causation: a positive weight does not mean that changing the feature will change the outcome.▸Go deeper: why squared error? A probabilistic view
Assume the data were generated as y = wᵀx + b + ε with Gaussian noise ε ~ N(0, σ²). The likelihood of the data is a product of Gaussian densities; taking the log turns it into −(1/2σ²)·Σ(yᵢ − ŷᵢ)² plus a constant. So maximising the likelihood is exactly minimising the squared error — least squares is maximum likelihood under Gaussian noise[4]. Assuming Laplace noise instead gives MAE.
‘Linear’ means linear in the parameters, not in x: ŷ = w₁x + w₂x² + b is still linear regression on the features [x, x²]. That is how polynomial regression works (see the overfitting lesson). History: Legendre published the method of least squares in 1805; Gauss published his version in 1809, saying he had used it since 1795.
Quiz
References
- [1]An Introduction to Statistical Learning (2nd ed.) — Ch. 3 Linear Regression, Ch. 6 RegularizationBookJames, Witten, Hastie & Tibshirani2021statlearning.com
- [2]scikit-learn User Guide — Linear ModelsDocsscikit-learn developersscikit-learn.org
- [3]Machine Learning Crash Course — Linear regressionCourseGoogledevelopers.google.com
- [4]Dive into Deep Learning — 3.1 Linear RegressionBookZhang, Lipton, Li & Smolad2l.aiIncludes the Gaussian-noise / maximum-likelihood derivation.
- [5]Ridge Regression: Biased Estimation for Nonorthogonal ProblemsPaperHoerl & Kennard1970doi.org
- [6]Regression Shrinkage and Selection via the LassoPaperTibshirani1996doi.org