Classical machine learning
Linear Regression Fundamentals
Learn ordinary least squares as projection, interpret coefficients conditionally, and fit linear regression without causal or extrapolation overclaims.
By the end you can
- Explain linear regression as a weighted feature model and a geometric projection
- Interpret coefficients using explicit units, transformations, and conditioning
- Distinguish predictive fit from causal and inferential claims
- Design a leak-resistant linear-regression workflow with residual checks
A weighted sum can be a serious scientific model
Linear regression predicts a numeric outcome by adding an intercept to weighted feature values. The apparent simplicity is what makes it useful. Every modeling choice is left in the open: representation, scale, interactions, loss, and residual error.
The relationship is linear in the coefficients. The raw inputs may be transformed first, through logs, splines, indicators, or interactions. That freedom is where the judgement lives. A column defined as 1000(Bk − 0.63)² is linear in its coefficient like any other. The model cannot tell you that someone chose the square, the centre and the scale before the estimator ever ran.
Linear in parameters does not mean the world must be a straight line in every raw variable.
Visual
Least squares as projection
Ordinary least squares picks a single prediction vector. It is the vector in the column space of the design matrix that is closest to the observed target.
Four objects are worth naming. The observed target is the vector of numeric outcomes in the training sample. The feature span is every prediction vector obtainable from the chosen columns and transformations. The fitted values are the orthogonal projection of the target onto that span. The residual vector is what is left over — the component the representation cannot fit.
- 01
Observed target
The vector of numeric outcomes in the training sample.
- 02
Feature span
All prediction vectors obtainable from the chosen columns and transformations.
- 03
Fitted values
The orthogonal projection of the target onto that span.
- 04
Residual vector
The remaining component that the representation cannot fit.
What ordinary least squares optimizes
The estimator minimizes the sum of squared residuals between observed and predicted outcomes. Squaring makes large errors influential. It also produces a convenient convex objective when the design is fixed.
This objective is not automatically the business cost. A few extreme errors can dominate the fit even when operational loss grows differently.
Case
Four data sets with identical regression output look nothing alike
Four data sets can return identical regression output and look nothing alike. That is the shortest argument there is for plotting the residuals, and Anscombe made it in 1973 in The American Statistician. He printed four fictitious data sets, each of eleven (x, y) pairs. Every one of them, he observed, “yields the same standard output from a typical regression program”. Eleven observations. Mean x of 9.0 and mean y of 7.5. A regression coefficient of 0.5, giving the equation y = 3 + 0.5x. A regression sum of squares of 27.50 and a residual sum of squares of 13.75. An estimated standard error of 0.118 on the slope. A multiple R² of 0.667.
Then look at the four scatterplots. Of the fourth Anscombe wrote that “all the information about the slope of the regression line resides in one observation—if that observation were deleted the slope could not be estimated”. In the third, all but one of the points lie close to a quite different line, y = 4 + 0.346x. The summary numbers cannot tell you which of the four you have.
Four was what one person could construct by hand in 1973. In 2017 the construction was automated. Matejka and Fitzmaurice, at Autodesk Research, started from Alberto Cairo's ‘Datasaurus’ and ran simulated annealing to breed twelve more data sets out of it. The thirteen hold 1,846 points between them. They agree to two decimal places on all five of the usual numbers: x mean 54.26, y mean 47.83, x standard deviation 16.76, y standard deviation 26.93, Pearson correlation −0.06. They look nothing alike. The first of the thirteen is the Datasaurus itself. They ship on CRAN as the datasauRus package's datasaurus_dozen data frame, whose description says it in two sentences: “The Datasaurus Dozen is a set of datasets with the same summary statistics. They retain the same summary statistics despite having radically different distributions.”
The point was not a curiosity of 1973 that better software has since retired. It is now a package you can install, plot, and watch produce thirteen different pictures from one column of summary output.
Comparison
A coefficient has several possible interpretations
The correct interpretation depends on design, preprocessing, and causal assumptions. The cheapest way to see that is to watch what happens to a coefficient when one column is added, and what happens to its sign when the data-generating process is not what the model assumes.
Start with conditioning. In autumn 1973, 4,526 people applied to the six largest graduate departments at the University of California, Berkeley. The aggregate figures sit on the manual page for R's UCBAdmissions data: “There were 2691 male applicants, of whom 1198 (44.5%) were admitted, compared with 1835 female applicants of whom 557 (30.4%) were admitted. This gives a sample odds ratio of 1.83, indicating that males were almost twice as likely to be admitted.” Now condition on the department applied to. The association disappears. Pooled with departmental autonomy taken into account, a 1975 paper in Science found instead “a small but statistically significant bias in favor of women”. No new data arrived. One column entered the design matrix, and every other coefficient came to mean something else.
Direction is not safe either. A pneumonia cohort of 14,199 patients — 9,847 for training, 4,352 for test — was reported in 1997, with “Has asthma” among the candidate predictors. Models fitted on it carried a negative weight on asthma. They had learned that a history of asthma lowers the risk of dying of pneumonia. The sign was an artefact of triage: asthmatic pneumonia patients were sent directly to intensive care. Caruana and five colleagues set it out in the first section of their 2015 paper: “The bad news is that because the prognosis for these patients is better than average, models trained on the data incorrectly learn that asthma lowers risk, when in fact asthmatics have much higher risk (if not hospitalized).” The coefficient predicted well and pointed the exact opposite way from the intervention it appeared to describe.
The most common misreading of a regression table has a name. It is the Table 2 fallacy, and Westreich and Greenland gave it that name in the American Journal of Epidemiology in 2013. The habit they describe is a familiar one: “a table might show odds ratios for one or more exposures and also for several confounders from a single logistic regression”. That, they argue, “can lead to mistaken interpretations of these estimates”. A single fitted model does not produce one kind of quantity. Listing the coefficients side by side invites “confusion of direct-effect estimates with total-effect estimates for covariates in the model”. The covariate coefficients “may also be confounded even though the effect estimate for the main exposure is not confounded”. Their remedy is not a better-annotated table. It is more models — “use of multiple models tailored to yield total-effect estimates for covariates”.
Three readings of the same number, then. A predictive slope is the expected change in prediction for one feature change while encoded peers stay fixed. It is conditional on the included columns, measured in target units per feature unit, sensitive to scaling and transformation, and not automatically causal. Berkeley shows how much that first clause carries. A standardized coefficient is that slope after features are placed on a common scale. It is useful for numerical comparison, it depends on the chosen standard deviation, it is still sensitive to correlation, and it is not a measure of feature importance. A causal effect is the change produced by an intervention under an identification strategy. It needs assumptions beyond regression, often randomization or adjustment, and it fails under confounding. The asthma weight is what claiming it from fit alone looks like.
Predictive slope
Expected change in prediction for one feature change while encoded peers stay fixed.
- Conditional on included columns
- Measured in target units per feature unit
- Affected by scaling and transformations
- Not automatically causal
Standardized coefficient
Slope after features are placed on a common scale.
- Useful for numerical comparison
- Depends on the chosen standard deviation
- Still sensitive to correlation
- Does not equal feature importance
Causal effect
Change produced by an intervention under an identification strategy.
- Requires assumptions beyond regression
- May need randomization or adjustment
- Can fail under confounding
- Cannot be claimed from fit alone
Position
A regression table is not a list of effects
In applied papers, model cards and dashboards alike, the fitted coefficients arrive as one column of numbers of apparently the same kind. They are sorted by size, and each is described as the effect of its variable. That reading is wrong for every row except the one the model was built around. The mistake is common enough to have been given a name in 2013: the Table 2 fallacy.
The reason is structural rather than statistical. A model is specified to answer one question — how one exposure relates to the outcome, with a chosen set of covariates held fixed. Those covariates were selected to serve that question and no other. Their own coefficients therefore estimate something different, mixing direct with total effects, and they “may also be confounded even though the effect estimate for the main exposure is not confounded”. Every number in the table is real. They are simply not all answers to the same question, and nothing in the printed output marks which is which.
The part that gets skipped is the remedy. It is not a longer caption or a more careful verb. It is more models — “multiple models tailored to yield total-effect estimates for covariates”. An effect estimate for a second variable costs a second model designed around it. Where that is out of budget, the honest move is to say what the table actually is. It is a description of what this model uses. Stop calling its rows effects.
Every row of that table but one is answering a question the model was never fitted to ask.
Example
The first regression many people ever fit
For decades the first regression a student ever fitted was a small hedonic price model on the Boston housing data. Harrison and Rubinfeld published it in 1978: 506 rows, 14 columns, small enough to fit in a lecture and to print in a textbook appendix.
Now read one of the columns. It is defined as 1000(Bk − 0.63)², where Bk is the proportion of black residents by town. Nobody measured that quantity. Somebody chose the square, chose the centre, and wrote the result into the design matrix before least squares saw a single row. The scikit-learn project said so plainly in the deprecation notice on its loader page: “The Boston housing prices dataset has an ethical problem: as investigated in [1], the authors of this dataset engineered a non-invertible variable "B" assuming that racial self-segregation had a positive impact on house prices [2].” load_boston was deprecated in version 1.0 and removed in version 1.2.
This is what "representation is a choice" costs when the bill arrives. Work through what the column does to every interpretation the fitted model can support.
- Units first: the fit is hedonic, so each coefficient is a price change per unit of its own column, with the rest of the design matrix held fixed. Every one of them is quoted relative to the columns that keep it company — this one included.
- The transform is a decision, not a measurement: 1000(Bk − 0.63)² is a squared distance from a chosen centre, scaled by a chosen constant. The estimator did not pick 0.63 or the exponent. The people who built the file did, and the assumption scikit-learn names is what those choices encode.
- Non-invertibility is the tell: the column squares a difference, so two different values of Bk can land on the same value of the column. No coefficient fitted on it can be read back to a proportion of residents. The information is not recoverable from the fit at any sample size.
- Interpretation limit: a coefficient on that column is a coefficient on the assumption. Reporting it as the effect of anything a town could measure is the Table 2 error with an extra layer of transformation on top, and nothing in the regression output marks it.
- Evidence limit: the remedy was not a footnote. The column encodes an assumption rather than a measurement, and scikit-learn removed the loader rather than annotate it. No residual plot, no R², and no amount of good fit repairs a design matrix that carries a belief as a variable.
Analogy
A rigid sheet laid through a cloud of points
A flat sheet is placed through a three-dimensional cloud. The placement makes the squared vertical gaps as small as possible. The sheet summarizes a global trend and leaves a residual for every point.
There is no sheet left to draw once a model carries many features, transformed columns, weights, and dependent observations. The picture hides more than that. Vertical distance is chosen by the loss rather than dictated by geometry alone.
Least squares finds the best surface available inside the chosen feature representation.
Steps
Fit a linear model that can be interpreted honestly
The algebra is easy. The contract around it requires care. Six steps, in order.
1. Define units — record target and feature units before scaling or transformation. 2. Build the design matrix — add indicators, transforms, interactions, and an intercept intentionally, and write down why each one is there; 1000(Bk − 0.63)² is what an unexamined step two leaves behind. 3. Inspect rank and correlation — find duplicate columns, near-collinearity, and unsupported contrasts. 4. Fit within a pipeline — keep imputation, encoding, and scaling inside the split. 5. Examine residuals — look by range, group, time, and influential observations; Anscombe's fourth set is eleven points whose whole slope rests on one of them. 6. Report conditional meaning — state what is held fixed, and avoid causal language without a design.
1. Define units
Record target and feature units before scaling or transformation.
2. Build the design matrix
Add indicators, transforms, interactions, and an intercept intentionally.
3. Inspect rank and correlation
Find duplicate columns, near-collinearity, and unsupported contrasts.
4. Fit within a pipeline
Keep imputation, encoding, and scaling inside the split.
5. Examine residuals
Look by range, group, time, and influential observations.
6. Report conditional meaning
State what is held fixed and avoid causal language without a design.
Key idea
Good fit does not validate extrapolation
A linear model can produce precise-looking values far beyond the feature range seen in training. The formula keeps extending even when physical, economic, or behavioral relationships change.
Deployment rules should detect unsupported ranges and decide whether to cap, abstain, or route elsewhere.
Nature published the textbook illustration on 30 September 2004. Four researchers took a century of Olympic 100-metre times and fitted straight lines to the winning times of men and of women. The coefficients of determination were 0.882 and 0.789. Then they extended the lines. One step beyond the data the result is defensible. For the 2008 Games the lines gave 10.57 ± 0.232 seconds for the women's race and 9.73 ± 0.144 seconds for the men's. Continued to their crossing point, the same two lines say that at the 2156 Olympics “the winning women's 100-metre sprint time of 8.079 s will be faster than the men's at 8.098 s”. Confidence intervals estimated by Markov chain Monte Carlo place that crossing anywhere between the 2064 and the 2788 Games. The authors state what the arithmetic cannot see. Their analysis “overlooks numerous confounding influences, such as timing accuracy, environmental variations, national boycotts and the use of legal and illegal stimulants.”
That extrapolation cost nothing. This one did. Challenger flew on 28 January 1986 at a predicted O-ring temperature of 31°F. That was 22°F below the 53°F of the coldest previous flight, STS 51-C of January 1985. The evening before, a teleconference considered exactly that gap. The Rogers Commission's report minutes the position Thiokol engineering took: “Recommendation by Thiokol (Lund) is not to fly STS 51-L (SAM-25) until the temperature of the O-ring reached 53 degrees Fahrenheit, which was the lowest temperature of any previous flight.” That is a range check, phrased in the plainest possible terms: do not read the relationship outside the data that supports it. It was not the recommendation that flew. A 1989 reanalysis refitted the 23 pre-accident launches. It put the probability of at least one complete field-joint O-ring failure at 31°F and 200 psi at 0.13, against 0.019 at 60°F — a risk its authors described as 600% higher.
Linearity makes extrapolation easy to compute, not safe to trust.
Figure
Prediction assumptions and inference assumptions are not identical
For point prediction, the most important question is whether the fitted relationship generalizes under the deployment distribution. Classical standard errors and hypothesis tests require additional assumptions. They concern sampling, dependence, variance, and model specification.
Do not import inferential confidence from software output without checking the data-generating design.
Google Flu Trends is what that failure looks like at scale. The service had fitted 50 million candidate search terms to 1,152 data points — a search wide enough to turn up terms that tracked the training window for reasons that had nothing to do with influenza. Four researchers reported that in Science on 14 March 2014. Under the heading "Big Data Hubris" they gave their verdict in one sentence: “In short, the initial version of GFT was part flu detector, part winter detector.” The fit was excellent and the deployment was not. From August 2011 the model missed high in 100 of the 108 weeks. A later independent reappraisal by Kandula and Shaman found GFT's mean squared error to be on average 2.5 times that of a simple lagged ILI estimate. The service was discontinued in 2015.
Nothing in the fitted output announced any of this. The training-window statistics stayed good while the thing the model was for stopped working.
A predictive model can be useful while its textbook p-values are invalid, and the reverse can also occur.
Key takeaways
- Linear regression is linear in its coefficients even when the design matrix contains nonlinear transformations — y = 3 + 0.5x is one such fit, and so is a column defined as 1000(Bk − 0.63)².
- Ordinary least squares projects the target onto the space spanned by the chosen feature columns. Eleven points can share every number that projection reports with three other data sets that look nothing like them, and 1,846 points can do it thirteen ways.
- Squared loss emphasizes large residuals and may not match the operational cost of prediction errors.
- A coefficient describes a conditional relationship in the encoded model, not automatically a causal effect: on 14,199 pneumonia patients the fitted weight on asthma pointed the opposite way from the risk.
- Collinearity, rank deficiency, unsupported ranges, and influential rows can destabilize interpretation. Berkeley admitted 44.5% of men and 30.4% of women until the department column was added, and Anscombe's fourth set puts the whole slope on one observation.
- Residual analysis and deployment-range checks matter as much as the fitted equation: 31°F was 22°F below anything the launch record covered, and Google Flu Trends missed high in 100 of the 108 weeks from August 2011.