Lesson 11 of 117 min
High-dimensional space
In many dimensions, random points sit about as far from each other as they can, and random arrows point at nearly right angles; real data still works because its numbers move together.
After this lesson you can explain why distance behaves strangely in many dimensions.
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.
Why a total of many bunches up
A total of many dice lands near its average. With more dice, the spread of the totals grows, but much slower than the total: a hundred times more dice give about ten times more spread. So the spread, as a share of the total, keeps shrinking. A distance adds many squared gaps, so it does the same.
import numpy as np
rng = np.random.default_rng(0)
for n in [1, 10, 100, 1000]:
totals = rng.integers(1, 7, (500, n)).sum(axis=1)
print(n, totals.mean().round(1), totals.std().round(1),
(totals.std() / totals.mean()).round(3))1 3.6 1.7 0.48 10 34.9 5.2 0.148 100 349.6 17.1 0.049 1000 3500.9 54.5 0.016
The ratio for every size
The board's eight lines, run for many sizes in one loop. Each line prints how many numbers each point has, then the nearest divided by the farthest. It keeps climbing toward 1, and never quite gets there.
for dims in [2, 10, 100, 768, 3000]:
points = np.random.default_rng(0).random((501, dims))
far = np.linalg.norm(points[1:] - points[0], axis=1)
print(dims, round(far.min() / far.max(), 2))2 0.01 10 0.33 100 0.72 768 0.87 3000 0.92
Most of a cube is in its corners
Another strange thing about many dimensions. Put the largest ball you can inside a cube, and count how many random points of the cube land in the ball. In a square, the round part holds most of them. With ten numbers, almost none: nearly every point is out in a corner.
for dims in [2, 3, 10, 20]:
points = np.random.default_rng(0).random((100_000, dims))
inside = np.linalg.norm(points - 0.5, axis=1) <= 0.5
print(dims, inside.mean())2 0.78678 3 0.52497 10 0.00234 20 0.0
Points above 0 bunch somewhere else
The video's arrows had numbers above and below 0, and their cosine similarity bunched at 0. The board's points have every number between 0 and 1, so they all point into one corner, and their cosine similarity bunches near 0.75 instead. Move the points so the middle of the cube is 0, and it bunches at 0 again.
points = np.random.default_rng(0).random((501, 768))
cos = points[1:] @ points[0] / (np.linalg.norm(points[1:], axis=1) * np.linalg.norm(points[0]))
print(cos.min().round(2), cos.max().round(2))
centered = points - 0.5
cos = centered[1:] @ centered[0] / (np.linalg.norm(centered[1:], axis=1) * np.linalg.norm(centered[0]))
print(cos.min().round(2), cos.max().round(2))0.72 0.79 -0.11 0.11
Cut a model's numbers short
A model trained so its first numbers carry the most meaning is called a Matryoshka model, after the dolls that sit one inside another. sentence-transformers cuts it with truncate_dim. The cut rows are no longer of length 1, so shrink them back before taking dot products. The scores keep the order they had with all 768.
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("google/embeddinggemma-2", truncate_dim=256)
docs = model.encode_document(["A kitten naps on the couch.",
"My car is parked on the street.",
"The dog sleeps by the fire."])
query = model.encode_query("Where is my cat sleeping?")
print(docs.shape, np.linalg.norm(docs, axis=1).round(3))
docs = docs / np.linalg.norm(docs, axis=1, keepdims=True)
print((docs @ (query / np.linalg.norm(query))).round(2))(3, 256) [0.68 0.698 0.692] [0.79 0.72 0.76]
Run on Python 3.13, NumPy 2.5.5, scikit-learn 1.9.1 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: Distance and cosine similarity
You rate two movies [2, 1]. A friend rates them [-1, 5]. How far apart are your two points?
2 of 3
With 768 numbers, random points are all about as far apart. A search compares sentences by the 768 numbers a real model gives them. Why does it still find sentences that mean the same thing?
3 of 3
This is the lesson's code, now with 2,000 numbers for each point. What does it print: the nearest divided by the farthest?
import numpy as np
rng = np.random.default_rng(0)
points = rng.random((501, 2000))
gaps = points[1:] - points[0]
far = np.linalg.norm(gaps, axis=1)
print(round(far.min() / far.max(), 2))The ideas in this lesson
- Distances bunch up
- In many dimensions, random points are all about as far apart: the nearest is barely nearer than the farthest.
- Random arrows at right angles
- In many dimensions, two random arrows almost always point at nearly a right angle: cosine similarity near 0.
- Real data is not random
- Real data's numbers move together, so alike things stay much nearer than the rest, even in many dimensions.
It leans on
- k-nearest neighbours
Transcript
What the video says, part by part. Press a time to watch from there.
The question
Here's a question. Look at these random points in a square, and one more, circled.
Its nearest point is right next to it. Now give every point hundreds of numbers. That's what AI does with a sentence. Will the nearest point still be much nearer than the rest?
In a square
Each of these random points is two numbers, from zero to one: two dimensions. From the circled point, measure the distance to every other point. Then divide the nearest by the farthest: about a hundredth. The nearest point is far nearer than the rest.
In a cube
Give each point a third number, and the points fill a cube. Nearest divided by farthest: about a tenth. The nearest is already not as close.
In many numbers
You can't draw seven hundred and sixty-eight directions. But you can still measure distances.
These eight lines make five hundred random points and one more. They measure every distance from that one, and print the nearest divided by the farthest. A histogram shows how many distances fall at each size. Let's run it.
With two numbers, the distances go from very short to long.
Ten numbers: about a third. A hundred: almost three quarters.
Seven hundred and sixty-eight... nearly nine tenths.
The nearest is almost as far as the farthest.
If you said much nearer: with more numbers, every distance does grow. But they all grow by about the same amount, so the nearest catches up with the farthest. From this point, every other point is about as far away, and it's the same from any point. The distances bunch up.
People call this the curse of dimensionality.
A hundred dice
Why?
Think of dice.
One die shows anything from one to six.
Now add up a hundred dice. What will you get?
One die gives three and a half on average, so a hundred dice give three hundred and fifty. We rolled them five hundred times. Every total landed between about three hundred and four hundred. Add up many random numbers, and the total lands near its average.
Many gaps added
A distance does the same. It squares the gap in each number and adds them up. With seven hundred and sixty-eight numbers, that's seven hundred and sixty-eight random gaps, added up. Every distance is a total of seven hundred and sixty-eight random gaps. So, like the dice, every total lands near the same size. The shortest and the longest end up close... and the nearest comes out almost as far as the farthest.
Directions?
So what if you compare directions instead, with cosine similarity? Does that get around the problem?
Nearly at right angles
Take two random arrows, with numbers above and below zero, and find their cosine similarity. With two numbers, it can be anything from minus one to one. Now spot what happens with seven hundred and sixty-eight.
Nearly all of them land very close to zero: four hundred and ninety-eight out of five hundred.
Zero means a right angle, so these arrows are nearly at right angles. Their dot product adds seven hundred and sixty-eight products. About half are above zero and half below, and they cancel out. So no: cosine similarity bunches up too.
Real data
So how can an AI search, which finds the sentences nearest to yours by their numbers, work at all?
Because real data isn't random.
Take the handwritten digits: eight by eight squares, sixty-four numbers each. Where one square of a three is dark, the squares next to it are dark too.
Their numbers move together.
For random points with sixty-four numbers, the nearest is about six tenths as far as the farthest. And for a typical digit?
About a quarter. And its nearest is the same digit, ninety-nine times in a hundred.
A real model
And a real model's seven hundred and sixty-eight numbers?
They move together too, so a few of them carry most of the meaning.
Google trained one of its models to put what matters most in its first numbers.
Cut each sentence's numbers to the first two hundred and fifty-six.
That's a third. The model keeps nearly all its quality. So, as with the digits, the sentence nearest to yours is still one that means the same thing.
In NumPy
Now let's find a digit's nearest digits in NumPy.
One line loads almost eighteen hundred handwritten digits, each with its label: the digit it shows.
Take one of the threes.
As in the eight lines before, two lines measure its distance to every digit at once. A third line puts the digits in order, nearest first. Which digits will the first six be?
All threes. The first is the three itself, at distance zero, and the next five are other threes.
So to read a digit nobody has labeled, find its nearest digits and take their label. That's called nearest neighbors.
An AI search does the same, on seven hundred and sixty-eight numbers. It puts everything in order, nearest first, and keeps the top few.
All about as far
So in many dimensions, random points are all about as far apart, and random arrows point at nearly right angles.
Real data still works, because its numbers move together.
The lab
That's the end of this unit. In its lab, you'll use these two lessons to find each digit's nearest neighbor, in far fewer numbers.
Numbers that move together
So random points bunch up, but real data doesn't. Now try it on this lesson's page, and take the quiz. Add numbers until the nearest is half as far as the rest.
You use this lesson in Lab 4: Nearest digits, in fewer numbers, which comes next.
Facts last checked on .
