Linear models · lesson 4 of 12
Parts in this lesson
AX @ w + bone prediction per row
B2 / n * X.T @ (pred - y)the gradient for every weight at once
CX.shape, w.shape, pred.shapecheck shapes as you go

Many features

Last updated

One input is rare. A penguin’s body mass depends on its flipper length, its bill and more; a house price on its size, its age and where it is. This lesson grows the line into a model with a weight for every feature, writes its predictions and its gradient as matrix products, and trains it on the penguins. The code hardly changes, as long as every array has the shape you think it has.

By the end of this lesson you can

  • Write a linear model with many features as yˆ=Xw+b, and say the shape of every part
  • Compute predictions and the gradient 2nX⊤(yˆ−y) with matrix products
  • Train a many-feature linear model by gradient descent, and read its weights
  • Spot a shape mismatch that broadcasting hides

From one feature to many

With one feature the model was yˆ=wx+b. With d features, each gets its own weight:

yˆ=w1x1+w2x2+…+wdxd+b=w⋅x+b

That's a dot product (lesson 1.3): multiply each feature by its weight and add them up. Each weight says how much the prediction changes when that feature goes up by 1 and the others stay the same.

The task for this lesson: predict a penguin's body mass, in grams, from its bill length, bill depth and flipper length. That's d=3 features and 342 penguins:

mass.ipynb

X has one row per penguin and one column per feature (lesson 2.3); y has one mass per penguin.

Vectorised predictions

You could loop over the penguins and take a dot product for each. A matrix product does all 342 at once (lesson 1.4):

yˆ=Xw+b

X is 342×3 and w has 3 entries, so Xw has 342: row i of X dotted with w is penguin i's prediction. Adding b adds it to every one. This is called vectorised code: one array operation instead of a Python loop, and much faster (lesson 0.2).

mass.ipynb

The second cell standardises each column first (lesson 0.5), so every feature has mean 0 and spread 1. Lesson 3.7 explains why gradient descent needs this. Then it starts every weight at 0 and predicts: pred has shape (342,), one prediction per penguin.

The vectorised gradient

Lesson 3.3's gradient for one weight was 2n∑ieixi: the errors times that weight's input, summed. For weight j it's the same with xij, the j-th feature of example i. All d of them together are one matrix product:

∂ℒ∂w=2nX⊤(yˆ−y),∂ℒ∂b=2n∑i=1n(yˆi−yi)

In words: X⊤ (X turned on its side, lesson 1.4) has one row per feature; multiplying it by the 342 errors dots each feature's column with the errors. The result has one entry per weight, the same shape as w, so the update w←w−η∂ℒ/∂w works entry by entry.

Every array in one training step, with its shape drawn to scale:

Shape tracer342 penguins, 3 features
X(342, 3)one row per penguin, one column per featurew(3,)one weight per featurepred = X @ w + b(342,)(342, 3) @ (3,): one prediction per penguiny(342,)one label per penguinpred - y(342,)one error per penguinX.T @ (pred - y)(3,)one gradient per weight, like w

Every shape lines up: the gradient X.T @ (pred − y) has shape (3,), the same as w, so w − lr × gradient works. Dashed outlines are 1-D arrays.

Training on the penguins

The training loop is lesson 3.3's, with @ where there was *:

mass.ipynb

After 500 steps, b is 4,201.8 g: with standardised features, b is the mean mass, the prediction for a perfectly average penguin. The weights say how many grams one standard deviation of each feature adds: flipper length 705.8 g, bill depth 39.5 g, bill length 22.7 g. Flipper length does nearly all the work.

The predictions are off by 391 g on average, in the root-mean-square sense (MSE, in grams like the masses). Penguins weigh 2,700 to 6,300 g, so that's a useful model, though not a precise one: three lengths can't capture everything about a bird's weight.

Wrong way: (n,) against (n, 1)

NumPy has two ways to hold 342 numbers: a 1-D array of shape (342,), and a column, a 2-D array of shape (342, 1). They print almost the same, and they don't behave the same:

mass.ipynb

pred is (342,) and y_col is (342, 1). Broadcasting, NumPy's rule for combining arrays of different shapes, stretches each to match the other: the result is (342, 342), every prediction minus every penguin's mass. No error. The "loss" is a number, 891,254, instead of the right 193,612, and gradient descent on it would train quietly to the wrong answer.

Columns like this come from reshape(-1, 1), from slicing a table with double brackets (df[["mass"]]), and from some libraries. The defence is cheap: print shapes as you write each line, and check that the loss's input has the shape you expect. Turn on "Make y a column" in the shape tracer above to see where it goes wrong.

Check what you learned

X has shape (500, 8) and w has shape (8,). What shape is X @ w?
With standardised features, a model’s weight for flipper length is 705.8. What does that mean?
Predict, then check with the shape tracer: pred has shape (342,) and y has shape (342, 1). What shape is pred − y?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning