Lesson 4 of 116 min
Distance and cosine similarity
Distance and the dot product care how long arrows are; shrink every arrow to length 1 and you compare only direction: cosine similarity.
After this lesson you can measure length and distance, and compare direction while ignoring length.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
The three measures in NumPy
Length is np.linalg.norm. Distance is the length of the gap, so subtract first. Cosine similarity is the dot product divided by both lengths, which is the same as shrinking both arrows first. The last line prints just under 1: a computer's sums leave a tiny error, so read it as 1.
import numpy as np
you = np.array([2, 1])
jo = np.array([1, 0.5])
print(np.linalg.norm(you))
print(np.linalg.norm(jo - you))
cos = (you @ jo) / (np.linalg.norm(you) * np.linalg.norm(jo))
print(cos)2.23606797749979 1.118033988749895 0.9999999999999998
Shrink every row at once
A search keeps its vectors as the rows of one table. axis=1 measures each row, and keepdims=True keeps the lengths in a column, so each row is divided by its own length. After that, @ with one shrunk row gives every cosine similarity at once.
rows = np.array([[2, 1], [1, 0.5], [2, 2]])
lengths = np.linalg.norm(rows, axis=1, keepdims=True)
unit = rows / lengths
print(unit.round(2))
print((unit @ unit[0]).round(2))[[0.89 0.45] [0.89 0.45] [0.71 0.71]] [1. 1. 0.95]
Why the three agree at length 1
For arrows of length 1, the distance squared is always 2 minus twice the cosine similarity. So when one goes up, the other goes down, and they sort any list in the same order. Here it is for your shrunk arrow and Max's.
a, b = unit[0], unit[2]
print(np.linalg.norm(a - b) ** 2)
print(2 - 2 * (a @ b))0.10263340389897238 0.10263340389897269
Check your model's vectors
Don't assume length 1: measure a few. sentence-transformers also says which measure a model was trained for, in similarity_fn_name. If the lengths are not 1, pass normalize_embeddings=True to encode, or use cosine similarity.
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("google/embeddinggemma-2")
docs = model.encode_document(["A kitten naps on the couch.",
"Rain is due on Friday."])
print(docs.shape)
print(np.linalg.norm(docs, axis=1).round(3))
print(model.similarity_fn_name)(2, 768) [1.001 0.999] cosine
Other measures, and in a database
There are more ways to measure a gap. The city-block distance adds up how far apart each pair of numbers is, with no squares. pgvector offers it as <+>, beside <-> for distance, <=> for cosine distance (1 minus the cosine similarity) and <#> for the dot product with a minus, since a database sorts the smallest first.
print(np.abs(jo - you).sum())1.5
Run on Python 3.13, NumPy 2.5.5 and sentence-transformers 6.3.0. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: The dot product
You rate two movies [1, 2]. A friend rates them [2, -2]. What is your dot product?
2 of 3
Your search compares sentences by their vectors, from a model that gives every vector a length of 1. Which should it rank them by?
3 of 3
You rate two movies [2, 1]. A friend rates them [-1, 5]. How far apart are your two points?
The ideas in this lesson
- Length
- Square each number, add them, take the square root: how long the arrow is.
- Distance
- Subtract two vectors' matching numbers, then take the length: how far apart their points are.
- Cosine similarity
- Shrink both arrows to length 1, then take their dot product: 1 the same way, −1 opposite.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
The bet
Here's a bet. You rate a comedy plus two, and a horror movie plus one. Jo likes the same movies, only half as much. Plus one, and plus a half. Max gives the comedy plus two, like you. And the horror movie plus two as well. Now make each of you a point on a map. Whose point is closer to yours: Jo's, or Max's?
Length
Hold on to your guess. To answer that, you need to measure. So first: how long is an arrow?
Your arrow, two, one, goes two across and one up.
That makes a triangle with a right angle, so the Pythagorean theorem from school gives its length.
Square each number: four, and one.
Add them: five. Then take the square root. NumPy does it in one line. So your arrow is about two and a quarter long.
Distance
How far apart are two points?
A point is where an arrow ends. Take your point, and Max's, and subtract one number at a time. The comedy: two minus two is zero. The horror movie: two minus one is one. So the gap between the two points is zero, one. The length of that gap... is called the distance. Here, it's one.
Closer
And Jo?
The comedy: one minus two is minus one. The horror movie: a half minus one is minus a half.
That gap is a bit longer than one. So Max is closer.
If you said Jo: Jo likes exactly what you like, only half as much.
But distance counts two things: which way your taste points, and how strongly you rate.
Which way
And the dot product counts both things too. Multiply the matching numbers, then add them up. Max gets six. Jo gets only two and a half.
So how do you compare only the direction?
Shrink to length one
To compare only the direction, make every arrow the same length: one.
Divide each arrow's numbers by its length. Divide your two numbers by your length, about two and a quarter. Then do the same with Jo's arrow. You get the exact same two numbers.
Every arrow now ends on the same circle. Jo's lands exactly on yours, and Max's lands close beside it. Only the direction is left.
Cosine similarity
Now take the dot product of the shrunk arrows.
That number... is called the cosine similarity.
It runs from one, the same way, through zero at a right angle, to minus one, opposite.
Jo: one. As close as two tastes can be.
Max: a little less.
The name comes from school math about angles. You won't need it here.
All three agree
Now, a real model. It turns sentences and photos into vectors of length one. Here's the sentence: my cat is asleep on the sofa.
And three others. A kitten naps on the couch.
My car is parked on the street.
And a photo of a cat asleep on a sofa. Will the three measures put them in the same order?
Yes. For distance, smaller means closer. For the other two, bigger means closer. And all three put the kitten first, then the car, then the photo. In this model, a photo and a sentence sit a little farther apart, even when they're about the same cat. When every arrow has length one, only the direction can be different.
For your search
So which one should your search use?
A search compares one sentence with many others, and shows you the closest first.
If your vectors have length one, and lots of models give you that, take the dot product. It puts them in the same order as the other two.
And it's the least work: no lengths, and no dividing.
If your vectors have other lengths, and only the direction should count, take cosine similarity. A vector database stores vectors and searches them. It offers all three.
In code: a search
Here's a search by meaning, in a few lines of code. The same model turns four sentences into vectors. Then it turns your question into one too: where is my cat sleeping? NumPy measures your question's length: one. So the dot product is all you need. The at sign takes the dot product of your question with every sentence at once. Which sentence comes out on top?
A kitten naps on the couch, with the highest score. Then the dog by the fire: it's about sleeping too.
The top sentence shares no words with your question... and it still comes first. That's a search by meaning. A vector database does the same, over millions of sentences.
What you saw
So here's what you saw. An arrow's length comes from the Pythagorean theorem. Distance is the length of the gap between two points. And cosine similarity is the dot product of arrows shrunk to length one. When your vectors already have length one, the dot product is all you need.
The lab
That's the end of this unit. In its lab, you'll use these four lessons to search a store's products by meaning.
Shrink, then the dot product
So to compare only the direction, shrink the arrows to length one. Then take the dot product. Now try it on this lesson's page, and take the quiz. Shrink the arrows, and make the distance exactly two. Then read the cosine similarity.
You use this lesson in Lab 1: Search a store by meaning, which comes next.
Facts last checked on .
