You walk 3 blocks east and 1 block north. Then you walk 1 block east and 2 blocks north. Where are you now, compared with the start? Add the east parts, , and the north parts, : you are 4 blocks east and 3 blocks north of where you began. Walking one trip after another is adding vectors. This lesson turns that everyday idea into the small set of moves that machine learning is built from.
Adding vectors
A trip is a vector: means “3 right, 1 up”. A second trip is . Doing and then gives the total trip . Add the matching entries:
There are two pictures of the same sum:
- Tip to tail. Draw from the origin. Then draw starting at the tip of (an arrow can start anywhere; P1.B1). The sum is the arrow from the very start to the very end.
- Parallelogram. Draw and both from the origin. Complete the parallelogram. The sum is the diagonal from the origin.
Both vectors must have the same number of entries. is not defined: one of the vectors has an entry with nothing to pair it with. (You will meet the same rule again in the dot product, P1.B3.) You can only add two vectors from the same space, for example two vectors in .
With the sliders at and the widget shows the plain sum . Notice two things. The black arrow is the same whichever order you walk the two legs (switch on the other order). And its two entries are always the sums of the two entries of and , as the readout shows.
Scaling a vector
To scale a vector, multiply every entry by the same number. A single number like this is a scalar (P1.B1), and the name fits the job: a scalar scales. For :
What the number does to the arrow :
| Scalar | Effect on the arrow |
|---|---|
| stretches it, same direction | |
| no change | |
| shrinks it, same direction | |
| the zero vector (a dot with no direction; P1.B1) | |
| flips it to point the opposite way, and also stretches it if or shrinks it if |
So is twice as long as and points backwards: . All the scalings of one nonzero vector lie on a single line through the origin, the line along (for the zero vector they are all just the origin). (The length of is times the length of ; P1.B4 studies lengths.)
Try it in the widget: set and slide . The thick blue arrow stretches, shrinks and flips, and the sum is just .
Subtracting vectors
Subtraction is adding the negative: , where is flipped. Entry by entry:
There is a second, very useful picture. Draw and from the same start. is the arrow from the tip of to the tip of . Check: start at and walk , and you arrive at . With numbers: . This is why P1.B1 found the move from point to point as : “destination minus start”.
Order matters here, unlike in addition: is the flipped arrow, . In the widget, press a − b and tick “Show the arrow from b to a”.
The three depths
Intuition
Think of trips. Adding vectors is doing one trip after another; the total is the one trip that has the same effect. Scaling is doing a trip twice as far, half as far, or in reverse. Subtracting is “undo trip ”.
That is why the rules feel obvious: the order of two trips doesn’t change where you end up (on an open field with no one-way streets), and doing a trip and then undoing it gets you back to the start.
The analogy has a weak spot: you can add two trips, but not two places. “Paris plus Berlin” means nothing, while “Paris to Berlin” is a perfectly good trip. In we can treat points and trips as the same thing because there is an origin to measure from (P1.B1), but the idea that matters is the trip.
Math
For vectors and in and a scalar :
Addition needs and to have the same . Scaling works for any vector. In an expression like , the scaling happens first, as with ordinary numbers.
The result of each operation is again a vector in . So adding and scaling never take you out of the space, which is why “the space of all vectors with entries” is a good home for them.
Code
import numpy as np
a = np.array([3, 1])
b = np.array([1, 2])
a + b # array([4, 3])
2 * a # array([6, 2])
a - b # array([ 2, -1])
-b # array([-1, -2])NumPy does each operation entry by entry, exactly like the formulas. There is a runnable cell with the pitfalls further down.
The rules, and why they hold
Vector operations obey a few rules. You don’t need to memorise them as a list. Each one holds for a simple reason: every entry is an ordinary number, and ordinary numbers already obey these rules. Here they are in plain words, with a check on , .
- Order doesn’t matter for addition: . (Two routes round the parallelogram reach the same corner.)
- Grouping doesn’t matter: , so we can write with no brackets.
- The zero vector does nothing: .
- Every vector can be undone: . (Walk there and back.)
- Scaling spreads over a sum: . Check with : and . (Doubling a whole trip is doubling each leg.)
- Scalars can be added first: . Check: .
- Scaling twice multiplies: , and .
Three things that are not rules:
- Subtraction is not order-free: (they are opposite arrows).
- There is no “vector times vector” yet. Multiplying two vectors can mean several different things. The dot product (P1.B3) gives a number; NumPy’s
a * bis a different operation, entry-by-entry multiplication, not part of the add-and-scale toolkit. - A scalar plus a vector is not defined in maths: means nothing. NumPy does accept
a + 3and adds 3 to every entry; that is a convenience called broadcasting (P1.B14), not a vector operation.
Go deeper Anything you can add and scale is a vector
P1.B1 promised this idea. Mathematicians call something a vector if you can add two of them and scale one by a number, and the rules above hold (the formal definition of a vector space lists about eight to ten such rules, depending on how the textbook counts them). Lists of numbers are the main example, but not the only one.
- Images. Add two same-size images pixel by pixel, and scale one to brighten or dim it. (With real images you also clip to the valid range, but the idea is the same.)
- Functions. Define and . A function is then a vector, and “the sum of two curves” is a curve.
- Polynomials. , and (also in P1.B1).
Everything in this lesson, including linear combinations below, works for all of these, because it only uses adding and scaling. P1.B7 returns to the formal definition. For machine learning, the main example stays : a model’s parameters, a data row and an embedding are all lists of numbers you can add and scale.
Linear combinations
Now put the two operations together. A linear combination of and is
for any scalars and (called the coefficients or weights). In words: scale each vector, then add. With more vectors it just continues: .
Worked example, with and :
You have already met special cases. is . is . A plain scaling is . The zero vector is . The widget above draws the general case: the blue arrow is , the pink arrow starts at its tip, and the black arrow is the result.
Which points can you reach? Drag so that it points along the same line as (for example and ) and move the sliders: the result never leaves that line. When and point in genuinely different directions, you can hit any point of the plane with a suitable and . (The widget’s sliders stop at and , so very distant points are out of reach there, but larger and would get you to them.) Try it as a game:
This question, “which vectors can I make from these?”, is the idea of span, and “do I really need both?” is independence. P1.B7 teaches both properly.
Go deeper Preview: a matrix times a vector is a linear combination
Take the matrix with columns and and multiply it by . The usual row-times-column recipe (P1.B6) gives . The same answer comes from a linear combination of the columns, with the entries of as weights:
So “a layer applies a matrix to a vector” can be read as “the layer mixes its columns using the input as weights”. P1.B5 and P1.B6 develop this; for now just notice that linear combinations are inside every neural-network layer.
Averages and interpolation
Two of the most useful linear combinations have their own names.
The average (mean) of vectors. Add them up and divide by how many there are. For vectors that is a linear combination with every weight equal to . Take , and :
Entry of the mean is the ordinary mean of entry of every vector. If each vector is one data example, the mean vector is the “average example”. For two vectors it is the midpoint: . (Press Average in the first widget.) A weighted average uses weights that are not negative and add up to 1; they need not be equal (the plain mean is the special case where they are).
Interpolation. To slide smoothly from to , use weights and :
At you get , at you get , and at the midpoint. The weights always add up to 1. There is a nice second reading using subtraction: , which says “start at and walk the fraction of the arrow ”. For , and this gives .
For between 0 and 1 the point stays on the segment between and . For outside that range it continues along the same line, which is called extrapolation.
Where this shows up in machine learning
| Where | The vector operation | Lesson |
|---|---|---|
| A gradient-descent step | : scale the gradient by the learning rate , then subtract | P1.F3 |
| One vector for a sentence | A simple baseline is to average the vectors of its words | P6.3 |
| Blending two training examples | Mixup trains on and mixes the labels the same way | P4.18 |
| Sliding between two latent codes | Interpolation between two vectors in a generative model | P8.3 |
| Residual connection | The block’s output is added to its input: | P7.7 |
| Attention | Each output is a weighted sum (linear combination) of value vectors | P7.3 |
A concrete gradient step: parameters , gradient and learning rate . Scale first: . Then subtract: . The whole step is one scaling and one subtraction. (The gradient itself is P1.F3’s topic.)
A concrete average, with the made-up toy word vectors from P1.B3: the average of and is .
A concrete residual connection: if the input is and the block computes , the output is . Addition needs matching dimensions, so must have as many entries as ; this is one reason the vectors in a transformer keep the same width from layer to layer.
Go deeper Word arithmetic: king − man + woman (famous, and often overstated)
Word embeddings (P6.3) give each word a vector. The famous example is that , a linear combination with weights , is close to . Mikolov, Yih and Zweig (2013) reported this for word vectors they trained, and it was repeated widely.
Keep three cautions in mind:
- It was shown for particular trained embeddings. It is not a law of vectors, and how well it works depends on the embedding and on the words.
- The usual test excludes the three words in the question (king, man, woman) from the possible answers. Nissim, van Noord and van der Goot (2020) point out that without that rule the nearest word can be one of the inputs themselves, which makes the result look less impressive.
- “Close to” means nearest among many words, not exactly equal.
So treat it as a fun, partly true illustration that directions in embedding space can carry meaning, not as proof that embeddings “understand” analogies. P6.4 explores embedding space with a proper explorer.
Vector operations in code
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The error text says the shapes “could not be broadcast together”. “Broadcasting” is the rule NumPy uses to decide whether two shapes can be combined (P1.B14); for two 1-D arrays it simply means they must have the same length, or one of them must have length 1. For the two arrays here, shapes (2,) and (3,), it fails. Use NumPy arrays, not Python lists, for vector maths: with lists, + concatenates and * 2 repeats, which is almost never what you want.
Check your understanding
What is ?
Add matching entries: 3 + 1 = 4 and 1 + 2 = 3. The vector (3, 2) would be the entry-by-entry product, (2, −1) is the difference a − b, and (−2, 1) is b − a.
Which of these sums is defined?
Addition pairs up matching entries, so both vectors need the same number of entries. Only (1, 2, 3) + (4, 5, 6) has that, and it equals (5, 7, 9).
What is for ?
Multiply every entry by −2: (−6, −2). The arrow is twice as long and points the opposite way. Multiplying only the first entry would give (−6, 1), and (5, 3) would be a + 2 added to each entry, which is not scaling.
For two vectors drawn from the same start, which arrow is ?
Starting at b and walking a − b lands on b + (a − b) = a. The opposite arrow, from a to b, is b − a. The parallelogram diagonal from the origin is the sum a + b.
For and , what is ?
2a = (6, 2), and subtracting b = (1, 2) gives (5, 0). The vector (7, 4) is 2a + b, (1, −3) is a − 2b, and (4, −2) is 2(a − b).
Exercises
- Compute .
Show answer
. - Compute .
Show answer
. - For write , and , and say what each does to the arrow.
Show answer
halves it, flips it, collapses it to the zero vector. - Find the vector from the point to the point , and the vector from to .
Show answer
and : opposite arrows. “Destination minus start.” - In the “reach the target” widget, which and hit the first target, ? Check by hand.
Show answer
, : . - Find the mean of , and .
Show answer
. Each entry is the mean of that entry: and . - Let and . Compute for and for . Which is between and ?
Show answer
For : , which is between them. For : , which is past on the far side from . - Do one gradient-descent step for , and .
Show answer
, so . - A residual connection adds to . Can it?
Show answer
No: has 3 entries and has 4, so the sum is not defined. A residual connection needs the block’s output to have the same size as its input. - In the code cell, look at
[1, 2] + [3, 4]with plain lists. What do you get, and how do you make+add entry by entry?Show answer
You get[1, 2, 3, 4], the lists joined. Convert them withnp.array(...)first and+adds entry by entry:[4 6].