TL;DR
Linear regression predicts a number as a weighted sum of input features, plus a constant. You pick the weights by finding the line, or flat plane in higher dimensions, that makes the squared gaps between predictions and true values as small as possible. That choice has a closed-form answer, so no iterative search is needed when the problem is small enough.
It is the simplest model that learns from data, and it is the template for most of the rest of machine learning. Almost every later model is a version of this idea with a more flexible function inside.
Where you'll see it: in forecasting sales from advertising spend, in calibrating lab instruments, in the least-squares fit that many data tools run by default, and as the baseline any new model must beat.
Intuition
Drawing the best line through a cloud
Plot the data as points. Hours of practice on the horizontal axis, exam score on the vertical axis. You can see a rising trend, but many lines could pass near the cloud. You need a rule for which line is best.
The usual rule is to measure each point's vertical gap from the line, which is called its residual, square those gaps so that signs do not cancel and big misses count more, and add them up. The best line is the one with the smallest total. The method is called least squares because it minimises the sum of squares.
- best fit: y = 2.2 + 0.6x
A line compresses the whole cloud into two readable numbers: a slope (output change per unit of input) and an intercept (where the line starts).
The math
Given an input vector , the model predicts , where is the weight vector (one weight per feature), is the intercept (also called the bias), and means transpose: it turns a column into a row so the product is a single number.
To remove the separate intercept, add a constant feature to every input and fold into the weights. The model becomes . Stack the training inputs as the rows of a matrix (size ), and stack the true targets as a column vector .
The loss
We measure the fit with the mean squared error, the average of the squared residuals:
Here is the true output for example , is its input, and is the squared length of a vector, which is the sum of its squared entries. The second form is just the matrix version of the first. (See Mean Squared Error for the loss on its own.)
Finding the minimum
Expand the loss. Using with and :
- .
- Take the gradient with respect to , using the rules for Gradient of quadratic forms: .
- At a minimum the gradient is zero, so . These are the normal equations.
- If is invertible, solve for the weights:
The hat on marks an estimate computed from data. Because is a sum of squares of linear functions, it is convex, so this stationary point is the global minimum.
The one-feature case
With a single input, the formula becomes two lines of arithmetic. Let and be the sample means:
The slope is the covariance of and divided by the variance of . The intercept makes the line pass through the point . A useful consequence: the residuals always sum to zero.
Worked examples
Use the five points from the plot: .
- Means: and .
- Deviations from the mean: and .
- Numerator: .
- Denominator: .
- Slope . Intercept .
- Predictions at are . Residuals are .
- The residuals sum to , as promised. The sum of squared residuals is , so the MSE is .
- Interpretation: each extra hour of practice is associated with about 0.6 more points, and no line does better on these five points.
Build with a column of ones and a column of values, so .
- and . Here , , , and .
- The determinant is , so the inverse is .
- Multiply: .
- This matches the slope and intercept from the previous example, so the two routes agree.
An ice-cream shop fits daily sales (in units) against the day's high temperature in degrees Celsius, using 60 days of data between 18 and 30 degrees. The fitted model is .
- At : units. This is inside the range of the data, so it is a reasonable forecast.
- At : units. This is outside the range of the data.
- The arithmetic is fine, but the number is not trustworthy. A straight line says sales rise forever. In reality the shop runs out of stock, or customers leave the city in the heat, and the trend flattens or reverses.
Tradeoffs and failure modes
Linear regression is fast, has a closed-form answer, and its weights are interpretable. It is also rigid, and most of its failures come from that rigidity or from the squared loss.
| Situation | Problem | Better choice |
|---|---|---|
| Relationship is curved | A straight line misses the pattern, and residuals show a systematic arc | Add transformed features (such as ), or use a nonlinear model |
| Outliers in the data | Squaring makes one far-off point dominate the fit | Huber loss, or least absolute deviations |
| Features are strongly correlated | is nearly singular, so the weights swing wildly with small data changes | Ridge regression (L2 Regularization) |
| More features than examples () | is not invertible, so there are infinitely many exact fits | Ridge regression, or a regularised solver |
| Very many features | Inverting a matrix costs roughly operations | Gradient Descent on the loss |
| Errors have different variances | Every point is weighted equally, even noisy ones | Weighted least squares |
| Prediction far outside the data | The line extrapolates with no check | Collect data in that range, or use domain knowledge to bound the forecast |
A common mistake is to read the weights as causes. A large weight means the feature predicts the output well, given the other features. It does not prove the feature causes the output.
History
The method of least squares was published by Adrien-Marie Legendre in 1805, as a way to fit the orbits of comets to noisy observations. Carl Friedrich Gauss said he had been using it since the 1790s, and in 1809 he tied it to the bell-shaped error distribution. That link is why least squares is the right answer under Gaussian noise, a point we return to through Maximum Likelihood Estimation.
The word regression came later. In the 1880s Francis Galton studied how the heights of children relate to their parents' heights, and found that extreme parents tend to have children closer to average. He called this regression toward mediocrity. Karl Pearson and George Udny Yule then built the general framework of correlation and multiple regression around 1900, and the name stuck even though the subject had nothing to do with going backwards.
Check yourself
QuestionIn one sentence, what does 'least squares' minimise?Show answer
The sum of the squared residuals, meaning the squared vertical distances between each observed and the prediction . Squaring stops positive and negative errors cancelling and makes large misses count more.
QuestionFit a line to the points . What is the prediction at ?Show answer
The means are and . The numerator is , and the denominator is , so the slope is . The intercept is . At the prediction is .
QuestionWhy does the matrix formula need to be invertible, and what goes wrong if two features are exact copies of each other?Show answer
The formula multiplies by , which exists only when the columns of are linearly independent. If two features are identical, the columns are dependent, is singular, and there are infinitely many weight vectors that give the same predictions. The solver cannot pick one. Ridge regression fixes this by adding a small to , which makes it invertible.
QuestionA model fitted on temperatures between 20 and 30 degrees is used to forecast sales at 45 degrees. What is the main risk, and why is the linear formula not the problem?Show answer
The main risk is extrapolation: the model has never seen data near 45 degrees, and the real relationship may bend or flatten there. The linear formula itself is computed correctly. The problem is assuming the fitted pattern still holds outside the range where it was measured.