Skip to content
AriadneTechnology

The Outer Ring · Chamber 2 of 9

Dot Products, Lengths and Angles

Measure similarity with one multiplication: norms, angles, cosine similarity and projections.

40 min 60 XP + 12 questions + 1 challengeMathVideoPapersProofsCodeLab

In this chamber you will

  • Compute dot products and norms, and interpret them geometrically
  • Find the angle between vectors and test orthogonality
  • Prove the Cauchy–Schwarz inequality
  • Use cosine similarity the way recommender systems and search do
DiscoverLearnRead beyondPapers & lecturesYour turn

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

r^ui=qiTpu\hat{r}_{ui} = q_i^T p_u
Koren, Bell & Volinsky (2009), “Matrix Factorization Techniques for Recommender Systems”, Equation 1

Read it as “r hat u i equals q i transpose p u”. r^ui\hat{r}_{ui} is the predicted rating of user uu for item ii (the hat marks an estimate, as in the first course). Each item gets a vector qiq_i and each user a vector pup_u, with the same number of entries, ff. 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 qiTpuq_i^T p_u? 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.

Quick check +20 XP

A film has factor vector qi=(1,2,−1)\mathbf{q}_i = (1, 2, -1) and a user has pu=(3,0,2)\mathbf{p}_u = (3, 0, 2). Multiply matching entries and add them up: what is the predicted rating r^ui=qi⊤pu\hat{r}_{ui} = \mathbf{q}_i^\top \mathbf{p}_u?

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.

DiscoverLearnRead beyondPapers & lecturesYour turn

Learn: the dot product

The dot product of two vectors in Rn\mathbb{R}^n multiplies matching entries and adds:

u⋅v=u1v1+u2v2+⋯+unvn=∑i=1nuivi.\mathbf{u} \cdot \mathbf{v} = u_1 v_1 + u_2 v_2 + \cdots + u_n v_n = \sum_{i=1}^{n} u_i v_i .

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,

(1,2,3)⋅(4,−5,6)=4−10+18=12.(1, 2, 3) \cdot (4, -5, 6) = 4 - 10 + 18 = 12 .

The same number goes by several names in papers. Machine learning prefers u⊤v\mathbf{u}^\top \mathbf{v}, “u transpose v”: a row times a column, which is exactly the sum above. Mathematicians often write ⟨u,v⟩\langle \mathbf{u}, \mathbf{v} \rangle, the inner product. Koren's qiTpuq_i^T p_u is the same thing again, with a plain TT for the transpose.

Notation in this chamber
  • u⋅v\mathbf{u} \cdot \mathbf{v}“u dot v”
    The dot product: multiply matching entries and add. The result is a single number.
    (1,2)⋅(3,4)=3+8=11(1, 2) \cdot (3, 4) = 3 + 8 = 11
  • u⊤v\mathbf{u}^\top \mathbf{v}“u transpose v”
    The same dot product, written as a row times a column. The usual form in machine learning papers.
    r^ui=qi⊤pu\hat{r}_{ui} = \mathbf{q}_i^\top \mathbf{p}_u
  • ⟨u,v⟩\langle \mathbf{u}, \mathbf{v} \rangle“the inner product of u and v”
    Angle-bracket notation for the dot product, common in maths and theory papers.
    ⟨u,v⟩=u⊤v\langle \mathbf{u}, \mathbf{v} \rangle = \mathbf{u}^\top \mathbf{v}
  • ∥v∥\lVert \mathbf{v} \rVert“the norm of v”
    The length of v\mathbf{v}. With no subscript it nearly always means the Euclidean norm ∥v∥2\lVert \mathbf{v} \rVert_2.
    ∥(3,4)∥=5\lVert (3, 4) \rVert = 5
  • ∥v∥2\lVert \mathbf{v} \rVert_2“the two-norm of v”
    Euclidean length: v12+⋯+vn2=v⋅v\sqrt{v_1^2 + \cdots + v_n^2} = \sqrt{\mathbf{v} \cdot \mathbf{v}}. Also called the ℓ2\ell_2 norm.
    ∥v∥2=v⊤v\lVert \mathbf{v} \rVert_2 = \sqrt{\mathbf{v}^\top \mathbf{v}}
  • ∥v∥1\lVert \mathbf{v} \rVert_1“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).
    ∥(3,−4)∥1=7\lVert (3, -4) \rVert_1 = 7
  • ∥v∥∞\lVert \mathbf{v} \rVert_\infty“the infinity-norm of v”
    The largest absolute value of any entry (the max norm).
    ∥(3,−4)∥∞=4\lVert (3, -4) \rVert_\infty = 4
  • v^\hat{\mathbf{v}}“v hat”
    The unit vector in the direction of v\mathbf{v}. On a vector, a hat often means “normalised” rather than “estimated”.
    v^=v/∥v∥\hat{\mathbf{v}} = \mathbf{v} / \lVert \mathbf{v} \rVert
  • ∥u−v∥\lVert \mathbf{u} - \mathbf{v} \rVert“the distance between u and v”
    The length of the arrow from the tip of v\mathbf{v} to the tip of u\mathbf{u}.
    ∥(4,6)−(1,2)∥=5\lVert (4, 6) - (1, 2) \rVert = 5
  • cos⁡θ\cos\theta“cos theta”
    The cosine of the angle between two vectors, known in machine learning as their cosine similarity. Always between −1-1 and 11.
    cos⁡θ=u⋅v∥u∥∥v∥\cos\theta = \frac{\mathbf{u} \cdot \mathbf{v}}{\lVert \mathbf{u} \rVert \lVert \mathbf{v} \rVert}
  • u⊥v\mathbf{u} \perp \mathbf{v}“u is perpendicular to v”
    Orthogonal: at right angles, which means u⋅v=0\mathbf{u} \cdot \mathbf{v} = 0.
    (2,1)⊥(−1,2)(2, 1) \perp (-1, 2)
  • proj⁡vu\operatorname{proj}_{\mathbf{v}} \mathbf{u}“the projection of u onto v”
    The shadow of u\mathbf{u} on the line through v\mathbf{v}: the point of that line closest to the tip of u\mathbf{u}.
    proj⁡vu=u⋅vv⋅v v\operatorname{proj}_{\mathbf{v}} \mathbf{u} = \frac{\mathbf{u} \cdot \mathbf{v}}{\mathbf{v} \cdot \mathbf{v}}\,\mathbf{v}

The dot product obeys a few rules. Each one follows from ordinary arithmetic, one entry at a time.

  • Symmetry: u⋅v=v⋅u\mathbf{u} \cdot \mathbf{v} = \mathbf{v} \cdot \mathbf{u}, since uivi=viuiu_i v_i = v_i u_i.
  • It distributes over addition: u⋅(v+w)=u⋅v+u⋅w\mathbf{u} \cdot (\mathbf{v} + \mathbf{w}) = \mathbf{u} \cdot \mathbf{v} + \mathbf{u} \cdot \mathbf{w}.
  • Scalars come out: (c u)⋅v=c (u⋅v)(c\,\mathbf{u}) \cdot \mathbf{v} = c\,(\mathbf{u} \cdot \mathbf{v}).
  • A vector dotted with itself is never negative: v⋅v=∑ivi2≥0\mathbf{v} \cdot \mathbf{v} = \sum_i v_i^2 \ge 0, and it is zero only when every viv_i is zero, that is, when v=0\mathbf{v} = \mathbf{0}.

The last rule is the doorway to length.

Learn: length, distance and three norms

In the plane, the arrow v=(v1,v2)\mathbf{v} = (v_1, v_2) is the long side of a right-angled triangle whose other sides are v1v_1 and v2v_2. Pythagoras gives its length as v12+v22\sqrt{v_1^2 + v_2^2}. In three dimensions, apply Pythagoras twice: the diagonal across the floor has length v12+v22\sqrt{v_1^2 + v_2^2}, and it forms a right angle with the vertical side v3v_3, so the full length is v12+v22+v32\sqrt{v_1^2 + v_2^2 + v_3^2}. The pattern continues, and in Rn\mathbb{R}^n we take it as the definition of the length, or norm:

∥v∥=v12+v22+⋯+vn2=v⋅v.\lVert \mathbf{v} \rVert = \sqrt{v_1^2 + v_2^2 + \cdots + v_n^2} = \sqrt{\mathbf{v} \cdot \mathbf{v}} .

So ∥(3,4)∥=9+16=5\lVert (3, 4) \rVert = \sqrt{9 + 16} = 5. The double bars are read “the norm of v”. Two consequences get used constantly:

  • Scaling scales the length: ∥c v∥=∣c∣ ∥v∥\lVert c\,\mathbf{v} \rVert = |c|\,\lVert \mathbf{v} \rVert. So dividing a non-zero vector by its own length gives a unit vector, of length 1, pointing the same way: v^=v/∥v∥\hat{\mathbf{v}} = \mathbf{v} / \lVert \mathbf{v} \rVert. This is called normalising. For (3,4)(3, 4), v^=(0.6,0.8)\hat{\mathbf{v}} = (0.6, 0.8).
  • Distance is the length of a difference. The distance between the tips of u\mathbf{u} and v\mathbf{v} is ∥u−v∥\lVert \mathbf{u} - \mathbf{v} \rVert, the length of the arrow between them (Chamber 1). Between (1,2)(1, 2) and (4,6)(4, 6) it's ∥(3,4)∥=5\lVert (3, 4) \rVert = 5.

Euclidean length isn't the only useful way to measure a vector. Machine learning uses three regularly, each written with a subscript:

NormFormulaFor (3,−4)(3, -4)Where you'll see it
ℓ2\ell_2 (Euclidean)∥v∥2=∑ivi2\lVert \mathbf{v} \rVert_2 = \sqrt{\sum_i v_i^2}55distances, weight decay λ∥θ∥22\lambda \lVert \boldsymbol{\theta} \rVert_2^2
ℓ1\ell_1 (taxicab)∥v∥1=∑i∣vi∣\lVert \mathbf{v} \rVert_1 = \sum_i \lvert v_i \rvert77penalties that push weights to exactly zero
ℓ∞\ell_\infty (max)∥v∥∞=max⁡i∣vi∣\lVert \mathbf{v} \rVert_\infty = \max_i \lvert v_i \rvert44adversarial attacks that may change each pixel by at most ϵ\epsilon

With no subscript, ∥v∥\lVert \mathbf{v} \rVert almost always means ℓ2\ell_2. Each norm has its own “unit circle”, the set of vectors of length 1. For ℓ2\ell_2 it's the ordinary circle; for ℓ1\ell_1 it's a diamond with corners on the axes; for ℓ∞\ell_\infty it's a square.

What makes something a norm? Three properties, true of all three:

  1. ∥v∥≥0\lVert \mathbf{v} \rVert \ge 0, and ∥v∥=0\lVert \mathbf{v} \rVert = 0 only for v=0\mathbf{v} = \mathbf{0}.
  2. ∥c v∥=∣c∣ ∥v∥\lVert c\,\mathbf{v} \rVert = |c|\,\lVert \mathbf{v} \rVert.
  3. The triangle inequality: ∥u+v∥≤∥u∥+∥v∥\lVert \mathbf{u} + \mathbf{v} \rVert \le \lVert \mathbf{u} \rVert + \lVert \mathbf{v} \rVert. Going straight is never longer than going round. You'll prove it for ℓ2\ell_2 at the end of this chamber.
Quick check +20 XP

What is the length ∥(2,−3,6)∥2\lVert (2, -3, 6) \rVert_2?

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 u\mathbf{u} and v\mathbf{v} from the origin, with angle θ\theta (theta) between them. The arrow from the tip of v\mathbf{v} to the tip of u\mathbf{u} is u−v\mathbf{u} - \mathbf{v}, so the three arrows form a triangle with sides of length ∥u∥\lVert \mathbf{u} \rVert, ∥v∥\lVert \mathbf{v} \rVert and ∥u−v∥\lVert \mathbf{u} - \mathbf{v} \rVert.

  1. 1

    The law of cosines

    For any triangle with sides aa and bb meeting at angle θ\theta, the third side cc satisfies c2=a2+b2−2abcos⁡θc^2 = a^2 + b^2 - 2ab\cos\theta. (When θ=90°\theta = 90°, cos⁡θ=0\cos\theta = 0 and this is Pythagoras.) For our triangle:

    ∥u−v∥2=∥u∥2+∥v∥2−2 ∥u∥∥v∥cos⁡θ.\lVert \mathbf{u} - \mathbf{v} \rVert^2 = \lVert \mathbf{u} \rVert^2 + \lVert \mathbf{v} \rVert^2 - 2\,\lVert \mathbf{u} \rVert \lVert \mathbf{v} \rVert \cos\theta .
  2. 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:

    ∥u−v∥2=(u−v)⋅(u−v)=u⋅u−2 u⋅v+v⋅v=∥u∥2−2 u⋅v+∥v∥2.\lVert \mathbf{u} - \mathbf{v} \rVert^2 = (\mathbf{u} - \mathbf{v}) \cdot (\mathbf{u} - \mathbf{v}) = \mathbf{u} \cdot \mathbf{u} - 2\,\mathbf{u} \cdot \mathbf{v} + \mathbf{v} \cdot \mathbf{v} = \lVert \mathbf{u} \rVert^2 - 2\,\mathbf{u} \cdot \mathbf{v} + \lVert \mathbf{v} \rVert^2 .
  3. 3

    Compare

    The two right-hand sides are equal. Cancel ∥u∥2\lVert \mathbf{u} \rVert^2 and ∥v∥2\lVert \mathbf{v} \rVert^2 from both, then divide by −2-2:

    u⋅v=∥u∥ ∥v∥cos⁡θ.\mathbf{u} \cdot \mathbf{v} = \lVert \mathbf{u} \rVert \, \lVert \mathbf{v} \rVert \cos\theta .

So for non-zero vectors,

cos⁡θ=u⋅v∥u∥ ∥v∥.\cos\theta = \frac{\mathbf{u} \cdot \mathbf{v}}{\lVert \mathbf{u} \rVert \, \lVert \mathbf{v} \rVert} .

Lengths are positive, so the sign of the dot product is the sign of cos⁡θ\cos\theta, and it tells you the kind of angle at a glance:

u⋅v\mathbf{u} \cdot \mathbf{v}AngleMeaning
positiveacute, under 90°90°the vectors broadly agree
zeroexactly 90°90°orthogonal, written u⊥v\mathbf{u} \perp \mathbf{v}
negativeobtuse, over 90°90°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, (2,1)⋅(−1,2)=−2+2=0(2, 1) \cdot (-1, 2) = -2 + 2 = 0. (By convention, 0\mathbf{0} counts as orthogonal to everything.)

The lab shows all of it live. The panel computes u⋅v\mathbf{u} \cdot \mathbf{v} 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

Drag u and v. The panel computes u · v term by term, the lengths, and the angle. The violet arrow is the projection of u onto the line through v.
−6−6−4−4−2−222446642.3°vu

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)

u= (,)
v= (,)
Challenge: Right anglesFind two non-zero vectors, neither on an axis, whose dot product is exactly zero.+30 XP

Things to try:

  1. Find two vectors at right angles with every component non-zero. (The challenge.) Is there a quick recipe that turns any (a,b)(a, b) into a vector orthogonal to it?
  2. Set u=(2,1)\mathbf{u} = (2, 1), note the dot product and the angle, then double u\mathbf{u} to (4,2)(4, 2). The dot product doubles. What happens to the angle?
  3. Make the angle obtuse and watch the violet projection flip to point away from v\mathbf{v}.
Quick check +20 XP

Two non-zero vectors have u⋅v=−4\mathbf{u} \cdot \mathbf{v} = -4. What can you say about the angle θ\theta 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 R300\mathbb{R}^{300}” mean? In higher dimensions we turn the result around and define the angle by cos⁡θ=u⋅v∥u∥∥v∥\cos\theta = \frac{\mathbf{u} \cdot \mathbf{v}}{\lVert \mathbf{u} \rVert \lVert \mathbf{v} \rVert}. But that only makes sense if the fraction is always between −1-1 and 11, 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 u,v∈Rn\mathbf{u}, \mathbf{v} \in \mathbb{R}^n,

∣u⋅v∣≤∥u∥ ∥v∥,|\mathbf{u} \cdot \mathbf{v}| \le \lVert \mathbf{u} \rVert \, \lVert \mathbf{v} \rVert ,

with equality exactly when one of the vectors is a multiple of the other.

Dividing both sides by ∥u∥∥v∥\lVert \mathbf{u} \rVert \lVert \mathbf{v} \rVert gives −1≤cos⁡θ≤1-1 \le \cos\theta \le 1, 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 v=0\mathbf{v} = \mathbf{0}, both sides are 0 and there's nothing to prove. So suppose v≠0\mathbf{v} \ne \mathbf{0}. For every real number tt, the vector u−t v\mathbf{u} - t\,\mathbf{v} has a length, and its square is not negative. Expanding with the rules of the dot product:

0≤∥u−t v∥2=(u−t v)⋅(u−t v)=∥u∥2−2t (u⋅v)+t2∥v∥2.0 \le \lVert \mathbf{u} - t\,\mathbf{v} \rVert^2 = (\mathbf{u} - t\,\mathbf{v}) \cdot (\mathbf{u} - t\,\mathbf{v}) = \lVert \mathbf{u} \rVert^2 - 2t\,(\mathbf{u} \cdot \mathbf{v}) + t^2 \lVert \mathbf{v} \rVert^2 .

This holds for every tt, so we may pick the most useful one: t=u⋅v∥v∥2t = \dfrac{\mathbf{u} \cdot \mathbf{v}}{\lVert \mathbf{v} \rVert^2}. Substituting,

0≤∥u∥2−2 (u⋅v)2∥v∥2+(u⋅v)2∥v∥2=∥u∥2−(u⋅v)2∥v∥2.0 \le \lVert \mathbf{u} \rVert^2 - 2\,\frac{(\mathbf{u} \cdot \mathbf{v})^2}{\lVert \mathbf{v} \rVert^2} + \frac{(\mathbf{u} \cdot \mathbf{v})^2}{\lVert \mathbf{v} \rVert^2} = \lVert \mathbf{u} \rVert^2 - \frac{(\mathbf{u} \cdot \mathbf{v})^2}{\lVert \mathbf{v} \rVert^2} .

Multiply both sides by the positive number ∥v∥2\lVert \mathbf{v} \rVert^2 and rearrange: (u⋅v)2≤∥u∥2∥v∥2(\mathbf{u} \cdot \mathbf{v})^2 \le \lVert \mathbf{u} \rVert^2 \lVert \mathbf{v} \rVert^2. Both sides are non-negative, so taking square roots keeps the inequality: ∣u⋅v∣≤∥u∥∥v∥|\mathbf{u} \cdot \mathbf{v}| \le \lVert \mathbf{u} \rVert \lVert \mathbf{v} \rVert.

For the equality case: if ∣u⋅v∣=∥u∥∥v∥|\mathbf{u} \cdot \mathbf{v}| = \lVert \mathbf{u} \rVert \lVert \mathbf{v} \rVert, every step above is an equality, so ∥u−t v∥2=0\lVert \mathbf{u} - t\,\mathbf{v} \rVert^2 = 0 for our chosen tt. Only the zero vector has length 0, so u=t v\mathbf{u} = t\,\mathbf{v}. Conversely, if u=c v\mathbf{u} = c\,\mathbf{v} then both sides equal ∣c∣ ∥v∥2|c|\,\lVert \mathbf{v} \rVert^2. (If v=0\mathbf{v} = \mathbf{0}, then v=0 u\mathbf{v} = 0\,\mathbf{u} is a multiple of u\mathbf{u}.) ■\blacksquare

Where did that value of tt come from? The expression ∥u∥2−2t (u⋅v)+t2∥v∥2\lVert \mathbf{u} \rVert^2 - 2t\,(\mathbf{u} \cdot \mathbf{v}) + t^2 \lVert \mathbf{v} \rVert^2 is a parabola in tt, and school algebra puts its lowest point at t=u⋅v∥v∥2t = \frac{\mathbf{u} \cdot \mathbf{v}}{\lVert \mathbf{v} \rVert^2}. We chose the tt that makes u−t v\mathbf{u} - t\,\mathbf{v} as short as possible, so the inequality “squared length ≥0\ge 0” is as sharp as it can be. Remember that tt: it comes straight back in the next section.

Learn: projection, a preview

Shine a light straight down onto the line through v\mathbf{v}, and u\mathbf{u} casts a shadow on it. That shadow is the projection of u\mathbf{u} onto v\mathbf{v}:

proj⁡vu=u⋅vv⋅v v.\operatorname{proj}_{\mathbf{v}} \mathbf{u} = \frac{\mathbf{u} \cdot \mathbf{v}}{\mathbf{v} \cdot \mathbf{v}}\,\mathbf{v} .

The coefficient is exactly the tt from the proof: the multiple of v\mathbf{v} that comes closest to u\mathbf{u}. And the leftover part, u−t v\mathbf{u} - t\,\mathbf{v}, is at right angles to v\mathbf{v}, because

(u−t v)⋅v=u⋅v−t (v⋅v)=u⋅v−u⋅v=0.(\mathbf{u} - t\,\mathbf{v}) \cdot \mathbf{v} = \mathbf{u} \cdot \mathbf{v} - t\,(\mathbf{v} \cdot \mathbf{v}) = \mathbf{u} \cdot \mathbf{v} - \mathbf{u} \cdot \mathbf{v} = 0 .

For example, with u=(3,4)\mathbf{u} = (3, 4) and v=(2,1)\mathbf{v} = (2, 1): t=6+44+1=2t = \frac{6 + 4}{4 + 1} = 2, so the projection is (4,2)(4, 2), and the leftover (3,4)−(4,2)=(−1,2)(3, 4) - (4, 2) = (-1, 2) satisfies (−1,2)⋅(2,1)=0(-1, 2) \cdot (2, 1) = 0. The lab draws the projection as the violet arrow and the leftover as the dashed line: drag u\mathbf{u} and watch the dashed line stay perpendicular.

This also gives the dot product a second picture. Since t ∥v∥=∥u∥cos⁡θt\,\lVert \mathbf{v} \rVert = \lVert \mathbf{u} \rVert \cos\theta, the dot product u⋅v\mathbf{u} \cdot \mathbf{v} is the (signed) length of the shadow of u\mathbf{u} times the length of v\mathbf{v}. 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:

cos⁡θ=u⊤v∥u∥ ∥v∥∈[−1,1].\cos\theta = \frac{\mathbf{u}^\top \mathbf{v}}{\lVert \mathbf{u} \rVert \, \lVert \mathbf{v} \rVert} \in [-1, 1] .

Thanks to Cauchy–Schwarz it always lies between −1-1 and 11: 1 for vectors pointing the same way, 0 for orthogonal ones, −1-1 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

w∗=argmaxwxwy∥xw∥∥y∥w^* = \mathrm{argmax}_w \frac{x_w y}{\lVert x_w \rVert \lVert y \rVert}
Mikolov, Yih & Zweig (2013), “Linguistic Regularities in Continuous Space Word Representations”, Section 5

“Find the word ww whose vector xwx_w has the greatest cosine similarity with y=xb−xa+xcy = x_b - x_a + x_c.” Notice that the paper writes the dot product as xwyx_w y, 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 qiTpuq_i^T p_u, so a longer vector counts for more, and transformer attention scores every query against every key with a raw dot product, q⊤k\mathbf{q}^\top \mathbf{k}. In the attention formula you met in the first course, QK⊤QK^\top is simply a table of these dot products, and the division by dk\sqrt{d_k} keeps them from growing with the dimension. Whether to normalise is a design choice, and now you know what each choice keeps.

Quick check +20 XP

You double every entry of u\mathbf{u} and leave v\mathbf{v} alone. What happens to u⋅v\mathbf{u} \cdot \mathbf{v} and to the cosine similarity of u\mathbf{u} and v\mathbf{v}?

DiscoverLearnRead beyondPapers & lecturesYour turn

Read beyond the course

The same ideas from four angles. Each one is free.

Book · free online · ~40 min

Mathematics for Machine Learning

Marc 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 Algebra

J. 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 Squares

Stephen 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 Reference

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

DiscoverLearnRead beyondPapers & lecturesYour turn

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), 2009

The 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 Systems

Yehuda Koren, Robert Bell, Chris Volinsky · IEEE Computer, 2009

+30 XP
min⁡q∗,p∗∑(u,i)∈κ(rui−qiTpu)2+λ(∥qi∥2+∥pu∥2)\min_{q^*, p^*} \sum_{(u,i) \in \kappa} \left(r_{ui} - q_i^T p_u\right)^2 + \lambda\left(\lVert q_i \rVert^2 + \lVert p_u \rVert^2\right)

How the recommender learns its vectors. Every user uu gets a factor vector pup_u and every item ii a factor vector qiq_i, both in Rf\mathbb{R}^f, and Equation 1 predicts a rating as their dot product. Equation 2 is what training makes small. Match each piece to its meaning.

ruir_{ui}
qiTpuq_i^T p_u
κ\kappa
∥qi∥2\lVert q_i \rVert^2
λ\lambda
min⁡q∗,p∗\min_{q^*, p^*}

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 uu and vv meet in a box labelled cosine-sim(u, v). The triplet objective just after it compares Euclidean distances ∥sa−sp∥\lVert s_a - s_p \rVert: norms from this chamber. Skip the experiments.

Sentence-BERT: Sentence Embeddings using Siamese BERT-NetworksNils Reimers, Iryna Gurevych · EMNLP-IJCNLP, 2019

Made sentence embeddings practical for search and clustering by training BERT so that cosine similarity between its outputs means similarity in meaning.

Watch

Dot products and duality | Chapter 9, Essence of linear algebra3Blue1Brown · 14 min

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.

DiscoverLearnRead beyondPapers & lecturesYour turn

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

+25 XP

Let u=(3,−4)\mathbf{u} = (3, -4) and v=(1,2)\mathbf{v} = (1, 2). Match each quantity to its value.

u⋅v\mathbf{u} \cdot \mathbf{v}
∥u∥2\lVert \mathbf{u} \rVert_2
∥u∥1\lVert \mathbf{u} \rVert_1
∥u∥∞\lVert \mathbf{u} \rVert_\infty
∥u−v∥2\lVert \mathbf{u} - \mathbf{v} \rVert_2
u^\hat{\mathbf{u}}
cos⁡θ\cos\theta between u\mathbf{u} and v\mathbf{v}

Options

Match · Maths ↔ NumPy

From symbols to NumPy

+25 XP

Match each formula to the NumPy that computes it. Assume u and v are 1D NumPy arrays of the same length.

u⊤v\mathbf{u}^\top \mathbf{v}
∥u∥2\lVert \mathbf{u} \rVert_2
∥u∥1\lVert \mathbf{u} \rVert_1
∥u∥∞\lVert \mathbf{u} \rVert_\infty
u^\hat{\mathbf{u}}
u⋅v∥u∥∥v∥\frac{\mathbf{u} \cdot \mathbf{v}}{\lVert \mathbf{u} \rVert \lVert \mathbf{v} \rVert}
proj⁡vu\operatorname{proj}_{\mathbf{v}} \mathbf{u}

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

+25 XP

Claim

If u\mathbf{u} and v\mathbf{v} are orthogonal, then ∥u+v∥2=∥u∥2+∥v∥2\lVert \mathbf{u} + \mathbf{v} \rVert^2 = \lVert \mathbf{u} \rVert^2 + \lVert \mathbf{v} \rVert^2.

Tap lines in the order they should appear. Not every line belongs. Tap a line in your proof to send it back.

Your proof

  1. Pick the first line below.

Available lines

Prove it yourself

The triangle inequality

+40 XP

Claim

For all vectors u,v∈Rn\mathbf{u}, \mathbf{v} \in \mathbb{R}^n,

∥u+v∥≤∥u∥+∥v∥.\lVert \mathbf{u} + \mathbf{v} \rVert \le \lVert \mathbf{u} \rVert + \lVert \mathbf{v} \rVert.

(Going straight is never longer than going the long way round.) You may use the Cauchy–Schwarz inequality.

Preview

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

+20 XP

For k=1,2,…,300k = 1, 2, \ldots, 300 define the vector vk∈R3\mathbf{v}_k \in \mathbb{R}^3 by

vk=((k mod 7)−3, (k2 mod 11)−5, (k mod 4)−2).\mathbf{v}_k = \big((k \bmod 7) - 3,\ (k^2 \bmod 11) - 5,\ (k \bmod 4) - 2\big).

How many pairs (j,k)(j, k) with 1≤j<k≤3001 \le j < k \le 300 are orthogonal, that is, have vj⋅vk=0\mathbf{v}_j \cdot \mathbf{v}_k = 0, with neither vj\mathbf{v}_j nor vk\mathbf{v}_k equal to the zero vector?

An exact integer (or a fraction like 7/12)

Problem 5·Standard

The recommender's report card

+35 XP

Koren, Bell and Volinsky (2009) learn a factor vector pu\mathbf{p}_u for every user and qi\mathbf{q}_i for every item by minimising their Equation 2, the regularised squared error over the set κ\kappa of known ratings:

L=∑(u,i)∈κ[(rui−qi⊤pu)2+λ(∥qi∥2+∥pu∥2)].L = \sum_{(u, i) \in \kappa} \Big[\big(r_{ui} - \mathbf{q}_i^\top \mathbf{p}_u\big)^2 + \lambda\big(\lVert \mathbf{q}_i \rVert^2 + \lVert \mathbf{p}_u \rVert^2\big)\Big].

The penalty is added once for every known rating, inside the sum, as in the paper. Compute LL for this untrained model, with f=3f = 3 factors:

- users u=1,…,20u = 1, \ldots, 20 with pu=(12((u mod 5)−2), (u mod 3)−1, 1)\mathbf{p}_u = \big(\tfrac{1}{2}((u \bmod 5) - 2),\ (u \bmod 3) - 1,\ 1\big); - items i=1,…,30i = 1, \ldots, 30 with qi=((i mod 4)−32, 12(3i mod 5)−1, 12(i mod 3))\mathbf{q}_i = \big((i \bmod 4) - \tfrac{3}{2},\ \tfrac{1}{2}(3i \bmod 5) - 1,\ \tfrac{1}{2}(i \bmod 3)\big); - known ratings κ={(u,i):(u+2i) mod 3=0}\kappa = \{(u, i) : (u + 2i) \bmod 3 = 0\}, with rui=1+(ui mod 5)r_{ui} = 1 + (u i \bmod 5); - λ=0.05\lambda = 0.05.

Here 3i mod 53i \bmod 5 means (3i) mod 5(3i) \bmod 5, and ui mod 5u i \bmod 5 means (u⋅i) mod 5(u \cdot i) \bmod 5. Give LL to 3 decimal places.

A number, rounded to 3 decimal places

Problem 6·Challenge

The most similar pair

+50 XP

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

s0=290797,sn+1=sn2 mod 50515093,tn=(sn mod 2001)−1000(n≥1),s_0 = 290797, \qquad s_{n+1} = s_n^2 \bmod 50515093, \qquad t_n = (s_n \bmod 2001) - 1000 \quad (n \ge 1),

so t1=213t_1 = 213, t2=−522t_2 = -522, t3=−260t_3 = -260. For k=1,…,500k = 1, \ldots, 500, embedding kk is the vector of eight consecutive values

xk=(t8k−7,t8k−6,…,t8k)∈R8.\mathbf{x}_k = \big(t_{8k-7}, t_{8k-6}, \ldots, t_{8k}\big) \in \mathbb{R}^8.

Among all pairs j≠kj \ne k, find the largest cosine similarity

cos⁡θjk=xj⋅xk∥xj∥ ∥xk∥,\cos\theta_{jk} = \frac{\mathbf{x}_j \cdot \mathbf{x}_k}{\lVert \mathbf{x}_j \rVert\, \lVert \mathbf{x}_k \rVert},

and give it to 6 decimal places.

A number, rounded to 6 decimal places

Key takeaways

  • The dot product multiplies matching entries and adds: u⋅v=∑iuivi=u⊤v=⟨u,v⟩\mathbf{u} \cdot \mathbf{v} = \sum_i u_i v_i = \mathbf{u}^\top \mathbf{v} = \langle \mathbf{u}, \mathbf{v} \rangle. A recommender's predicted rating qiTpuq_i^T p_u is one.
  • Length comes from it: ∥v∥=v⋅v\lVert \mathbf{v} \rVert = \sqrt{\mathbf{v} \cdot \mathbf{v}}. Distance is ∥u−v∥\lVert \mathbf{u} - \mathbf{v} \rVert, and ℓ1\ell_1 and ℓ∞\ell_\infty are other useful ways to measure length.
  • So does the angle: u⋅v=∥u∥∥v∥cos⁡θ\mathbf{u} \cdot \mathbf{v} = \lVert \mathbf{u} \rVert \lVert \mathbf{v} \rVert \cos\theta, derived from the law of cosines. The sign tells acute, right or obtuse, and u⊥v\mathbf{u} \perp \mathbf{v} exactly when u⋅v=0\mathbf{u} \cdot \mathbf{v} = 0.
  • Cauchy–Schwarz, ∣u⋅v∣≤∥u∥∥v∥|\mathbf{u} \cdot \mathbf{v}| \le \lVert \mathbf{u} \rVert \lVert \mathbf{v} \rVert, makes angles meaningful in any dimension and implies the triangle inequality.
  • Projection u⋅vv⋅vv\frac{\mathbf{u} \cdot \mathbf{v}}{\mathbf{v} \cdot \mathbf{v}}\mathbf{v} 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.

0/8
Question 1 of 8 +20 XP

Compute u⋅v\mathbf{u} \cdot \mathbf{v} for u=(2,−1,3)\mathbf{u} = (2, -1, 3) and v=(4,5,1)\mathbf{v} = (4, 5, 1).

Question 2 of 8 +20 XP

What is the angle, in degrees, between (1,1)(1, 1) and (−1,0)(-1, 0)?

°
Question 3 of 8 +20 XP

For x=(3,−4)\mathbf{x} = (3, -4), which line is correct?

Question 4 of 8 +20 XP

What is the unit vector v^\hat{\mathbf{v}} in the direction of v=(3,4)\mathbf{v} = (3, 4)?

Question 5 of 8 +20 XP

Which statement is true for every pair of vectors u,v∈Rn\mathbf{u}, \mathbf{v} \in \mathbb{R}^n?

Question 6 of 8 +20 XP

Project u=(4,2)\mathbf{u} = (4, 2) onto the line through v=(1,1)\mathbf{v} = (1, 1). What is the first component of proj⁡vu\operatorname{proj}_{\mathbf{v}} \mathbf{u}?

Question 7 of 8 +20 XP

In Koren, Bell and Volinsky's model r^ui=qi⊤pu\hat{r}_{ui} = \mathbf{q}_i^\top \mathbf{p}_u, when is the predicted rating large and positive?

Question 8 of 8 +20 XP

Transformer attention compares a query q\mathbf{q} with a key k\mathbf{k}, both in Rdk\mathbb{R}^{d_k}, through the score q⊤k/dk\mathbf{q}^\top \mathbf{k} / \sqrt{d_k}. Why divide by dk\sqrt{d_k}?

End of the chamber

Clear this chamber

+60 XPDot ProductNormCosine SimilarityCauchy–Schwarz Inequality