Linear Regression the Matrix Way
Stack the data into a matrix and the answers into a vector , and the best-fitting weights are where the gradient of the squared error is zero: . Gradient descent walks down the same bowl and stops at the same place.
What the symbols mean
- Design matrix
The data table: one row per example, a column of ones first (for the bias), then one column per feature.
- Weights
The bias and one weight per feature, the numbers we're solving for.
- Targets
The true answers, one per example.
- Number of examples
How many rows the data has.
What the symbols mean
- Residual vector
Prediction minus truth for every example.
What the symbols mean
- Gram matrix
A small square matrix (one row and column per weight) of dot products between the columns of X.
Explanation
Linear regression is simply fitting the best straight line through data (or the best flat plane, when there are several inputs), where "best" means the squared prediction errors add up to as little as possible. Machine learning writes it with matrices so that one formula covers a line with one input and a model with a thousand. In , the pieces are (the data table: one row per example, one column per feature), (the answers we want to predict) and (the weights we're solving for). It's the same least squares you met in linear algebra, now reached by calculus: find where the gradient is zero. The transposes are just bookkeeping; bear with them.
Setting it up. For one example with features , the model predicts . That's a neuron with no activation, and is its bias (see The Artificial Neuron). Put a in front of each example's features and stack the rows into : then every prediction at once is , the leading is what multiplies , and the errors are . The loss is their mean square, the MSE from Loss Functions.
The gradient, derived. Write the squared length as a dot product and multiply out:
Look at it next to the one-variable version , whose derivative is . The matrix version works the same way: the gradient of (for symmetric ) is , and the gradient of is . You can check both by taking the partial derivative with respect to one (see Partial Derivatives). So
Set it to zero and the drops out: . Is that flat spot a minimum? Yes: , so the loss is a bowl that opens upward in every direction, and its only flat spot is the bottom.
Why they're called "normal." Rearrange to . Each row of is a column of , so this says the residual is perpendicular (normal) to every column of . In other words, is the orthogonal projection of onto the column space of : the exact picture from Least Squares and Orthogonal Projections. The calculus route and the geometry route land on the same equation.
The same answer gradient descent finds. Gradient descent walks downhill on this same bowl and stops where , which is the normal equations again. So which do you use? Solving directly costs about to build plus about to solve a system. A gradient step costs about . With a few hundred features, solve directly. With millions of features, or a model that isn't linear (every neural network), iterate. The step size has to respect the bowl's steepest curvature, the largest eigenvalue of the Hessian , as in The Learning Rate and Convergence.
When can't be inverted. If one column is a combination of others, say temperature in Celsius and again in Fahrenheit, infinitely many weight vectors fit equally well and is singular. The standard fix adds a small penalty to the loss, which turns the equations into , always solvable. That's ridge regression, the same L2 weight decay as in Overfitting, Bias–Variance and Regularization.
A common mistake. It's tempting to build from the features alone. Without the column of ones there's no , and the fitted line is forced through the origin, which is almost never what the data wants. The other classic slip is writing instead of : is (huge, one entry per pair of examples), while is small, one row and column per weight.
There's an animation further down where you choose the slope and watch the error bottom out exactly where the normal equations say.
See it
Worked examples
Fit to the points , , , with the normal equations.
- 1
Build with a column of ones (for ) and a column of values, and stack the values: , .
For the same data, take one gradient descent step from with learning rate . Then show the gradient is zero at .
- 1
At every prediction is , so the residual vector is .
Practice
Type your answer and check it. Solve them all to complete the lesson.
A dataset has 500 examples and 3 features. You add a column of ones to build . What size is ?
Use the normal equations to fit to , , . Enter .
Fit a line through the origin, , to , , . (Now is a single column of values.)
For data , , and the model , find at , where is the mean squared error. Enter .
A courier company models delivery time as . Four deliveries: 2 km took 10 min, 4 km took 14 min, 6 km took 20 min, 8 km took 24 min. Fit the model by least squares and predict the time for a 7 km delivery, in minutes.
A weather model uses three columns: ones, temperature in °C, and the same temperature in °F. What happens to the normal equations?
For the four points , , , , the MSE has Hessian . Gradient descent converges exactly when , where is the largest eigenvalue of . Find the largest learning rate that still converges, to 4 decimal places.
The hardest one here. Get it, and you've got this lesson.
Ridge regression minimizes . Derive the equations it solves, then fit , , , with (penalizing both and ). Enter .
Where it's used
Least squares is still the first model a data team fits: predicting delivery times, energy use from weather, or sales from ad spend. Libraries solve the normal equations (through a more stable factorization of ) when the feature count is moderate, and switch to gradient descent for huge or streaming datasets. The final layer of many neural networks is exactly a linear regression on features the earlier layers learned.