Skip to content

Linear regression with many features

Predict with a weighted sum of features, and find the weights by least squares in one step or by gradient descent on the same bowl, with the same answer.

Helps to know first
This topic

First, the picture

Two measurements, one number to predict. Below, a flat plane is fitted to forty points in two ways at once. Before it plays: will the step-by-step fit and the one-step formula end on the same plane?

Fitting a plane to points

Two features and a target; gradient descent on the mean squared loss, η = 0.5, beside the normal equations.

40 readings of two features x₁, x₂ and a target y, and a plane ŷ = w₁x₁ + w₂x₂ + b, flat at 0 to start (the features are centred). Right: the loss over the two weights as contours, with b at its best.

gradient descent after t steps: (w₁, w₂, b)
(0.000, 0.000, 0.000)
normal equations: (w₁, w₂, b)
(1.975, −0.886, 3.109)
0.00 / 13.22 s
Describe this picture

Two panels. On the left, 40 readings in three dimensions, two features x1x_1 and x2x_2 across the floor, each from −1 to 1, and the target yy up, with a plane y^=w1x1+w2x2+b\hat y=w_1x_1+w_2x_2+b through them; the view turns slowly. The plane starts flat at 0, with the features centred. On the right, a contour map of the loss against the two weights w1w_1 and w2w_2, with bb at its best, and a ball on it. In the clip gradient descent takes 30 steps with learning rate 0.5 from all weights zero. Step 1 lifts bb to the average of the targets, 3.109, where it stays. Then the plane tilts into the cloud on the left while the ball crosses the contours to the bottom on the right, and the plane stops where the ball stops. Readouts give the step tt and two lists of (w1,w2,b)(w_1,w_2,b): “gradient descent after t steps”, which changes at every step, and “normal equations”, which does not. After 30 steps they agree to three decimals: (1.975, −0.886, 3.109)(1.975,\,-0.886,\,3.109). There is a play button and no other control.

The model and the data matrix

Each example now has dd features, xi1,…,xidx_{i1},\dots,x_{id}, collected in the vector xi\mathbf{x}_i, and one target yiy_i, a number. There are mm examples; statistics writes nn for a sample size, and on these pages mm counts examples. The model is a weighted sum of the features plus a constant:

y^i=w1xi1+⋯+wdxid+b=w⊤xi+b.\hat y_i=w_1x_{i1}+\dots+w_dx_{id}+b=\mathbf{w}^\top\mathbf{x}_i+b.

The weights w=(w1,…,wd)\mathbf{w}=(w_1,\dots,w_d) and the bias term bb are the parameters, θ=(w,b)\boldsymbol\theta=(\mathbf{w},b). With one feature this is the line of Linear regression; with two it is a plane over the floor of the two features, the plane in the picture; with more, the same sum, though no longer something to draw.

The bias term is a weight on a feature that is always 1. So put a 1 into every xi\mathbf{x}_i as an extra feature and bb into w\mathbf{w} as its weight; from here on w\mathbf{w} holds bb too. Stack the examples as the rows of the data matrix X\mathbf{X}, mm rows and d+1d+1 columns, one of them all ones, and the targets as y=(y1,…,ym)\mathbf{y}=(y_1,\dots,y_m). All mm predictions are then one product:

y^=Xw.\hat{\mathbf{y}}=\mathbf{X}\mathbf{w}.

The loss and its gradient

The loss is the average squared residual of Models and loss, now over a plane:

J(w)=1m∑i=1m(yi−y^i)2=1m∥Xw−y∥2.J(\mathbf{w})=\frac1m\sum_{i=1}^{m}(y_i-\hat y_i)^2=\frac1m\lVert\mathbf{X}\mathbf{w}-\mathbf{y}\rVert^2.

Its gradient comes entry by entry, as in Partial derivatives and the gradient. The weight wqw_q appears in each prediction y^i\hat y_i once, multiplied by xiqx_{iq}, so the slope of (y^i−yi)2(\hat y_i-y_i)^2 along wqw_q is 2(y^i−yi)xiq2(\hat y_i-y_i)x_{iq}. Averaging over the examples and stacking the d+1d+1 entries,

∇J=2m X⊤(Xw−y).\nabla J=\frac2m\,\mathbf{X}^\top(\mathbf{X}\mathbf{w}-\mathbf{y}).

The loss is a bowl in the weights, and the gradient is zero at its bottom, where

X⊤X w=X⊤y.\mathbf{X}^\top\mathbf{X}\,\mathbf{w}=\mathbf{X}^\top\mathbf{y}.

Two routes to the bottom

In one step. Those are the normal equations, d+1d+1 equations in d+1d+1 unknowns. Solve them and the answer is exact, at once.

In linear algebra · the normal equations

Least squares in the linear algebra course reaches the same equations from the other side: the best y^\hat{\mathbf{y}} is the projection of y\mathbf{y} onto the columns of the data matrix, and the residual is at right angles to every column. There the matrix is A\mathbf{A} and the unknowns x^\hat{\mathbf{x}}.

Step by step. Or walk down the bowl by Gradient descent: wt+1=wt−η∇J(wt)\mathbf{w}_{t+1}=\mathbf{w}_t-\eta\nabla J(\mathbf{w}_t), with tt counting steps. Every step costs one pass through the data.

Now the answer to the question. Both routes end on the same plane: the bowl has one bottom, and the normal equations name it while gradient descent walks to it. In the clip, after 30 steps the two readouts agree to three decimals.

In the clip the two features were centred first: their averages were subtracted, so each feature column adds up to zero. That makes the column of ones square to the two feature columns, so the bias term separates from the weights. One step with η=0.5\eta=0.5 puts bb at the average of the targets, 3.109, and from then on the bowl in (w1,w2)(w_1,w_2) on the right is the whole story. The readings were made from y=3+2x1−x2y=3+2x_1-x_2 plus noise, so the fitted weights land near 2 and −1, at 1.975 and −0.886, not on them: forty noisy readings do not pin them exactly.

Which route to take depends on the size of the problem. With a few features, solving the normal equations is quick and exact. With very many features, or data too large to hold at once or arriving all the time, steps are cheaper, and Stochastic gradient descent takes them on a few examples at a time. And many models have no normal equations at all: from Logistic regression on, stepping is the only route.

Reading the weights

Each weight says how much the prediction changes per unit of its feature, with the others held still: w1w_1 is in units of the target per unit of x1x_1. So the size of a weight depends on the units. Measure a distance in kilometres instead of metres and its weight becomes 1000 times larger, for exactly the same model. A bigger weight does not mean a more important feature.

Features that move together are a second trap. If two columns of X\mathbf{X} are equal, the model can raise one weight and lower the other by the same amount without changing a single prediction: there are infinitely many best answers, and X⊤X\mathbf{X}^\top\mathbf{X} cannot be inverted. If two columns are only nearly equal, the bowl becomes a long, flat-bottomed valley:

Left: the worked example's two features are square to each other, and the loss over the two weights is a round bowl round its best weights (1.25, 1.75). Right: the same four targets with a second feature that nearly copies the first, x₂ = (1, 0.6, −0.6, −1) beside x₁ = (1, 1, −1, −1), give a valley 8.3 times longer than wide: along its floor the loss hardly changes, and the best weights sit far out, at (−5.75, 8.75). Contours at the same heights above the least loss in both.
Describe this picture

Two square maps of the loss over the weights w1w_1 and w2w_2, with bb at its best, each centred on its best weights, with contours at the same heights above the least loss: 0.25, 1, 2.25 and 4. On the left, “x₂ square to x₁”: the worked example below, whose two features are at right angles, gives four evenly spaced circles round (1.25,1.75)(1.25,1.75), a round bowl. On the right, “x₂ nearly a copy of x₁”: the same four targets with a second feature (1,0.6,−0.6,−1)(1,0.6,-0.6,-1) beside the first, (1,1,−1,−1)(1,1,-1,-1), give long, thin ellipses running from upper left to lower right and out of the map at both ends, a valley 8.3 times longer than wide. Its best weights sit far out, at (−5.75,8.75)(-5.75,8.75). There is no control.

The two features in the valley differ only in their middle two readings, yet the weights they lead to, −5.75 and 8.75, are far from the round bowl’s 1.25 and 1.75, and of opposite signs. Along the valley floor the loss hardly changes, so the data cannot tell the two weights apart: a little new noise slides the bottom far along the valley, and the weights swing while the predictions barely move. Conditioning measures how long the valley is. On such a bowl, gradient descent zig-zags as it did on the stretched bowl of Gradient descent.

Watch out

A weight’s size depends on its feature’s units, and the weights of features that move together are unstable. Neither says how much a feature matters.

Does another feature help?

Add a feature to a least-squares fit and the training error can only fall or stay: the fit could always set the new weight to 0 and do as well as before. That is exactly why the training error is a poor judge of a feature. Here is a feature of pure noise, a random number with nothing to do with the target, added to the two real ones.

mean squared error, average of 100 repeats00.040.080.120.08310.08060.09630.0997training errorerror on 40 new readings
  • two features
  • two features + one of pure noise
Averaged over 100 training sets of 40 readings: a third feature of pure noise lowers the training error a little, from 0.0831 to 0.0806 (it fell in all 100 sets), and raises the error on new readings a little, from 0.0963 to 0.0997 (it rose in 67 of the 100). On the training data an extra feature can only help; on new data it can hurt.
Describe this picture

A bar chart of mean squared error, from 0 to 0.12, each bar the average of 100 repeats with fresh training sets of 40 readings. Two groups, “training error” and “error on 40 new readings”, each with two bars: “two features” and “two features + one of pure noise”. With the noise feature the training error is a little lower, 0.0806 against 0.0831, and it fell in all 100 sets; the error on new readings is a little higher, 0.0997 against 0.0963, and it rose in 67 of the 100. There is no control.

The noise feature helped on the training readings in every one of the hundred repeats, because the fit found some chance pattern in it to use. On new readings that pattern is not there, and the error rose, in 67 of the 100 repeats and on average. Bias and variance of a model explains the size of both changes: each fitted coefficient takes about σ2/m\sigma^2/m off the training error and adds about as much to the error on new data, where σ2\sigma^2 is the variance of the noise, here 0.32=0.090.3^2=0.09, and 0.09/40=0.002250.09/40=0.00225.

Noise and least squares

Why squares? Suppose each target is the model’s value plus noise, yi=w⊤xi+εiy_i=\mathbf{w}^\top\mathbf{x}_i+\varepsilon_i, where the εi\varepsilon_i are independent, bell-shaped, with mean 0 and the same spread. Then the weights under which the readings are most likely are exactly the least-squares weights.

In probability and statistics · maximum likelihood is least squares

Maximum likelihood in the statistics course shows it: with bell-shaped noise of fixed width, making the likelihood largest is making the sum of squared errors smallest.

Worked example

Four examples (x1,x2,y)(x_1,x_2,y): (1,1,6)(1,1,6), (1,−1,2)(1,-1,2), (−1,1,3)(-1,1,3) and (−1,−1,0)(-1,-1,0). With columns ones, x1x_1, x2x_2, and w=(b,w1,w2)\mathbf{w}=(b,w_1,w_2):

X=[11111−11−111−1−1],y=[6230].\mathbf{X}=\begin{bmatrix}1&1&1\\1&1&-1\\1&-1&1\\1&-1&-1\end{bmatrix},\qquad \mathbf{y}=\begin{bmatrix}6\\2\\3\\0\end{bmatrix}.

The normal equations. The three columns are at right angles to each other, and each has squared length 4, so X⊤X=4I\mathbf{X}^\top\mathbf{X}=4\mathbf{I}. And X⊤y=(6+2+3+0, 6+2−3−0, 6−2+3−0)=(11,5,7)\mathbf{X}^\top\mathbf{y}=(6+2+3+0,\ 6+2-3-0,\ 6-2+3-0)=(11,5,7). So 4w=(11,5,7)4\mathbf{w}=(11,5,7):

b=2.75,w1=1.25,w2=1.75.b=2.75,\qquad w_1=1.25,\qquad w_2=1.75.

Check. The predictions are 2.75+1.25+1.75=5.752.75+1.25+1.75=5.75, then 2.25, 3.25 and −0.25. The residuals are 0.250.25, −0.25-0.25, −0.25-0.25 and 0.250.25, so the loss is 0.06250.0625, down from (36+4+9+0)/4=12.25(36+4+9+0)/4=12.25 with every weight zero.

Gradient descent. At zero, ∇J=24X⊤(0−y)=−12(11,5,7)=(−5.5,−2.5,−3.5)\nabla J=\frac24\mathbf{X}^\top(\mathbf{0}-\mathbf{y})=-\tfrac12(11,5,7)=(-5.5,-2.5,-3.5). One step with η=0.25\eta=0.25 goes to (1.375,0.625,0.875)(1.375,0.625,0.875), exactly halfway. One step with η=0.5\eta=0.5 lands on (2.75,1.25,1.75)(2.75,1.25,1.75), the answer. That works because this bowl is round: its curvature is 2mX⊤X=2I\frac2m\mathbf{X}^\top\mathbf{X}=2\mathbf{I}, 2 in every direction, so every step multiplies the distance to the bottom by 1−2η1-2\eta, which is 0 at η=0.5\eta=0.5. Any η<1\eta<1 converges; at η=1\eta=1 it bounces for ever.

A prediction. At (x1,x2)=(0,0)(x_1,x_2)=(0,0) the model predicts the bias term, 2.75.

Units. If x1x_1 were in kilometres rather than metres, w1w_1 would be 1.25×1000=12501.25\times1000=1250 per kilometre for the same predictions.

Where you’ll meet this

Energy use. A building’s daily energy use predicted from the outdoor temperature and the number of people inside, one weight each.

Sensor correction. A sensor whose reading drifts with temperature and supply voltage is corrected by a weighted sum of both at once.

Filters. The Wiener filter and linear prediction choose filter taps by the same normal equations, with past samples as the features.

In signal processing · taps by least squares

The Wiener filter and Parametric models and linear prediction in the signal processing course solve normal equations for filter taps: each tap is a weight, and each delayed sample a feature.

Reference card

QuantityFormulaNotes
Modely^i=w⊤xi\hat y_i=\mathbf{w}^\top\mathbf{x}_idd features and a 1 in xi\mathbf{x}_i; bb in w\mathbf{w}
All predictionsy^=Xw\hat{\mathbf{y}}=\mathbf{X}\mathbf{w}a column of ones in X\mathbf{X}, bb in w\mathbf{w}
LossJ(w)=1m∥Xw−y∥2J(\mathbf{w})=\frac1m\lVert\mathbf{X}\mathbf{w}-\mathbf{y}\rVert^2the mean squared residual
Gradient∇J=2mX⊤(Xw−y)\nabla J=\frac2m\mathbf{X}^\top(\mathbf{X}\mathbf{w}-\mathbf{y})
Normal equationsX⊤Xw=X⊤y\mathbf{X}^\top\mathbf{X}\mathbf{w}=\mathbf{X}^\top\mathbf{y}the bottom, in one solve
Descentwt+1=wt−η∇J(wt)\mathbf{w}_{t+1}=\mathbf{w}_t-\eta\nabla J(\mathbf{w}_t)the same bottom, step by step
A weightchange in y^\hat y per unit of its featuredepends on units
Equal columnsno single answerX⊤X\mathbf{X}^\top\mathbf{X} cannot be inverted
Another featuretraining error never risesjudge on new data

Keep reading with a free account.

By creating an account you accept the terms of use.

Sign in

Already have an account? Use the service you signed up with.

Or keep reading: get new lessons by email

Are you 13 or over?

Accounts and email updates are for people aged 13 or over. We keep only your answer, never your date of birth.

End of the lesson

Where to go next.

Phasorium

Account

Sign inKeep your place on any device

Subjects

Site

Look