Python for data · lesson 6 of 11
Parts in this lesson
A(x * w).sum()multiply in pairs, then add
Bx @ wthe dot product
CX @ Wmatrix multiplication: every row meets every column
DW.Tthe transpose: rows become columns

Matrix multiplication with @

Last updated

The most important line of code in machine learning is X @ w: multiply each example's features by a weight, add them up, and you have one prediction per example. Every layer of every neural network in this course, up to the largest language models, is built from it. In this lesson you'll work out a dot product by hand, multiply matrices with @, and learn the shape rule that tells you whether a multiplication makes sense.

By the end of this lesson you can

  • Work out a dot product as “multiply in pairs, then add”
  • Use X @ w to make one prediction per example
  • Predict the shape of a matrix product, and say when it isn’t allowed
  • Tell @ from *, and say why mixing them up gives no error

The dot product

One penguin, three features: x=(39.1,18.7,181). A simple model gives each feature a weight, a number saying how much that feature counts: w=(0.5,−1.0,0.1). Its output is each feature times its weight, added up. Run it:

dot.ipynb

x * w multiplies in pairs (lesson 0.4): 19.55, −18.7, 18.1. .sum() adds them: 18.95. That two-step sum is the dot product, and NumPy has it built in: np.dot(x, w), or x @ w.

In symbols, for d features:

x⋅w=∑j=1dxjwj=x1w1+x2w2+⋯+xdwd

In words: multiply the first feature by the first weight, the second by the second, and so on, then add them all. Bold letters like x are vectors (1-D arrays); xj is the jth number in one. In NumPy: x @ w.

18.950000000000003 is the decimal rounding you met in lesson 0.1. The weights here are made up; finding good ones is what training does, from Stage 3 on.

One prediction per example

Now do it for every penguin at once. Step through the picture first, with stores and prices instead of penguins:

Each row of one matrix meets each column of the other. Kilos sold by two stores (rows) of three items (columns), and each item’s price and cost per kilo. We want each store’s revenue and cost.4012535108453860529070kilos (2, 3)ricesugaroilBatangasLipaper kilo (3, 2)pricecostricesugaroilkilos @ per_kilo (2, 2)revenuecostBatangasLipa
1 of 5 Kilos sold by two stores (rows) of three items (columns), and each item’s price and cost per kilo. We want each store’s revenue and cost.

Then run it with the penguins' data matrix X:

predict.ipynb
  • X @ w takes the dot product of every row of X with w: one number per penguin. Shape (5, 3) @ (3,) gives (5,). The first value, 18.95, is step 1's answer.
  • W has two columns: two sets of weights, two outputs. X @ W takes every row of X with every column of W, giving (5, 2): two outputs for each of the five penguins.

The first is a linear model: Stage 3 is all about it. The second is a layer of a neural network, with two outputs instead of one: Stage 6 stacks them. Both are this one line:

yˆ=Xw

In words: the predictions yˆ (said "y hat"; the hat means "predicted") are the data matrix times the weights, one prediction per row. In NumPy: y_hat = X @ w.

The shape rule

@ doesn't work on any two arrays. The rule:

(n,d)@(d,k)→(n,k)

The inner lengths (the two ds) must be equal, and they disappear; the outer lengths make the result. A row of the first matrix has d numbers, and so must a column of the second, or they can't be paired. Run this:

shapes.ipynb

(5, 3) @ (2, 3): inner lengths 3 and 2 don't match. NumPy stops with a ValueError saying the input operand 1 has a mismatch in its core dimension 0: in plainer words, the first array's rows have 3 numbers, the second array's columns have 2.

Here the fix is the transpose, W.T, which flips rows and columns: (2, 3) becomes (3, 2), and (5, 3) @ (3, 2) gives (5, 2). Weights are often stored the other way round (PyTorch stores a layer's weights as (outputs, inputs)), so .T is a fix you'll make often. Before you reach for it, check that it's what you mean: the shapes will fit, but only the right weights give the right answer.

Wrong way: * where @ was meant

Two small matrices, multiplied both ways. Run them:

star.ipynb
  • A * B multiplies element by element: 1×10, 2×20, 3×30, 4×40.
  • A @ B is matrix multiplication: row 0 of A with column 0 of B gives 1×10+2×30=70, and so on.

Both run without an error, because two arrays of the same shape can always be multiplied element by element. So if you type * where you meant @, nothing stops you. With square matrices, even the shape of the answer looks right.

The way to catch it is the shape check. Before you multiply, say what shape you expect: "five penguins times three-by-two weights should give five by two". Then check .shape. When the data isn't square, X * W usually fails to broadcast, and the error is your clue.

Check what you learned

What is np.array([1, 2, 3]) @ np.array([4, 5, 6])?
X is (64, 10) and W is (10, 3). What shape is X @ W?
Predict, then check in step 3’s notebook: X is (5, 3) and W is (3, 2). Does X @ W.T work?

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