Linear Models
Lines, planes and the workhorse models of statistics.
Draw a straight line through a cloud of points and you have built one of the oldest and most useful models in science. Linear models price houses, forecast demand, filter spam and score loans, and the last layer of most neural networks is one. This lesson shows what a line can do, how a computer picks the best one, and what to do when a line is not enough.
What you’ll learn
- Fit a line by least squares, and read its slope, intercept and residuals.
- Explain why a single outlier can drag a least-squares line far off course.
- Turn a linear score into a probability with the sigmoid, and describe the decision boundary of logistic regression.
- Explain how extra features let a linear model bend, and how ridge and the lasso keep many features in check.
A line through the data
The simplest way to predict one number from another is a straight line. A linear regression with one input predicts
The slope says how much the prediction rises when grows by one unit, and the intercept is the prediction at . The hat on marks a prediction, to tell it apart from the true value .
For each training point, the vertical gap between the point and the line is its residual: positive if the point sits above the line, negative if below. A good line keeps the residuals small.
Suppose a line fitted to families reads: child's adult height (parents' average height) , in centimeters. What does it predict for a child whose parents average 190 cm?
Show the answer
183.5 cm
cm. That is tall, yet shorter than the parents: because the slope is below 1, predictions are pulled toward the middle of the population. The intercept, 60 cm, is the prediction for parents of height zero, a reminder that an intercept can be meaningless far outside the data.
Least squares: make the squared errors small
Infinitely many lines could pass through the cloud. The classic rule for choosing one, least squares, picks the slope and intercept that make the sum of squared residuals as small as possible:
Why squares? Squaring makes every miss count as positive, so misses above and below the line cannot cancel. It turns the total into a smooth bowl over the possible with a single lowest point, which a formula can find exactly. And it charges big misses heavily: one residual of 3 costs 9, three times as much as three residuals of 1.
A data-entry error puts one point 100 units below the trend, while every other point lies within 1 unit of it. How does the least-squares line respond?
- It ignores the point, since it is obviously wrong
- It tilts toward the point, because that point's squared residual dwarfs all the others combined
- It always moves exactly halfway toward the point
- It cannot be computed until the point is removed
Show the answer
B. It tilts toward the point, because that point's squared residual dwarfs all the others combined
A residual of 100 costs , more than all the other squared residuals together, so the best compromise moves the line toward the outlier. Spotting and handling such points is your job, or the job of a robust method (the Convergence lesson Robust Regression covers several).
Many features: planes and hyperplanes
Real predictions use more than one input. A house's price depends on its floor area, its age, its distance to the city center. With two features the model is
a flat plane hovering over the floor. With features it is a hyperplane: the same idea in more dimensions than you can picture, but not more than you can compute. Collect the features into a vector and the weights into , and the prediction is a dot product plus the intercept: . Multiply each feature by its weight and add.
| Features | Model | Picture | Numbers to learn |
|---|---|---|---|
| 1 | a line in the plane | 2 | |
| 2 | a flat plane in 3-D | 3 | |
| a hyperplane in dimensions |
Each weight is the change in the prediction when feature grows by one unit while every other feature stays fixed. That last clause is easy to forget, and it matters.
Think first A model of house prices from floor area and number of bedrooms gives bedrooms a negative weight. Does an extra bedroom make a house worth less?
Not necessarily. The weight compares houses with the same floor area, so an extra bedroom there means smaller rooms, which buyers may value less. On its own, bedroom count still rises with price, because bigger houses have more bedrooms. Weights describe patterns in the data with the other features held fixed; they are not promises about what a renovation would do.
A line between two classes
Linear models also answer yes-or-no questions: is this email spam, will this loan be repaid? Give each example a score , where large positive scores point to one class and large negative scores to the other. To turn a score into a probability, squash it with the sigmoid function:
This is logistic regression: the probability of class 1 is . Despite its name, it is a classification method. Predicting class 1 whenever that probability exceeds 50% is the same as predicting it whenever the score is positive, so the decision boundary, where the prediction switches, is the set of points with score exactly zero: a straight line in two dimensions, a hyperplane in more. The weights are chosen to make the observed labels as probable as possible, which amounts to minimizing the log loss; the Descent lesson derives it.
A spam filter gives an email the score . What probability of spam does the sigmoid assign?
Show the answer
88 %
. A score of would give : the curve is symmetric, . Each extra unit of score multiplies the odds of spam, , by .
When a line is not enough
A straight line cannot follow a curve. The fix is surprisingly simple: invent new features. Feed the model both and and it fits
a parabola. Yet the model is still linear in the sense that matters: the prediction is a weighted sum, so least squares works unchanged. The invented features are called basis functions; with powers of the method is polynomial regression.
The same trick works for classifiers. No straight line separates a disk of points from a ring around it. But add the feature , the squared distance from the center, and the boundary becomes a circle, while the model stays a weighted sum of features. Choosing good features is often the most important decision in building a linear model.
Think first If extra features make a linear model so flexible, why not add hundreds of them?
Flexibility cuts both ways. With as many weights as data points, the model can pass through every training point, noise included, and swing wildly in between. More features mean more variance: the fitted model changes a lot from one sample of data to the next. The next step shows the standard cure.
Taming many features: ridge and lasso
Regularization adds a price for large weights to the least-squares objective:
The knob sets the price. Ridge regression charges the sum of the squared weights and shrinks the weights, taken together, smoothly toward zero. The lasso charges the sum of their absolute values, and it does something ridge does not: it sets some weights exactly to zero, dropping those features from the model altogether. That sparsity makes lasso models easier to read.
| Descent lesson | What you will do there |
|---|---|
| Linear Regression & Least Squares | Derive the normal equations, see least squares as a projection, read and residual plots, and compare exact solvers with gradient descent. |
| Logistic Regression & Linear Classifiers | Derive the cross-entropy loss and its gradient, prove it is convex, choose thresholds, and compare logistic regression with the perceptron. |
| Regularization: Ridge & Lasso | Solve ridge in closed form, see why the lasso's corners give sparsity, and pick by cross-validation. |
| Basis Functions & Generalized Linear Models | Build polynomial, spline and radial features, and extend the linear recipe to counts and other targets with link functions. |
Key takeaways
- A linear model predicts with a weighted sum of features plus an intercept, . Each weight is the change in the prediction per unit of its feature, with the other features held fixed.
- Least squares chooses the weights that minimize the sum of squared residuals. Squaring makes big misses expensive, which is why one outlier can drag the whole line.
- Logistic regression feeds the same kind of score through the sigmoid to get a probability. Its decision boundary, where the score is zero, is a straight line or a flat hyperplane.
- Extra features such as (basis functions) let a linear model bend while staying linear in its weights; too many of them overfit.
- Ridge shrinks the weights toward zero, the lasso sets some exactly to zero. Both trade a little bias for much less variance, with the strength chosen on held-out data.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A model predicts exam scores from hours of study: . What does the 4 tell you?
- A student who does not study at all is predicted to score 4
- Each extra hour of study goes with a predicted score 4 points higher
- The predictions are off by 4 points on average
- Studying one more hour will raise any student's score by exactly 4 points
Show the answer
B. Each extra hour of study goes with a predicted score 4 points higher
The slope is the change in the prediction per unit of : one more hour, four more predicted points. It summarizes a pattern in the data; it does not guarantee what an extra hour does for a particular student.
Least squares chooses the line that minimizes…
- the number of points the line misses
- the sum of the perpendicular distances from the points to the line
- the largest single residual
- the sum of the squared vertical distances from the points to the line
Show the answer
D. the sum of the squared vertical distances from the points to the line
Least squares minimizes : vertical gaps, measured in the units of the quantity being predicted, then squared and added.
A logistic regression spam filter gives a new email the score . What does it predict?
- A 50% chance of spam: the email sits exactly on the decision boundary
- Certainly not spam
- Certainly spam
- Nothing, because a score of 0 is not allowed
Show the answer
A. A 50% chance of spam: the email sits exactly on the decision boundary
. Score zero is exactly the decision boundary; positive scores lean toward spam and negative ones away from it.
Which of these models is not linear in its weights (the 's)?
Show the answer
C.
In the weight sits inside the exponential, so the prediction is not a weighted sum of fixed features and least squares no longer has its simple solution. In the other three, , , , and are fixed features, each multiplied by a weight and added.
You fit a model with 50 features but suspect only a handful matter. Which method can set the weights of useless features to exactly zero?
- Ridge regression
- The lasso
- Plain least squares
- Adding even more features
Show the answer
B. The lasso
The lasso's penalty, the sum of absolute weights, has corners on the axes, so its solution often puts weights at exactly zero and drops those features. That is sparsity.
Go deeper
- Linear Regression & Least Squares · Fitting lines, the normal equations and the geometry of projection.
- Logistic Regression & Linear Classifiers · From scores to probabilities: the sigmoid, cross-entropy and decision boundaries.
- Regularization: Ridge & Lasso · Shrinking coefficients to trade a little bias for a lot less variance.
- Basis Functions & Generalized Linear Models · Polynomials, splines and link functions: linear models that bend.
Further reading
- G. James, D. Witten, T. Hastie & R. Tibshirani, An Introduction to Statistical Learning, 2nd ed. (Springer, 2021), chapters 3, 4 and 6.
- S. M. Stigler, "Gauss and the invention of least squares," Annals of Statistics 9(3), 465–474 (1981).