Discover: a million-dollar multiplication
In 2006, Netflix offered a million dollars to anyone who could predict its customers' film ratings 10% more accurately than its own system. The prize was won in 2009, and three members of the winning team explained one of its key ideas in a magazine article. The idea fits on one line:
Spotted in the wild
Read it as “r hat u i equals q i transpose p u”. is the predicted rating of user for item (the hat marks an estimate, as in the first course). Each item gets a vector and each user a vector , with the same number of entries, . The paper suggests 20 to 100. Each entry measures a “factor”: how much of some quality a film has, and how much the user likes that quality. The factors are learned from the ratings. Some may be recognisable, such as comedy versus drama or the amount of action, and others have no obvious meaning at all. The article's own sketch uses two, placing films from serious to escapist on one axis, and predicts that a user called Gus will love Dumb and Dumber.
And ? You met the transpose notation in Chamber 6 of the first course. It says: multiply matching entries of the two vectors and add them up. Try it.
A film has factor vector and a user has . Multiply matching entries and add them up: what is the predicted rating ?
That operation is the dot product. It looks like bookkeeping, but it turns out to measure three things at once: how long vectors are, the angle between them, and how much they agree. This chamber shows how, and why the same multiplication sits inside recommenders, search engines and transformers.
Learn: the dot product
The dot product of two vectors in multiplies matching entries and adds:
Read it “u dot v”. The result is a single number, a scalar, which is why it's also called the scalar product. For example,
The same number goes by several names in papers. Machine learning prefers , “u transpose v”: a row times a column, which is exactly the sum above. Mathematicians often write , the inner product. Koren's is the same thing again, with a plain for the transpose.
- “u dot v”The dot product: multiply matching entries and add. The result is a single number.
- “u transpose v”The same dot product, written as a row times a column. The usual form in machine learning papers.
- “the inner product of u and v”Angle-bracket notation for the dot product, common in maths and theory papers.
- “the norm of v”The length of . With no subscript it nearly always means the Euclidean norm .
- “the two-norm of v”Euclidean length: . Also called the norm.
- “the one-norm of v”The sum of the absolute values of the entries: distance along a grid of streets (the taxicab or Manhattan norm).
- “the infinity-norm of v”The largest absolute value of any entry (the max norm).
- “v hat”The unit vector in the direction of . On a vector, a hat often means “normalised” rather than “estimated”.
- “the distance between u and v”The length of the arrow from the tip of to the tip of .
- “cos theta”The cosine of the angle between two vectors, known in machine learning as their cosine similarity. Always between and .
- “u is perpendicular to v”Orthogonal: at right angles, which means .
- “the projection of u onto v”The shadow of on the line through : the point of that line closest to the tip of .
| Symbol | Say it | Meaning | LaTeX |
|---|---|---|---|
| “u dot v” | The dot product: multiply matching entries and add. The result is a single number. | ||
| “u transpose v” | The same dot product, written as a row times a column. The usual form in machine learning papers. | ||
| “the inner product of u and v” | Angle-bracket notation for the dot product, common in maths and theory papers. | ||
| “the norm of v” | The length of . With no subscript it nearly always means the Euclidean norm . | ||
| “the two-norm of v” | Euclidean length: . Also called the norm. | ||
| “the one-norm of v” | The sum of the absolute values of the entries: distance along a grid of streets (the taxicab or Manhattan norm). | ||
| “the infinity-norm of v” | The largest absolute value of any entry (the max norm). | ||
| “v hat” | The unit vector in the direction of . On a vector, a hat often means “normalised” rather than “estimated”. | ||
| “the distance between u and v” | The length of the arrow from the tip of to the tip of . | ||
| “cos theta” | The cosine of the angle between two vectors, known in machine learning as their cosine similarity. Always between and . | ||
| “u is perpendicular to v” | Orthogonal: at right angles, which means . | ||
| “the projection of u onto v” | The shadow of on the line through : the point of that line closest to the tip of . |
The dot product obeys a few rules. Each one follows from ordinary arithmetic, one entry at a time.
- Symmetry: , since .
- It distributes over addition: .
- Scalars come out: .
- A vector dotted with itself is never negative: , and it is zero only when every is zero, that is, when .
The last rule is the doorway to length.
Learn: length, distance and three norms
In the plane, the arrow is the long side of a right-angled triangle whose other sides are and . Pythagoras gives its length as . In three dimensions, apply Pythagoras twice: the diagonal across the floor has length , and it forms a right angle with the vertical side , so the full length is . The pattern continues, and in we take it as the definition of the length, or norm:
So . The double bars are read “the norm of v”. Two consequences get used constantly:
- Scaling scales the length: . So dividing a non-zero vector by its own length gives a unit vector, of length 1, pointing the same way: . This is called normalising. For , .
- Distance is the length of a difference. The distance between the tips of and is , the length of the arrow between them (Chamber 1). Between and it's .
Euclidean length isn't the only useful way to measure a vector. Machine learning uses three regularly, each written with a subscript:
| Norm | Formula | For | Where you'll see it |
|---|---|---|---|
| (Euclidean) | distances, weight decay | ||
| (taxicab) | penalties that push weights to exactly zero | ||
| (max) | adversarial attacks that may change each pixel by at most |
With no subscript, almost always means . Each norm has its own “unit circle”, the set of vectors of length 1. For it's the ordinary circle; for it's a diamond with corners on the axes; for it's a square.
What makes something a norm? Three properties, true of all three:
- , and only for .
- .
- The triangle inequality: . Going straight is never longer than going round. You'll prove it for at the end of this chamber.
What is the length ?
Learn: the angle between two vectors
Here is the surprise. The dot product, defined by multiplying entries, also knows the angle between two arrows. Let's derive the connection.
Draw and from the origin, with angle (theta) between them. The arrow from the tip of to the tip of is , so the three arrows form a triangle with sides of length , and .
- 1
The law of cosines
For any triangle with sides and meeting at angle , the third side satisfies . (When , and this is Pythagoras.) For our triangle:
- 2
Expand the left side with the dot product
Squared length is a dot product with itself. Distribute, and use symmetry to merge the two middle terms:
- 3
Compare
The two right-hand sides are equal. Cancel and from both, then divide by :
So for non-zero vectors,
Lengths are positive, so the sign of the dot product is the sign of , and it tells you the kind of angle at a glance:
| Angle | Meaning | |
|---|---|---|
| positive | acute, under | the vectors broadly agree |
| zero | exactly | orthogonal, written |
| negative | obtuse, over | the vectors broadly disagree |
Orthogonality is the most useful case, because testing it needs no square roots and no cosines: two vectors are at right angles exactly when their dot product is zero. For example, . (By convention, counts as orthogonal to everything.)
The lab shows all of it live. The panel computes term by term; the marker at the origin is a blue arc when the angle is acute, a green square at a right angle and a red arc when it's obtuse.
Interactive lab
Dot product explorer
u · v > 0: the angle is acute, and the projection of u lands on v's side.
Dot product, term by term
u · v = u₁v₁ + u₂v₂
= (4)(2) + (1)(3)
= 8 + 3 = 11
length ‖u‖
√17≈ 4.12
length ‖v‖
√13≈ 3.61
angle θ
42.3°
cos θ
0.74
Projection of u onto v
(u·v / v·v) v = (11/13)·v
= (1.692, 2.538)
Vectors (or drag the heads)
Things to try:
- Find two vectors at right angles with every component non-zero. (The challenge.) Is there a quick recipe that turns any into a vector orthogonal to it?
- Set , note the dot product and the angle, then double to . The dot product doubles. What happens to the angle?
- Make the angle obtuse and watch the violet projection flip to point away from .
Two non-zero vectors have . What can you say about the angle between them?
One question should be nagging you. The derivation used a triangle, and triangles are drawn in the plane. What does “the angle between two vectors in ” mean? In higher dimensions we turn the result around and define the angle by . But that only makes sense if the fraction is always between and , because no angle has a cosine of 1.3. Is it? That's the most important inequality in this course.
Learn: the Cauchy–Schwarz inequality
Theorem (Cauchy–Schwarz). For all ,
with equality exactly when one of the vectors is a multiple of the other.
Dividing both sides by gives , which is exactly what we need. The proof uses one idea you already know, that a squared length can't be negative, and one clever choice.
Proof. If , both sides are 0 and there's nothing to prove. So suppose . For every real number , the vector has a length, and its square is not negative. Expanding with the rules of the dot product:
This holds for every , so we may pick the most useful one: . Substituting,
Multiply both sides by the positive number and rearrange: . Both sides are non-negative, so taking square roots keeps the inequality: .
For the equality case: if , every step above is an equality, so for our chosen . Only the zero vector has length 0, so . Conversely, if then both sides equal . (If , then is a multiple of .)
Where did that value of come from? The expression is a parabola in , and school algebra puts its lowest point at . We chose the that makes as short as possible, so the inequality “squared length ” is as sharp as it can be. Remember that : it comes straight back in the next section.
Learn: projection, a preview
Shine a light straight down onto the line through , and casts a shadow on it. That shadow is the projection of onto :
The coefficient is exactly the from the proof: the multiple of that comes closest to . And the leftover part, , is at right angles to , because
For example, with and : , so the projection is , and the leftover satisfies . The lab draws the projection as the violet arrow and the leftover as the dashed line: drag and watch the dashed line stay perpendicular.
This also gives the dot product a second picture. Since , the dot product is the (signed) length of the shadow of times the length of . Chamber 7 extends projection from lines to whole subspaces, and turns it into least squares and linear regression.
Learn: cosine similarity, from search to attention
Divide a dot product by both lengths and you get cosine similarity:
Thanks to Cauchy–Schwarz it always lies between and : 1 for vectors pointing the same way, 0 for orthogonal ones, for opposite ones. It ignores length entirely, which is often exactly right. In a vector of word counts, a long document has bigger numbers than a short one on the same topic. Normalising removes that, and leaves only the direction: what the document is about.
That's why Chamber 1's paper used it. Its analogy search, which you couldn't read then, is a cosine similarity:
Spotted in the wild
“Find the word whose vector has the greatest cosine similarity with .” Notice that the paper writes the dot product as , with no transpose at all. Papers are often relaxed about this, and now you can tell from context.
The same measure powers modern semantic search. Sentence-BERT (Reimers and Gurevych, 2019) trains a network to turn whole sentences into vectors that can be compared with cosine similarity, so that finding similar sentences becomes a matter of dot products between unit vectors.
Not every system normalises. Koren's recommender uses the raw dot product , so a longer vector counts for more, and transformer attention scores every query against every key with a raw dot product, . In the attention formula you met in the first course, is simply a table of these dot products, and the division by keeps them from growing with the dimension. Whether to normalise is a design choice, and now you know what each choice keeps.
You double every entry of and leave alone. What happens to and to the cosine similarity of and ?
Read beyond the course
The same ideas from four angles. Each one is free.
Book · free online · ~40 min
Mathematics for Machine LearningMarc Peter Deisenroth, A. Aldo Faisal & Cheng Soon Ong · Chapter 3, Sections 3.1–3.4
Norms, inner products, lengths, distances and angles, treated a level more generally than here: Section 3.2 shows that the dot product is only one of many inner products. Read it now to see which of this chamber's results depend on the dot product and which only need the rules.
Interactive · free online · ~30 min
Immersive Linear AlgebraJ. Ström, K. Åström & T. Akenine-Möller · Chapter 3: The Dot Product
Interactive figures of projection and the angle formula that you can drag, and in Section 3.4 the Cauchy–Schwarz and triangle inequalities with pictures. A good way to see this chamber's proofs geometrically.
Book · free online · ~45 min
Introduction to Applied Linear Algebra: Vectors, Matrices, and Least SquaresStephen Boyd & Lieven Vandenberghe · Chapter 3: 3.1 Norm, 3.2 Distance and 3.4 Angle
Norms and distances applied to real data: feature distances, nearest neighbours, and document similarity with word counts. Section 3.4 proves Cauchy–Schwarz a slightly different way from this chamber. Compare the two proofs.
Lecture notes · free online · ~15 min
Linear Algebra Review and ReferenceZico Kolter, updated by Chuong Do (Stanford CS229) · Section 2.1, Vector-Vector Products, and Section 3.5, Norms
The notes Stanford's machine learning course hands its students. Short and dense: read these two sections now as a check that the notation is second nature, and keep the rest for later chambers.
Papers and lectures
Koren, Bell and Volinsky wrote for a general computing magazine, so the article is eight pages with very little heavy mathematics. Read the section “A basic matrix factorization model”, which contains Equations 1 and 2, and look at Figure 2, the two-factor sketch. Then skim “Learning algorithms”: the stochastic gradient descent updates there use nothing but dot products, vector addition and scaling. Skip the later sections on biases, implicit feedback and time for now.
Matrix Factorization Techniques for Recommender SystemsYehuda Koren, Robert Bell, Chris Volinsky · IEEE Computer 42(8), 2009The Netflix Prize winners' own introduction to recommending by dot products. The DOI link leads to IEEE's paywalled page; many universities have access, and copies of the article are easy to find online.
Decode the paper · Eq. (2)
Matrix Factorization Techniques for Recommender SystemsYehuda Koren, Robert Bell, Chris Volinsky · IEEE Computer, 2009
How the recommender learns its vectors. Every user gets a factor vector and every item a factor vector , both in , and Equation 1 predicts a rating as their dot product. Equation 2 is what training makes small. Match each piece to its meaning.
Options
Sentence-BERT is a full research paper, but the parts you can read now are short. Read the abstract, then Section 3 up to and including “Regression Objective Function”, and look at Figure 2, where two sentence embeddings and meet in a box labelled cosine-sim(u, v). The triplet objective just after it compares Euclidean distances : norms from this chamber. Skip the experiments.
Sentence-BERT: Sentence Embeddings using Siamese BERT-NetworksNils Reimers, Iryna Gurevych · EMNLP-IJCNLP, 2019Made sentence embeddings practical for search and clustering by training BERT so that cosine similarity between its outputs means similarity in meaning.
Watch
The first part of this episode shows the dot product as projection: the length of one vector's shadow on the other, times the other's length, and why the order doesn't matter. Watch that part now and compare it with the projection section above. The second part, on duality, reads vectors as transformations: come back to it after Chamber 4.
Your turn
The lab's challenge is in the Learn section if you haven't cleared it. Here: measure two vectors every way this chamber knows, translate the formulas into NumPy, prove Pythagoras and the triangle inequality, and solve three problems, two of them straight from the papers.
Match · Quantity ↔ Value
Measure it
Let and . Match each quantity to its value.
Options
Match · Maths ↔ NumPy
From symbols to NumPy
Match each formula to the NumPy that computes it. Assume u and v are 1D NumPy arrays of the same length.
Options
Proofs
The puzzle proves Pythagoras' theorem for vectors in any number of dimensions. Then use Cauchy–Schwarz to prove the third property every norm must have.
Proof puzzle
Pythagoras, for vectors
Claim
If and are orthogonal, then .
Tap lines in the order they should appear. Not every line belongs. Tap a line in your proof to send it back.
Your proof
- Pick the first line below.
Available lines
Prove it yourself
The triangle inequality
Claim
For all vectors ,
(Going straight is never longer than going the long way round.) You may use the Cauchy–Schwarz inequality.
Your typeset proof appears here.
Code it up
The second problem computes Koren's Equation 2 exactly as the paper writes it, and the third is a small version of the search that Sentence-BERT made fast.
Problem 4·Warm-up
Right angles in a crowd
For define the vector by
How many pairs with are orthogonal, that is, have , with neither nor equal to the zero vector?
Problem 5·Standard
The recommender's report card
Koren, Bell and Volinsky (2009) learn a factor vector for every user and for every item by minimising their Equation 2, the regularised squared error over the set of known ratings:
The penalty is added once for every known rating, inside the sum, as in the paper. Compute for this untrained model, with factors:
- users with ; - items with ; - known ratings , with ; - .
Here means , and means . Give to 3 decimal places.
Problem 6·Challenge
The most similar pair
Sentence-BERT (Reimers and Gurevych, 2019) turns each sentence into a vector so that similar sentences can be found with cosine similarity. Their headline example is finding the most similar pair in a collection of 10,000 sentences. Here's a smaller version with made-up embeddings.
Generate numbers with the recurrence
so , , . For , embedding is the vector of eight consecutive values
Among all pairs , find the largest cosine similarity
and give it to 6 decimal places.
Key takeaways
- The dot product multiplies matching entries and adds: . A recommender's predicted rating is one.
- Length comes from it: . Distance is , and and are other useful ways to measure length.
- So does the angle: , derived from the law of cosines. The sign tells acute, right or obtuse, and exactly when .
- Cauchy–Schwarz, , makes angles meaningful in any dimension and implies the triangle inequality.
- Projection is the closest point on a line, and the leftover is orthogonal to it.
- Cosine similarity ignores length, which is why search and word analogies use it, while recommenders and attention use raw dot products.
Checkpoint
Prove it to the labyrinth
Answer every question to clear this chamber. First-try answers earn the most XP.
Compute for and .
What is the angle, in degrees, between and ?
For , which line is correct?
What is the unit vector in the direction of ?
Which statement is true for every pair of vectors ?
Project onto the line through . What is the first component of ?
In Koren, Bell and Volinsky's model , when is the predicted rating large and positive?
Transformer attention compares a query with a key , both in , through the score . Why divide by ?
End of the chamber
Clear this chamber
- Questions in this chamber (0/12 solved)Next unsolved
- Bonus: Right angles (+30 XP)
- Bonus: Problem 4: Right angles in a crowd (+20 XP)
- Bonus: Problem 5: The recommender's report card (+35 XP)
- Bonus: Problem 6: The most similar pair (+50 XP)
- Bonus: Proof: Pythagoras, for vectors (+25 XP)
- Bonus: Proof: The triangle inequality (+40 XP)
- Bonus: Decode the paper (+30 XP)
- Bonus: Match: Measure it (+25 XP)
- Bonus: Match: From symbols to NumPy (+25 XP)