This is a toolkit chapter. It is optional, and you can skip it if lists of numbers and tables of numbers already feel comfortable. Everything here is used somewhere in the book, and nothing here needs more than multiplication and addition.
A list of numbers
A student studied for 4 hours and slept for 7. Write those two facts side by side:
That list is a
Vectors are how machine learning describes things. A student is two numbers. A house might be five: size, age, rooms, floor, distance to the centre. A small greyscale image of 28 by 28 pixels is a list of 784 brightness values. Whatever the object, once it is a vector the same mathematics applies.
A vector with two entries can also be drawn, as an arrow from the origin to the point . Pictures like that are a good guide to intuition even though real vectors have far too many entries to draw.
Adding and stretching
Two things can be done to vectors with almost no thought.
Add two vectors by adding matching entries. Stretch a vector by multiplying every entry by the same scalar.
In the picture, adding means placing one arrow at the tip of the other. Stretching changes an arrow’s length, and a negative scalar flips it round.
Adding arrows, stretching arrows
- a, stretched by the slider
- b
- b again, starting where a ends
- the sum
- 1.0 × a
- [3.0, 1.0]
- b
- [1.0, 3.0]
- Sum, entry by entry
- [4.0, 4.0]
These two operations are all that gradient descent uses. “Take the weights, and subtract the learning rate times the gradient” is one stretch and one addition.
The dot product
The most important operation in this book takes two vectors and returns a single number. Multiply matching entries, then add up the results. That is the
multiply each pair of matching entries, then add everything up
Suppose each hour of study is worth 5 points and each hour of sleep is worth 2. Collect those into a vector of weights, . For the student with :
Every linear model in this book, and every neuron in a neural network, makes its prediction this way: a dot product of weights and features, plus a bias.
The dot product also has a geometric meaning. It measures how much two arrows point the same way.
How much do two arrows agree?
- a
- b
- shadow of b on a
- a₁b₁ + a₂b₂
- 4.0×2.0 + 2.0×4.0
- Dot product
- 16.0
- Angle between them
- 37°
- Meaning
- pointing the same way
- Positive: the arrows point broadly the same way.
- Zero: they are at right angles. Neither says anything about the other.
- Negative: they point broadly opposite ways.
What is the dot product of [2, 0, 3] and [4, 5, 1]?
A table of numbers
A dataset has many examples. Stack their vectors as rows and you get a table: one row per student, one column per feature. A table of numbers is a
Multiplying a matrix by a vector means taking the dot product of each row with the vector. The result has one number per row. With the students as rows and the weights as the vector, one multiplication produces every student’s prediction at once.
One dot product per row
| hours studied | hours slept | score | ||
|---|---|---|---|---|
| 1 | 6 | → | 17 | |
| 4 | 7 | → | 34 | |
| 6 | 5 | → | 40 | |
| 9 | 8 | → | 61 | |
| weights | 5 | 2 |
- Row B · weights
- 4×5 + 7×2
- Score for student B
- 34
- Shapes
- 4×2 times 2 gives 4
This is why linear algebra is everywhere in machine learning. A model’s predictions for a million examples are written , three symbols, and a computer can carry that out far faster than a loop over the rows.
Keeping track of shapes
The size of a matrix is its
For to make sense, each row of must have as many entries as , because they are paired off in a dot product. The rule is:
The inner sizes must match, and they disappear. The outer size is what remains. When code involving matrices fails, mismatched shapes are the cause more often than anything else, so it is worth writing the shapes down before blaming the mathematics.
A dataset has 500 houses with 6 features each, and a model has one weight per feature. What is the shape of the predictions Xw?
In code
NumPy is the standard Python library for vectors and matrices. The @ symbol means “matrix multiply”, which for two vectors is the dot product.
import numpy as np
x = np.array([4, 7]) # one student: hours studied, hours slept
w = np.array([5, 2]) # one weight per feature
print(x + x) # [ 8 14] add entry by entry
print(2 * x) # [ 8 14] stretch
print(w @ x) # 34 dot product
X = np.array([[1, 6],
[4, 7],
[6, 5],
[9, 8]]) # four students as rows
print(X.shape) # (4, 2)
print(X @ w) # [17 34 40 61] every prediction at once
Key Takeaways
- A vector is an ordered list of numbers. It describes one example by its features.
- Vectors are added entry by entry, and stretched by multiplying every entry by a scalar.
- The dot product multiplies matching entries and adds them up. A linear model’s prediction is a dot product.
- A matrix is a table with one row per example. Matrix times vector is one dot product per row.
- Shapes must match on the inside: (n × d) times (d) gives (n).
- Add two vectors and stretch one by a number, by hand.
- Work out a dot product and say what its sign tells you.
- Multiply a matrix by a vector and predict the shape of the answer before computing it.
Exercises
Try each one before opening its solution. Getting stuck for a few minutes is where most of the learning happens.
Let and . Work out , then , then .
Hint
Add and stretch entry by entry. For the dot product, multiply matching entries, then add the three results.
Solution
Adding goes entry by entry: .
Stretching multiplies every entry: .
The dot product multiplies matching entries and adds: . It is negative, so the two vectors point slightly away from each other.
Check that and have a dot product of zero. Then find a vector whose dot product with is zero. What do such pairs look like when drawn as arrows?
Hint
Try swapping the two entries and changing the sign of one of them.
Solution
.
For , swap the entries and change one sign: gives . So does , or any stretch of either.
A dot product of zero means the arrows are at right angles. In the second figure of this chapter, it is the position where b has swung a quarter turn away from a.
Three students have features (hours studied, hours slept) of , and . A model uses weights and a bias of 10. What score does it predict for each student? What are the shapes of the matrix, the weight vector and the result?
Hint
Each prediction is one dot product of a row with the weights, plus the bias.
Solution
One dot product per row, plus the bias:
The matrix is (3 × 2), the weights are (2), and the result is (3): one prediction per student.
Put the three students from the previous exercise into a NumPy array X and the weights into w. Compute the predictions with X @ w + 10. Then try w @ X and explain what happens.
Hint
Write the two shapes next to each other and compare the inside numbers.
Solution
import numpy as np
X = np.array([[4, 7], [2, 8], [6, 5]])
w = np.array([5, 2])
print(X @ w + 10) # [44 36 50]
print(w @ X) # ValueErrorX @ w lines up (3 × 2) with (2): the inside numbers are both 2, so it works. w @ X lines up (2) with (3 × 2): the inside numbers are 2 and 3, which do not match, so NumPy refuses. The order matters.
Go back to the figure “How much do two arrows agree?”. Keeping the length of b about the same, swing it all the way round a. Where does b point when the dot product is largest? Where is it most negative? Where is it zero?
Hint
Watch the number as b passes through the direction of a, and again a half turn later.
Solution
The dot product is largest when b points the same way as a, and most negative when b points exactly the opposite way. It is zero twice in every full turn, each time b is at right angles to a.
So for arrows of fixed length the dot product is a measure of direction alone: how much of one arrow lies along the other.
References and further reading
- M. P. Deisenroth, A. A. Faisal and C. S. Ong, Mathematics for Machine Learning, chapter 2. Free at mml-book.github.io.
- H. Kinsley and D. Kukieła, Neural Networks from Scratch in Python, chapter 2, nnfs.io.
- G. Sanderson, Essence of linear algebra, 3Blue1Brown.