Matrix Operations
Dotting weights with one flat gives one prediction. The agency has thousands of flats, and a loop over them is slow and clumsy. One matrix multiplication predicts every rent at once, and nearly every "shape mismatch" error in ML code comes from not knowing when that multiplication is allowed.
The rule
Inner sizes must match; outer sizes give the answer's shape.
Take the flats as a matrix with 5 rows (flats) and 3 columns (size, rooms, metro km), and the weights as a column with 3 rows: [0.3, 1, -1].
- Addition works entry by entry, so both matrices need the same shape.
- Scalar multiplication multiplies every entry: doubles every number.
- Transpose swaps rows and columns: is 3 × 5.
- Matrix multiplication needs the columns of to equal the rows of . Each entry of the result is a row of dotted with a column of .
Writing shapes side by side, : the inner 3s match, so exists, and the outer sizes give a 5 × 1 result, one prediction per flat.
import numpy as np
X = np.array([[40, 1, 2], [60, 2, 1], [80, 3, 3], [50, 2, 4], [70, 2, 1]])
w = np.array([0.3, 1, -1])
X @ w # array([11., 19., 24., 13., 22.])In NumPy, @ is matrix multiplication, while * multiplies entry by entry, stretching shapes where it can. So X * w runs without any error but returns a 5 × 3 table of products, not five predictions.
Order matters. and are usually different, and often only one of them exists at all.
The shortcut
Write the shapes next to each other and cancel the middle pair. If the middle pair differs, stop: the product is undefined. If it matches, what remains on the outside is the shape of the answer.
Write the shapes
X is 5 × 3 and w is 3 × 1. Side by side: (5 × 3)(3 × 1).
The same trick checks , which appears in the formula for linear-regression weights: cancels the 5s and gives 3 × 3, one row and column per feature.
Drills
Answer fast — trust the rule.
What is the shape of a 5 × 3 matrix times a 3 × 1 matrix?
Can you multiply X (5 × 3) by X (5 × 3)?
What is the shape of X transposed times X?
With w = [0.3, 1, -1], what is the prediction for flat C (80 m², 3 rooms, 3 km)?
Which statement about matrix multiplication is true?
Remember
- Inner sizes must match; outer sizes give the answer's shape.
- Shortcut: write shapes side by side and cancel the middle pair.
- Trap: assuming AB equals BA, or confusing entry-by-entry with matrix multiplication.
