Lesson 11 of 227 min
k-nearest neighbors
A new penguin gets the kind most of its nearest examples have, and "nearest" only means something when every measurement is on one ruler.
After this lesson you can predict from the closest examples.
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 new penguin on the training set's ruler
The scaler in the pipeline learns each column's average and spread from the training set only. A new penguin is put on that same ruler before its neighbors are found. So its bill sits a little over one spread above the average, and its mass a little over one spread below.
scaler = one_ruler[0]
print(scaler.mean_.round(1), scaler.scale_.round(1))
print(scaler.transform(new).round(2))[ 44. 4214.6] [ 5.4 772.5] [[ 1.16 -1.18]]
Let nearer neighbors count more
By default each of the five votes the same. With weights="distance", a nearer neighbor counts more. It is one more setting, so choose it on the folds. On these penguins it does a little worse.
weighted = make_pipeline(
StandardScaler(), KNeighborsClassifier(weights="distance"))
print(cross_val_score(one_ruler, X_train, y_train).mean().round(3))
print(cross_val_score(weighted, X_train, y_train).mean().round(3))0.937 0.926
Nearest neighbors for a number
To guess a number instead of a kind, KNeighborsRegressor takes the average of the nearest. Here it guesses a penguin's mass from its flipper. Its score is the R² of the linear regression lesson.
fl = df.dropna(subset=["flipper_length_mm"])
Xf, yf = fl[["flipper_length_mm"]], fl["body_mass_g"]
Xf_train, Xf_test, yf_train, yf_test = train_test_split(
Xf, yf, test_size=0.25, random_state=0)
mass = KNeighborsRegressor().fit(Xf_train, yf_train)
print(mass.predict(pd.DataFrame({"flipper_length_mm": [200]})))
print(round(mass.score(Xf_test, yf_test), 3))[3695.] 0.652
Other ways to measure distance
The video used the straight-line distance, scikit-learn's default. metric="manhattan" adds the gaps instead: along the streets, not across them. For embeddings, metric="cosine" compares directions, as the help page's search did. Which works best is a setting too.
for metric in ["euclidean", "manhattan"]:
model = make_pipeline(StandardScaler(), KNeighborsClassifier(metric=metric))
print(metric, cross_val_score(model, X_train, y_train).mean().round(3))euclidean 0.937 manhattan 0.945
Searching many rows fast
Measuring a new row against every training row is slow when there are millions. scikit-learn can build a tree of the rows first and skip the far ones. The answer is the same. Vector search over millions of embeddings uses faster, approximate indexes such as HNSW, taught in Embeddings and Vector Search.
for algorithm in ["brute", "kd_tree"]:
model = make_pipeline(StandardScaler(), KNeighborsClassifier(algorithm=algorithm))
print(algorithm, model.fit(X_train, y_train).predict(new))brute ['Chinstrap'] kd_tree ['Chinstrap']
Run on Python 3.13.3, scikit-learn 1.9.1, pandas 3.1.1. 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
A table has each person's age in years, from 20 to 80, and income in dollars, from 10,000 to 200,000. Measured as they are, which column decides who the nearest neighbors are?
3 of 3
With one neighbor voting, the model gets all 256 of its training penguins right. On five folds, k 1 scores 0.91, k 5 scores 0.94, and k 101 scores 0.82. Which k do you keep?
The ideas in this lesson
- k-nearest neighbours
- A new thing gets the kind most of its k nearest examples have; training only keeps the examples.
- Scale before distances
- Measured as they are, the column with the biggest numbers decides who is nearest; put every column on one ruler first.
- Choosing k
- One neighbour copies every odd example and too many blur the smallest group; choose k on the folds.
It leans on
- Semantic search
Transcript
What the video says, part by part. Press a time to watch from there.
k-nearest neighbors
Here's a game. A new penguin arrives. We know its bill and its mass. Which kind is it? A simple way is to find the penguins most like it. Then let them vote. So which kind will the computer say?
Keep your guess
Hold on to your guess. Here are the penguins, by bill length and mass. Two hundred and fifty-six to learn from, and eighty-six kept aside, just like in the earlier lessons.
The nearest vote
Here is the new penguin. A bill of fifty point three millimeters, and three thousand three hundred grams. How do you guess what kind it is?
Ask the penguins most like it. Find the five nearest, and let them vote.
In this picture, all five are Chinstraps.
So it says Chinstrap.
This way of guessing is called k-nearest neighbors. And k is how many vote. Here, five.
Training keeps the examples
So what did it learn from the two hundred and fifty-six? Nothing, not ahead of time. Training only keeps them. Every guess measures the new penguin against all of them. Ask the same way for every spot in the picture, and you see the kind each spot would get.
As scikit-learn runs it
The five nearest vote.
Now run it the way scikit-learn does, with the bill in millimeters and the mass in grams.
That's as measured: the numbers just as they are. Look at the five it picks. What's wrong?
Four Adelies with much shorter bills, and one Chinstrap. All five are within twenty-five grams of its mass. It says Adelie.
Distance in grams
Why those five?
The computer measures the distance between two penguins with their numbers just as they are.
Look at this Chinstrap, the nearest one in the picture. It's not one of the five. Its bill is zero point two millimeters shorter, and it's a hundred grams heavier. The distance is a hundred.
Now this Adelie. Its bill is twelve point seven millimeters shorter, and its mass is the same. The distance is twelve point seven. To the computer, the Adelie is... about eight times closer.
Grams are big numbers, so the mass decides on its own.
As the computer measures
In the picture, each measurement is stretched to fill its own side. Your eye judged "nearest" from that. The computer has no picture. It only has the numbers. So draw the picture the way it measures, with a millimeter the same size as a gram. The bills cover about twenty-eight millimeters. The masses cover three thousand six hundred grams. Every penguin stands in one thin column, and the nearest are the ones at the same height.
One ruler
So put both measurements on one ruler, the way we did for the bank's columns.
Subtract each one's average, and divide by its spread, how far its values usually sit from the average.
A spread of five point four millimeters on the bill becomes one. A spread of seven hundred and seventy-three grams on the mass becomes one too.
The picture did the same thing for your eye. Will the five nearest change?
Five Chinstraps. It says Chinstrap.
On five folds of the training set, as measured, it's right zero point seven five of the time. On one ruler, zero point nine four.
One neighbor remembers
The k nearest vote, with the measurements on one ruler.
But why five? Let just one neighbor vote. How many of the two hundred and fifty-six will it get right?
All two hundred and fifty-six.
Each penguin it learned from is its own nearest neighbor. So it remembers them, and paints a small patch around every unusual one.
Too many blur
Now let a hundred and one vote. There are only fifty-one Chinstraps to learn from. So near their edges, the other kinds win the vote, and the Chinstraps' region gets smaller.
Choose k on the folds
k is a setting. So choose it on the folds, never on the test set.
One neighbor: zero point nine one. Anything from five to thirty-one: about zero point nine four, too close to call.
A hundred and one: zero point eight two.
So keep five. It's scikit-learn's default, and it's as good as any of them.
Now open the test set, just once.
On one ruler, it gets eighty-one of the eighty-six right. As measured, seventy-six.
And always saying Adelie, the most common kind, gets thirty-eight.
In code
In real code, with scikit-learn.
Here's the new penguin, as a row in a table.
scikit-learn's k nearest neighbors model, fitted as measured.
Ask it for the new penguin's five nearest neighbors, and how far each one is.
And it predicts Adelie.
Put the one-ruler step, a standard scaler, in front of it, in a pipeline. Now it predicts Chinstrap.
Now score both on five folds. Guess the two numbers.
Zero point seven five, and zero point nine four.
The same search runs on a store's help page. Each of its eight answers is a list of seven hundred and sixty-eight numbers, made by an embedding model. Someone types, "I forgot how to log in." The nearest answer is, "Reset your password from the sign-in page." They don't share a single word, but their numbers are close. That's vector search.
Three ideas
So: the nearest examples vote, and k is how many. Measure distance on one ruler, or the biggest numbers decide for you. And you choose k on the folds.
Ask the nearest, on one ruler
So ask the nearest, with every measurement on one ruler. Now try it on this lesson's page, and take the quiz. Move the new penguin until the two rulers disagree.
You use this lesson in Lab 4: Neighbors, a tree and a forest, after Random forests.
Facts last checked on .
