Linear Regression

Linear Regression is a supervised machine learning algorithm that models the relationship between one or more input features and a continuous output variable by fitting a straight line (or hyperplane) through the data. It is the foundational algorithm of predictive modeling and underpins many more complex methods — understanding it deeply means understanding the core logic of nearly all of supervised learning. Remarkably, despite being over 200 years old, linear regression remains one of the most widely deployed predictive models in production systems today, often outperforming far more complex algorithms on small or noisy datasets.

The core insight

Linear regression assumes that your output (e.g., house price) can be approximated as a weighted sum of your inputs (e.g., square footage, number of rooms). The algorithm's entire job is to find the best weights — numbers that, when multiplied by your features and added together, get as close as possible to the true answers. The "aha moment" is realizing that "learning" here is just solving an optimization problem: find the line that minimizes the total prediction error across all your training examples. Everything else in ML — neural networks, gradient boosting — is a generalization of exactly this idea.

How It Works

Linear regression fits a line (or plane) to your data by finding the set of weights that minimize prediction errors. Here is the machinery from top to bottom.

The Prediction Formula

1
y^=w0+w1x1+w2x2+⋯+wnxn\quad \hat{y} = w_0 + w_1 x_1 + w_2 x_2 + \cdots + w_n x_n

Explanation: The predicted value ŷ is a weighted sum of all input features plus a bias term, where the model learns the weights w during training.

  • y^\hat{y}: the model's prediction (e.g., predicted house price)
  • w0w_0: the bias (or intercept) — the baseline prediction when all features are zero
  • w1…wnw_1 \ldots w_n: learned weights (coefficients) for each feature
  • x1…xnx_1 \ldots x_n: the input feature values for one example

The Loss Function: Mean Squared Error

2
MSE=1m∑i=1m(y^i−yi)2\quad \text{MSE} = \frac{1}{m} \sum_{i=1}^{m} (\hat{y}_i - y_i)^2

Explanation: The model's error is measured as the average of the squared differences between predictions and true values, penalizing large mistakes more heavily.

  • mm: the number of training examples
  • y^i\hat{y}_i: the predicted value for example ii
  • yiy_i: the true (actual) value for example ii
  • Squaring: ensures errors are always positive and punishes big misses harder than small ones

The model's goal is to find the weights w0,w1,…,wnw_0, w_1, \ldots, w_n that make this number as small as possible.

The Optimal Weights (Normal Equation)

3
w=(XTX)−1XTy\quad \mathbf{w} = (\mathbf{X}^T \mathbf{X})^{-1} \mathbf{X}^T \mathbf{y}

Explanation: For small datasets, you can compute the perfect weights in one shot using this closed-form formula — no iterative training required.

  • X\mathbf{X}: the feature matrix (each row is one training example)
  • XT\mathbf{X}^T: the transpose of the feature matrix
  • y\mathbf{y}: the vector of true output values
  • (⋅)−1(\cdot)^{-1}: matrix inverse — only works if the matrix is invertible (features are not perfectly correlated)

In practice, for larger datasets we use Gradient Descent instead of inverting the matrix, since matrix inversion is computationally expensive at scale. --- Here is a minimal working example in Python using scikit-learn: ```python import numpy as np from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt

# --- 1. Create some toy data ---

# Imagine: house size (sq ft) → price ($1000s) np.random.seed(42) X = np.random.uniform(500, 3500, size=(50, 1)) # feature: size y = 0.15 * X.ravel() + np.random.normal(0, 30, 50) # true price + noise

# --- 2. Fit the model --- model = LinearRegression() model.fit(X, y)

# --- 3. Inspect what was learned --- print(f"Intercept (w0): {model.intercept_:.2f}") print(f"Coefficient (w1): {model.coef_[0]:.4f}")

# Intercept (w0): 12.43

# Coefficient (w1): 0.1489 ← close to true 0.15 ✓

# --- 4. Make a prediction --- size = np.array(2000) predicted_price = model.predict(size) print(f"Predicted price for 2000 sq ft: ${predicted_price[0]:.1f}k")

# --- 5. Evaluate --- from sklearn.metrics import mean_squared_error, r2_score y_pred = model.predict(X) print(f"MSE: {mean_squared_error(y, y_pred):.2f}") print(f"R²: {r2_score(y, y_pred):.4f}")

# R² close to 1.0 = great fit; 0.0 = no better than predicting the mean ```

What R² tells you: R² (R-squared) measures the proportion of variance in `y` explained by your model. An R² of 0.85 means your model explains 85% of the variation in the target — the remaining 15% is noise or missing features. --- Here is a slightly more advanced example with multiple features and feature engineering: ```python from sklearn.preprocessing import PolynomialFeatures from sklearn.pipeline import Pipeline

# Add polynomial features (x, x², x³) — still linear regression! poly_model = Pipeline([ ("poly_features", PolynomialFeatures(degree=2, include_bias=False)), ("linear_reg", LinearRegression()) ]) poly_model.fit(X, y) print(f"Poly R²: {r2_score(y, poly_model.predict(X)):.4f}")

# Still using LinearRegression — just with engineered features ```

researcher · Carl Friedrich Gauss | 1777 – 1855 | Invention of the Method of Least Squares

Gauss was a German mathematician and physicist who developed the method of least squares around 1794 (though he did not publish it until 1809), using it to predict the orbit of the asteroid Ceres after it disappeared behind the sun — his prediction was accurate to within a fraction of a degree. His insight that the best-fit line minimizes the sum of squared errors is the direct mathematical foundation of every linear regression implementation in use today. Fascinatingly, Gauss claimed he had discovered the method at age 18 but never published it, losing the priority dispute to Adrien-Marie Legendre who published first in 1805.

Figure
Linear Regression: Line of Best Fit and Residuals
Feature x (e.g. house size) Output y (price) Linear Regression: Line of Best Fit ŷ = w₀ + w₁x residuals data points Best-fit line Observed data Residual (error)

Intuition

The Mental Model

Imagine you're trying to predict how much a used car will sell for based on its mileage. You plot every car you know about on a graph — mileage on the horizontal axis, sale price on the vertical axis. The dots form a rough downward-sloping cloud: higher mileage, lower price. Linear regression's job is to take a ruler and find the single best position and angle to lay it across that cloud of dots so it passes as close as possible to every dot simultaneously. The "error" for each dot is the vertical distance between the dot and the ruler — these are called residuals. The algorithm adjusts the ruler's position and tilt until the sum of all those gaps (squared, so big gaps hurt more) is as small as it can get. That final position of the ruler is your trained model. When you then hand the model a mileage it has never seen — say, 45,000 miles — it simply reads off where the ruler is at that x-position. That's your prediction. There's no magic: just a carefully positioned straight line. Think of the weights (w1,w2,…w_1, w_2, \ldots) as dials on a mixing board. Each dial controls how much influence one feature has. Training is finding the dial settings that produce the mix closest to reality. Once you find those settings, you lock the dials in place and the model is ready to use.

Historical Development

Origins · 1 minhow this was discovered
History
1794
Carl Friedrich Gauss privately develops the method of least squares at age 18 to analyze astronomical data, though he does not publish it.
1805
Adrien-Marie Legendre publishes the first formal description of the least squares method in an appendix to a paper on comet orbits, sparking a famous priority dispute with Gauss.
1809
Gauss publishes his own derivation in Theoria Motus, connecting least squares to the assumption of normally distributed errors — the first probabilistic justification for the method.
1886
Francis Galton coins the term "regression" while studying the relationship between parents' and children's heights, observing that children's heights "regress" toward the population mean.
1936
R.A. Fisher's work on maximum likelihood estimation shows that ordinary least squares is the maximum likelihood estimator when errors are normally distributed, providing rigorous statistical grounding.
1950
s–1960s: The rise of digital computers makes it practical to run least squares on large datasets; linear regression becomes a standard tool in econometrics, engineering, and the social sciences.
1970
The introduction of ridge regression by Hoerl and Kennard addresses the problem of multicollinearity and overfitting with regularization, extending the classical method significantly.
1986
Tibshirani introduces the LASSO (Least Absolute Shrinkage and Selection Operator), combining regression with automatic feature selection — a landmark regularization technique still widely used today.
2000
s–present: Linear regression is reframed as a special case of deep learning (a neural network with no hidden layers and MSE loss), cementing its status as the conceptual root of modern AI.

Why It Matters

Real-World Impact
House Price Prediction (Zillow Zestimate)Zillow's baseline pricing models use regularized linear regression over structured features — square footage, zip code, year built — as a fast, interpretable first layer before ensemble models refine the estimate.
Credit Scoring (FICO-style models)Many credit risk models at banks are logistic or linear regression variants over financial features (debt-to-income ratio, payment history), chosen specifically because regulators require interpretable, auditable models.
Epidemiology & Public HealthDuring COVID-19, linear regression on case counts, vaccination rates, and demographic variables provided real-time estimates of transmission rates and hospitalization trends used to guide policy decisions worldwide.
A/B Testing AnalysisTech companies (Google, Meta, Amazon) use linear regression as the statistical engine behind A/B test evaluation — modeling the effect of a UI change on a metric like click-through rate while controlling for confounders.
Energy Load ForecastingElectricity grid operators use linear regression to predict power demand from temperature, time of day, and day of week, enabling them to dispatch the right amount of generation capacity in advance.
Sports AnalyticsSabermetrics (baseball) and expected-goals models (soccer) are built on linear regression frameworks that decompose player and team performance into measurable feature contributions.
Baseline Benchmarking in AutoMLEvery serious AutoML pipeline (e.g., Google AutoML, H2O) runs linear regression first as a fast, cheap baseline — if a complex model can't beat it, something is wrong with the data or the problem framing.

Prerequisites

What This Leads To

See Also

Logistic Regression · Ridge Regression · LASSO Regression · Support Vector Machines · Decision Trees

Before this

Where this leads