Dot product and cosine similarity
Compute $a\cdot b$, read it as alignment times lengths, and use cosine similarity to compare vectors.
Builds on: Vectors
What the animation says
Do their tastes agree?
Two friends rate the same five films, from minus two, hated it, to plus two, loved it. Each person's ratings are just a list of five numbers. A vector. Do their tastes agree? We want one number that says how much. Language models ask this all the time, about lists with thousands of numbers. One simple move answers it: multiply, then add.
Multiply matching entries
Line up the two lists. Multiply the entries that sit in the same position. Film one: Ana gives two, Ben gives one. Two times one is two. Both liked it, so the product is positive. Film three: minus two times minus one is plus two. Both hated it. That counts as agreement too. When the signs differ, one likes and one hates, so the product is negative. Your turn: tap the film where Ana and Ben disagree.
Then add: one number
Film four gives minus two. Film two: two times two, four. Film five: Ben is neutral, so zero. Now we have five products. That list is not the answer yet. Add them all: two, four, two, minus two, zero. Six. That's the dot product: multiply matching entries, then add. Positive means they mostly agree. Now Ben doubles every rating. Same taste, just louder. What happens to the score?
Length sneaks in: cosine
Twelve. Same tastes, double the score. The dot product grows with length too. Arrows make this visible. a is three, four. b is four, three. Their dot product is twenty-four. Now c: six, eight. Same direction as a, twice as long. Dot product fifty. To keep only direction, divide by both lengths. That's cosine similarity. a with b: twenty-four over twenty-five, zero point nine six. a with c: fifty over fifty, exactly one. One more. u is minus four, three. What is its cosine with a?
Remember
Zero. Three times minus four, plus four times three: minus twelve plus twelve. The arrows are perpendicular. Cosine runs from one, same direction, through zero, perpendicular, to minus one, opposite. So the dot product means multiply matching entries, then add. One number. It equals length times length times alignment. Cosine similarity divides the lengths out. Language models ask this constantly: how much does this list of numbers point the same way as that one?
Multiply matching entries, then add
Dot product and cosine similarity
Three comparisons with a = (3, 4)
Remember
On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.
Bytewise
All courses