Toolkit 0.1 // Toolkit

Vectors and Matrices.

How do you do arithmetic on a whole table of data at once?

Reading time
12 min

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:

x=[4, 7]x = [4,\ 7]

That list is a . The order matters: the first entry is always study, the second always sleep. A single ordinary number, by contrast, is called 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 (4,7)(4, 7). 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.

[3, 1]+[1, 3]=[4, 4]2×[3, 1]=[6, 2][3,\ 1] + [1,\ 3] = [4,\ 4] \qquad\qquad 2 \times [3,\ 1] = [6,\ 2]

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.

Figure

Adding arrows, stretching arrows

absum
  • 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]
1.0
Drag the two round handles.
The orange arrow is the sum. The dashed arrow is b, moved so that it starts where a ends. Try it: drag the tips of a and b and check the sum against the numbers. Then pull the slider below zero and watch a flip.

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 .

a⋅b=a1b1+a2b2+⋯+adbda \cdot b = a_1 b_1 + a_2 b_2 + \dots + a_d b_d

multiply each pair of matching entries, then add everything up

ExampleA prediction is a dot product

Suppose each hour of study is worth 5 points and each hour of sleep is worth 2. Collect those into a vector of weights, w=[5, 2]w = [5,\ 2]. For the student with x=[4, 7]x = [4,\ 7]:

w⋅x=5×4+2×7=20+14=34w \cdot x = 5 \times 4 + 2 \times 7 = 20 + 14 = 34

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.

Figure

How much do two arrows agree?

ab
  • 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
Drag the two round handles. Try to make the dot product exactly zero, then negative.
The thick orange bar is the shadow that b casts along a. Try it: swing b around until the dot product is zero. Then keep going until it turns negative.
  • 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.
Checkpoint

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 .

X=[16476598]four students, two features eachX = \begin{bmatrix} 1 & 6 \\ 4 & 7 \\ 6 & 5 \\ 9 & 8 \end{bmatrix} \qquad \text{four students, two features each}

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.

Figure

One dot product per row

hours studiedhours sleptscore
16→17
47→34
65→40
98→61
weights52
Row B · weights
4×5 + 7×2
Score for student B
34
Shapes
4×2 times 2 gives 4
5
2
Each row is a student. Each row is combined with the same two weights to give that student's score. Try it: click each student in turn and check the arithmetic underneath. Then change the weights and watch all four scores update together.

This is why linear algebra is everywhere in machine learning. A model’s predictions for a million examples are written XwXw, 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 , written rows × columns. The matrix above is 4 × 2.

For XwXw to make sense, each row of XX must have as many entries as ww, because they are paired off in a dot product. The rule is:

( n×d ) matrix  ×  ( d ) vector  =  ( n ) vector(\,n \times d\,)\ \text{matrix} \;\times\; (\,d\,)\ \text{vector} \;=\; (\,n\,)\ \text{vector}

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.

Checkpoint

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).
You can now
  • 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.

Exerciseby hand

Let a=[2, −1, 3]a = [2,\ -1,\ 3] and b=[1, 4, 0]b = [1,\ 4,\ 0]. Work out a+ba + b, then 3a3a, then a⋅ba \cdot b.

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: a+b=[3, 3, 3]a + b = [3,\ 3,\ 3].

Stretching multiplies every entry: 3a=[6, −3, 9]3a = [6,\ -3,\ 9].

The dot product multiplies matching entries and adds: 2×1+(−1)×4+3×0=2−4+0=−22 \times 1 + (-1) \times 4 + 3 \times 0 = 2 - 4 + 0 = -2. It is negative, so the two vectors point slightly away from each other.

Exerciseby hand

Check that [3, 4][3,\ 4] and [−4, 3][-4,\ 3] have a dot product of zero. Then find a vector whose dot product with [2, 5][2,\ 5] 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

3×(−4)+4×3=−12+12=03 \times (-4) + 4 \times 3 = -12 + 12 = 0.

For [2, 5][2,\ 5], swap the entries and change one sign: [5, −2][5,\ -2] gives 2×5+5×(−2)=02 \times 5 + 5 \times (-2) = 0. So does [−5, 2][-5,\ 2], 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.

Exerciseby hand

Three students have features (hours studied, hours slept) of [4, 7][4,\ 7], [2, 8][2,\ 8] and [6, 5][6,\ 5]. A model uses weights w=[5, 2]w = [5,\ 2] 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:

  • 5×4+2×7+10=445 \times 4 + 2 \times 7 + 10 = 44
  • 5×2+2×8+10=365 \times 2 + 2 \times 8 + 10 = 36
  • 5×6+2×5+10=505 \times 6 + 2 \times 5 + 10 = 50

The matrix is (3 × 2), the weights are (2), and the result is (3): one prediction per student.

Exercisein code

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)        # ValueError

X @ 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.

Exercisewith the figure

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.

Last updated Spotted a mistake? Suggest an editWhat changed

In this chapter
  1. Top of the chapter
  2. 0.1.1A list of numbers
  3. 0.1.2Adding and stretching
  4. 0.1.3The dot product
  5. 0.1.4A table of numbers
  6. 0.1.5Keeping track of shapes
  7. 0.1.6In code
  8. Exercises
SearchNext ›
Search

    The Book of Machine Learning
    Search
    Reading settings
    Text size
    Colours

    Saved in this browser only.

    Keyboard shortcuts
    /
    Search the book
    ← →
    Previous and next chapter
    g
    Glossary
    c
    Table of contents
    e
    Jump to the exercises
    t
    Reading settings
    ?
    Show this list
    Esc
    Close a window or pop-in