Maths toolkit2 / 17

Lesson 2 · Linear algebra

Vectors: lists of numbers

The problem

You run a pizza shop. You want to guess how long each delivery will take.

Two things matter most: how far away the customer is, and how bad the traffic is. So you describe each delivery with two numbers. A 5 km trip in light traffic (level 1) becomes:

(5,1)(5, 1)

That pair of numbers is a vector. Most of machine learning works on lists of numbers like this one. A photo, a sentence and a game position all become vectors before a model can use them.

This chapter covers four things you can do with vectors: add them, scale them, measure their length, and take dot products. For each one, you'll see what it means as well as how to compute it.

A vector is a list of numbers

A vector is an ordered list of numbers. Order matters: (5,1)(5, 1) is not the same delivery as (1,5)(1, 5).

We write vectors in bold, like x\mathbf{x}. The entries get subscripts: x1x_1 is the first entry and x2x_2 is the second. For our delivery, x1=5x_1 = 5 (km) and x2=1x_2 = 1 (traffic level).

Each entry is one measurement. In ML these measurements are called features, so a list of them is a feature vector.

A vector with two entries can be drawn as an arrow. It starts at the origin, the point (0,0)(0, 0), and ends at the point (x1,x2)(x_1, x_2). The arrow picture works in 2D and 3D. With more entries you can't draw it, but the maths stays the same.

Adding and scaling

There are two basic things you can do to vectors. Both work one entry at a time.

Vector addition adds matching entries:

(2,1)+(1,2)=(2+1, 1+2)=(3,3)(2, 1) + (1, 2) = (2 + 1,\ 1 + 2) = (3, 3)

Scalar multiplication multiplies every entry by the same number. A single number like this is called a scalar:

2⋅(2,1)=(4,2)2 \cdot (2, 1) = (4, 2)

Drag the arrow tips below. In the Add tab, the dashed arrows are copies. One copy of b\mathbf{b} starts at the tip of a\mathbf{a}, and one copy of a\mathbf{a} starts at the tip of b\mathbf{b}. In the Scale tab, move the slider and watch the arrow stretch, shrink and flip.

-6-6-4-4-2-2224466a + bab

a = (2, 1) · b = (1, 2)

a + b = (2 + 1, 1 + 2) = (3, 3)

Drag the dots. Adding puts arrows tip to tail, in either order. Scaling stretches an arrow along its own line; a negative k flips it.

Notice two things.

First, both dashed routes end at the same point. Going a\mathbf{a} then b\mathbf{b} gets you to the same place as b\mathbf{b} then a\mathbf{a}, so order doesn't matter for addition.

Second, scaling never moves an arrow off its line. It only changes how far along the line the arrow reaches, and which way it points. At k=0k = 0 the arrow shrinks to a single point.

Length

The length of a vector is the length of its arrow. Pythagoras gives it directly. For a=(3,4)\mathbf{a} = (3, 4):

∥a∥=32+42=25=5\lVert \mathbf{a} \rVert = \sqrt{3^2 + 4^2} = \sqrt{25} = 5

The double bars ∥⋅∥\lVert \cdot \rVert mean "length of". This length is one kind of norm, and it's the one this book means by "norm". With more entries you keep adding squares: ∥x∥=x12+x22+⋯+xn2\lVert \mathbf{x} \rVert = \sqrt{x_1^2 + x_2^2 + \dots + x_n^2}.

A vector with length 1 is a unit vector. To get one, divide any vector by its length. For example, (3,4)/5=(0.6,0.8)(3, 4) / 5 = (0.6, 0.8). A unit vector keeps only the direction.

The dot product

The dot product takes two vectors and gives back one number. You multiply matching entries, then add them up.

Worked example

Dot product of a = (2, 1, 3) and b = (4, 0, −1)

  1. Multiply matching entries: 2×4=82 \times 4 = 8, then 1×0=01 \times 0 = 0, then 3×(−1)=−33 \times (-1) = -3.

For vectors with nn entries, you do the same thing nn times. Writing out every term gets long, so we use sum notation:

a⋅b=∑i=1naibi=a1b1+a2b2+⋯+anbn\mathbf{a} \cdot \mathbf{b} = \sum_{i=1}^{n} a_i b_i = a_1 b_1 + a_2 b_2 + \dots + a_n b_n

The ∑\sum (capital sigma) means "add up". Read the line as: for each ii from 1 to nn, multiply aia_i by bib_i, then add all of those together.

What the number means

Predict first

Two arrows meet at a right angle (90°). What is their dot product?

In the figure, the dashed line drops from the tip of b\mathbf{b} straight down onto the line through a\mathbf{a}. The thick coloured segment is the shadow of b\mathbf{b} along a\mathbf{a}. Its proper name is the projection of b\mathbf{b} onto a\mathbf{a}. Drag b\mathbf{b} around and watch the shadow and the number change together.

-4-4-2-22244ab

a · b = 3 × 2 + 0 × 2 = 6

Angle between them: 45° · pointing roughly the same way

The dot product is the length of a times the signed length of b's shadow along a: negative when the shadow points backwards. Green means positive, pink means negative.

Here is what to notice:

  • When b\mathbf{b} points roughly the same way as a\mathbf{a}, the shadow points along a\mathbf{a} and the dot product is positive.
  • At a right angle, there is no shadow, and the dot product is zero.
  • When b\mathbf{b} points away from a\mathbf{a}, the shadow points backwards and the dot product is negative.
  • Make either arrow longer and the dot product moves further from zero.

So the dot product measures how much two vectors point the same way, scaled by their lengths. As a formula:

a⋅b=∥a∥ ∥b∥cos⁡θ\mathbf{a} \cdot \mathbf{b} = \lVert \mathbf{a} \rVert \, \lVert \mathbf{b} \rVert \cos\theta

Here θ\theta is the angle between the arrows. Read it as: length of a\mathbf{a}, times length of b\mathbf{b}, times cos⁡θ\cos\theta. The cos⁡θ\cos\theta part is 1 when the arrows line up, 0 at a right angle, and −1-1 when they point in opposite directions. So cos⁡θ\cos\theta decides whether the answer is positive, zero or negative.

Check it with numbers. Take a=(2,1)\mathbf{a} = (2, 1) and b=(1,2)\mathbf{b} = (1, 2). Their dot product is 2+2=42 + 2 = 4. Both have length 5\sqrt{5}, so 5×5×cos⁡θ=4\sqrt{5} \times \sqrt{5} \times \cos\theta = 4. That gives cos⁡θ=0.8\cos\theta = 0.8, so θ≈36.9°\theta \approx 36.9°.

Drag a\mathbf{a} to (2,1)(2, 1) and b\mathbf{b} to (1,2)(1, 2) in the figure, and the readout shows the same angle.

Divide the dot product by both lengths and you get cos⁡θ\cos\theta on its own:

cos⁡θ=a⋅b∥a∥ ∥b∥\cos\theta = \frac{\mathbf{a} \cdot \mathbf{b}}{\lVert \mathbf{a} \rVert \, \lVert \mathbf{b} \rVert}

This is called cosine similarity. It compares only direction and ignores length. For (2,1)(2, 1) and (1,2)(1, 2) it's 0.80.8: fairly similar directions. Later in the book, it's how we measure whether two words or two documents mean similar things (see embeddings).

DeeperWhy the cosine formula is trueWork out one triangle side two ways and the formula drops out. · 4 min

We have two ways to get a⋅b\mathbf{a} \cdot \mathbf{b}: multiply-and-add, and lengths times cos⁡θ\cos\theta. Why do they always agree? Look at the triangle made by a\mathbf{a}, b\mathbf{b} and the arrow from the tip of b\mathbf{b} to the tip of a\mathbf{a}. That third side is a−b\mathbf{a} - \mathbf{b}.

-4-4-2-22244a − bab

‖a − b‖² = 1² + (-1)² = 2

‖a‖² + ‖b‖² − 2 (a · b) = 5 + 5 − 2 × 4 = 2

‖a‖ = 2.24, ‖b‖ = 2.24

The third side of the triangle is a − b. Both lines of the readout always show the same number.

First way: use entries. The squared length of any vector is its dot product with itself. So:

∥a−b∥2=(a−b)⋅(a−b)=a⋅a−2 a⋅b+b⋅b=∥a∥2+∥b∥2−2 a⋅b\begin{aligned} \lVert \mathbf{a} - \mathbf{b} \rVert^2 &= (\mathbf{a} - \mathbf{b}) \cdot (\mathbf{a} - \mathbf{b}) \\ &= \mathbf{a} \cdot \mathbf{a} - 2\, \mathbf{a} \cdot \mathbf{b} + \mathbf{b} \cdot \mathbf{b} \\ &= \lVert \mathbf{a} \rVert^2 + \lVert \mathbf{b} \rVert^2 - 2\, \mathbf{a} \cdot \mathbf{b} \end{aligned}

The second line multiplies out the brackets, like (x−y)2=x2−2xy+y2(x - y)^2 = x^2 - 2xy + y^2. That works because the dot product is multiply-and-add, entry by entry.

Second way: use the angle. The cosine rule from school geometry gives the same side from the triangle's angle:

∥a−b∥2=∥a∥2+∥b∥2−2∥a∥∥b∥cos⁡θ\lVert \mathbf{a} - \mathbf{b} \rVert^2 = \lVert \mathbf{a} \rVert^2 + \lVert \mathbf{b} \rVert^2 - 2 \lVert \mathbf{a} \rVert \lVert \mathbf{b} \rVert \cos\theta

Put them together. Both lines describe the same side. Cancel the matching ∥a∥2+∥b∥2\lVert \mathbf{a} \rVert^2 + \lVert \mathbf{b} \rVert^2, and what's left is a⋅b=∥a∥∥b∥cos⁡θ\mathbf{a} \cdot \mathbf{b} = \lVert \mathbf{a} \rVert \lVert \mathbf{b} \rVert \cos\theta.

With numbers: for a=(2,1)\mathbf{a} = (2, 1) and b=(1,2)\mathbf{b} = (1, 2), the third side is (1,−1)(1, -1), so its squared length is 22. From entries: 5+5−2×4=25 + 5 - 2 \times 4 = 2. The figure shows both calculations for any arrows you choose.

The dot product as a score

Back to the pizza shop. Say each km adds about 4 minutes, and each traffic level adds about 6 minutes. Put those numbers in a weight vector w=(4,6)\mathbf{w} = (4, 6).

For the delivery x=(5,1)\mathbf{x} = (5, 1), the predicted time is:

w⋅x=4×5+6×1=26 minutes\mathbf{w} \cdot \mathbf{x} = 4 \times 5 + 6 \times 1 = 26 \text{ minutes}

Each weight says how much its feature matters. The dot product adds up feature × weight over all the features. A sum like this is a weighted sum. It appears in almost every ML model.

Change the weights below. Each bar shows one delivery's predicted time. The blue part comes from distance and the orange part comes from traffic.

  • Delivery A (2 km, traffic 0)

    4 × 2 + 6 × 0 = 8 min

  • Delivery B (5 km, traffic 1)

    4 × 5 + 6 × 1 = 26 min

  • Delivery C (3 km, traffic 2)

    4 × 3 + 6 × 2 = 24 min

Each delivery's time is weights · features. Move a slider to see which deliveries depend on which feature.

Predict first

You raise 'minutes per traffic level' from 6 to 12. Which delivery's time goes up the most?

Key idea

A model that predicts with w⋅x\mathbf{w} \cdot \mathbf{x} is a linear model. Real linear models usually add a constant too, w⋅x+b\mathbf{w} \cdot \mathbf{x} + b, which we'll add later. "Learning" means finding the weights w\mathbf{w} that make good predictions.

DigressionVectors with 768 numbersReal models use vectors with hundreds of entries. Nothing in this chapter changes. · 2 min

The vectors in real models are long. A word in a language model might be a vector with 768 entries, or many more. You can't draw an arrow in 768 dimensions.

You don't need to. Every operation in this chapter works entry by entry, so it works for any length. Adding is still adding matching entries. The dot product is still multiply-and-add. Cosine similarity still compares direction.

One thing does change. Make two long vectors whose entries are random numbers centred on zero. They almost always end up close to a right angle, so their cosine similarity is near zero. With 768 entries it's usually within about ±0.1. So in that setting, a cosine similarity well above zero is unlikely to be chance.

Real embeddings aren't fully random like this, and their similarities are often all a bit above zero. So treat it as a rule of thumb, not a test.

Common misconceptions

"Is a vector a point or an arrow?" Both pictures are useful. As a point, (5,1)(5, 1) is a location. As an arrow, it's a step from the origin. Adding vectors makes most sense with arrows: take one step, then the other.

"The dot product gives a vector." It doesn't. It gives a single number. Adding and scaling give vectors.

"A dot product of zero means one vector is zero." Not necessarily. It also happens when the vectors are at a right angle, like (3,0)(3, 0) and (0,2)(0, 2).

Recap

  • A vector is an ordered list of numbers. In 2D you can draw it as an arrow.
  • Adding vectors puts arrows tip to tail. Scaling stretches an arrow along its line.
  • Length comes from Pythagoras: ∥x∥=∑ixi2\lVert \mathbf{x} \rVert = \sqrt{\sum_i x_i^2}.
  • The dot product multiplies matching entries and adds them. It's positive when vectors point the same way, zero at right angles, and negative when they point apart.
  • A weighted sum w⋅x\mathbf{w} \cdot \mathbf{x} scores a feature vector. This is the core of a linear model.

Section 2 shows how to compute these in PyTorch.