Gradient LabStart the lesson

Lessons › Chapter 4: Classification

k-nearest neighbors

Here is our map of students again, plus a new one (yellow) whose result we don’t know yet. The idea behind k-nearest neighbors is simple: you are probably like the people closest to you.

Watch it move. This lesson is interactive on Gradient Lab: every step is an animated scene you can replay.

Start the interactive lesson

Step by step

Story

Customers like this one

A new customer has almost no history. Maya asks what similar customers did.

Concept

A new point arrives

Here is our map of students again, plus a new one (yellow) whose result we don’t know yet. The idea behind k-nearest neighbors is simple: you are probably like the people closest to you.

Build

Find the closest neighbors

Measure the distance from the new point to every known student, and keep the closest few. How many to keep is called k. Here k = 3.

Key idea

They vote

Count the answers among those 3 neighbors: 2 passed and 1 failed. The majority wins, so the guess is pass.

Build

Changing k can change the answer

With k = 5 the circle grows: 3 passed and 2 failed, so the guess is pass. A small k listens to just a few nearby points (jumpy). A big k listens to many (smoother, but can miss local detail).

Use an odd k for two classes, so a vote can never tie.

Insight

Lazy, but simple

k-NN never really “trains”. It just remembers every example. That makes it easy to understand, but slow when there are millions of examples, because every guess measures distance to all of them.

Real life

In real life: “customers like you also bought”

Online shops and streaming services often recommend by looking at the customers most similar to you (same past purchases, same ratings) and suggesting what those neighbors chose next.

Quick check: With k = 3, two neighbors are cats and one is a dog. What does k-NN guess?

The majority of the 3 nearest neighbors are cats, so the vote goes to cat.

Pseudocode

new_point = [3.8, 3.6]
k = 3

distances = distance from new_point to every example
closest = the k examples with the smallest distance
votes = count the answers among closest
guess = the answer with the most votes

# no training step: it just remembers every example

Key terms

k
In k-nearest neighbors, how many nearby examples get a vote.
neighbors
The examples closest to a new point.

Build it: Your first ML model: an iris flower classifier (20 min, runs in your browser)

See the project