# Toolkit 0.1: Vectors and Matrices

> Lists of numbers, the dot product, and what a matrix does to a vector. Opening question: How do you do arithmetic on a whole table of data at once?

From *The Book of Machine Learning*, a free interactive machine learning textbook. Interactive version, with figures to use: https://thebookofml.com/vectors-and-matrices/

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]
$$

That list is a vector. The order matters: the first entry is always study, the second always sleep. A single ordinary number, by contrast, is called a scalar.

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)$. 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] \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.

> **Interactive figure: Adding arrows, stretching arrows.** 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.
> (Use it at https://thebookofml.com/vectors-and-matrices/)

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 dot product.

$$
a \cdot b = a_1 b_1 + a_2 b_2 + \dots + a_d b_d
$$

**Example: A 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]$. For the student with $x = [4,\ 7]$:

$$
w \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.

> **Interactive figure: How much do two arrows agree?.** 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.
> (Use it at https://thebookofml.com/vectors-and-matrices/)

- **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.

**Check your understanding:** What is the dot product of [2, 0, 3] and [4, 5, 1]?

- 11 **(correct)** — 2×4 + 0×5 + 3×1 = 8 + 0 + 3 = 11.
- [8, 0, 3] — That multiplies matching entries but forgets to add them up. A dot product is always a single number.
- 15 — That adds all six numbers. Each entry is multiplied by its partner first.

## 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 matrix.

$$
X = \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.

> **Interactive figure: One dot product per row.** 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.
> (Use it at https://thebookofml.com/vectors-and-matrices/)

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

For $Xw$ to make sense, each row of $X$ must have as many entries as $w$, because they are paired off in a dot product. The rule is:

$$
(\,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.

**Check your understanding:** 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?

- 500 **(correct)** — X is 500 × 6 and w has 6 entries. The 6s pair off, leaving one prediction per house.
- 6 — There is one prediction per row of X, and X has 500 rows. The 6 is used up in the dot products.
- 500 × 6 — That is the shape of X itself. Each row collapses to a single number when it meets the weights.

**Common mistake: Fixing a shape error by guessing**

When code stops with a complaint about shapes, it is tempting to flip things around until the complaint goes away. That can produce code that runs and computes the wrong thing. Write the two shapes next to each other instead: (500 × 6) times (6). The inside numbers must match, and the outside numbers tell you the shape of the answer. If they do not match, one of your tables is not what you think it is.

## 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.

```python
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).

## What you should now be able to do

- 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

### Exercise (by hand)

Let $a = [2,\ -1,\ 3]$ and $b = [1,\ 4,\ 0]$. Work out $a + b$, then $3a$, then $a \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]$.

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

The dot product multiplies matching entries and adds: $2 \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.

### Exercise (by hand)

Check that $[3,\ 4]$ and $[-4,\ 3]$ have a dot product of zero. Then find a vector whose dot product with $[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 \times (-4) + 4 \times 3 = -12 + 12 = 0$.

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

### Exercise (by hand)

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

### Exercise (in 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:**

```python
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.

### Exercise (with 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

- M. P. Deisenroth, A. A. Faisal and C. S. Ong, *Mathematics for Machine Learning*, chapter 2. Free at [mml-book.github.io](https://mml-book.github.io).
- H. Kinsley and D. Kukieła, *Neural Networks from Scratch in Python*, chapter 2, [nnfs.io](https://nnfs.io).
- G. Sanderson, [Essence of linear algebra](https://www.3blue1brown.com/topics/linear-algebra), 3Blue1Brown.

## Next

A dot product turns weights into a prediction. To improve the weights you need to know how the prediction changes when a weight changes a little. Measuring that is the job of the derivative, in the next toolkit chapter.
