Please enable JavaScript to use CodeHS

Machine Learning Basics

How Does AI Sort Things Into Groups? Meet k-Nearest Neighbors

You are the company you keep. A computer can sort a brand new thing into a group the same way: it looks at the closest examples it already knows and lets them vote. Drag a mystery point around a live map and watch it happen.

Machine Learning ~15 min 3 interactive tools
The Big Idea

You are the company you keep

Say a new student joins your school. You want to guess which lunch table they will pick. You have no list of rules. So you do something simple. You look at the five kids who are most like them, and you see where those five sit.

If four of the five sit at the robotics table, you guess robotics. That is the whole idea behind k-nearest neighbors, often shortened to kNN. It is one of the simplest ways a computer can make a decision.

In one sentence: to label something new, find the k labeled examples that are nearest to it, let them vote, and go with the winner.

Sorting things into groups is called classification. Here are the words you will need. Every one of them shows up in the tools below.

Label
The group name an example belongs to, like "sneaker" or "boot".
Feature
One measurement about a thing, like its height or weight. Features are the clues.
Training data
The pile of examples that already have labels. The computer remembers them.
Neighbor
A labeled example that sits close to the new thing.
k
How many neighbors get a vote. If k is 5, the five closest neighbors vote.

For this tutorial we use a made-up shoe store. Every shoe is one of three types: a sneaker, a boot, or a sandal. We measure two features: how tall the shoe is and how thick its sole is. All the shoes are invented for teaching.


Try It

The neighborhood map

Every shoe becomes a dot on a map. Height goes left to right. Sole thickness goes bottom to top. Shoes of the same type end up near each other, like neighborhoods. Each type has its own color and its own shape, so you can tell them apart even without color.

The glowing white star is a mystery shoe. Drag it, click anywhere on the map, or focus it and use the arrow keys. The lines show its nearest neighbors. The bars show the vote.

Mystery shoe classifier

Your goal: find a spot where the answer changes when you change k.

    The answer

    The vote

      Nearest neighbors, closest first

        5

        Arrow keys move the star by half a step. Hold Shift for bigger steps. Even values of k can tie. A tie goes to the group whose voters are closer.

        Turn on the decision map. It colors every spot on the map by the answer kNN would give if the mystery shoe landed there. Where two colors meet is called a decision boundary. It is the line where the answer flips.


        How Close Is Close?

        Measuring distance

        "Nearest" needs a number. The usual choice is straight-line distance, the same as measuring with a ruler. You can work it out from two simple gaps.

        1. Find how far apart the two shoes are sideways. That is the height gap.
        2. Find how far apart they are up and down. That is the sole gap.
        3. Square each gap, add them, then take the square root. This is the Pythagorean theorem, the same one you use for triangles.

        Example: shoe A is 11 cm tall with a 12 mm sole. Shoe B is 14 cm tall with a 16 mm sole. The gaps are 3 and 4. So the distance is √(9 + 16) = √25 = 5.

        This works with any number of features. You just add one more squared gap for each one.


        Your Turn

        Be the algorithm

        A computer does not "see" the map. It does the math one shoe at a time. Press the big yellow button to follow each step. The mystery shoe is 14 cm tall with a 15 mm sole.

        Step-by-step kNN

        Measure, sort, pick the top k, count the votes.

        ShoeHeightSoleLabelDistance

        The math

        Press the button to measure the first shoe.

        Try this: finish once with k = 1, then start over with k = 5. The closest shoe is a boot, but most of the nearby shoes are sneakers. One odd neighbor can fool a small k.


        Not Too Small, Not Too Big

        Choosing k

        The number k is a dial that you choose. It is not learned from the data. Go back to the neighborhood map, turn on the decision map, and slide k from 1 up to 15.

        • Tiny k (like 1). The map gets jagged. Every single odd shoe makes its own little island. The model is copying noise, which is like trusting one loud friend.
        • Huge k (like 15 or more). The map gets smooth, then blurry. Eventually it ignores where the shoe is. It just picks whichever type has the most examples overall.
        • In the middle. Small odd numbers like 3, 5, or 7 often work well. Odd numbers help because two groups cannot tie in a vote between two choices.

        How do real builders pick? They try several values of k and test each one on examples that were hidden from the vote. The next tool does exactly that kind of testing.


        Garbage In, Garbage Out

        Picking features

        A feature is a clue. Good clues point to the right answer. Bad clues are just noise. And clues measured in huge numbers can shout over the quiet ones.

        The lab below has 36 made-up shoes and four possible clues. Two of them are useful: height and sole thickness. Weight is only loosely related to the type. And the shelf number (where the shoe sat in the store) has nothing to do with the type at all.

        The lab tests itself with a trick called leave-one-out. It hides one shoe, asks kNN with k = 5 to guess its type using the other 35, then checks the guess. It repeats this for every shoe. The score is how many guesses were right.

        Feature lab

        Mix clues, flip scaling, and watch the score.

        Clues kNN may use

        Leave-one-out score

        0of 36 right

        Yellow line: about what you would get by blind guessing with three equal groups (1 in 3).

        Who is doing the talking in the distance?

          Your tries

            Why scaling matters: a weight gap of 200 grams squares to 40,000. A height gap of 5 cm squares to 25. Without scaling, weight wins every argument and height barely whispers. Scaling squeezes each feature into the same range, here 0 to 1, so each clue gets a fair say.


            Why It Matters

            Bad data, bad answers

            kNN has no opinions of its own. It only repeats what its neighbors say. So if the neighbors are wrong or missing, the answer is wrong too. Use the buttons to change the training data and watch the decision map.

            What the training data teaches

            Same mystery shoe tool, three different piles of examples.

              Training data

              The answer

              The vote

                3

                Drag the star or use the arrow keys. The decision map is always on here.

                Notice what happened. With almost no boots in the data, the boot neighborhood nearly vanishes. A real boot would get called a sneaker, and the model would not "know" it was wrong. With wrong labels, small k copies the mistakes.

                This is how bias sneaks into AI. Imagine a model trained on mostly one kind of example. It will be great for that kind and unreliable for everyone else. To learn how this plays out for people, read AI Bias and Fairness.

                What builders do about it: collect examples from all the groups the model will meet, check the labels for mistakes, test the model separately on each group, and pick features that really relate to the answer.


                Quick Answers

                Quick answers

                What is k-nearest neighbors in simple words?

                It is a way for a computer to label something new. It finds the k labeled examples closest to the new thing, counts which label shows up most, and gives the new thing that label. Think of it as asking your closest neighbors to vote.

                How do you choose k?

                Try several values and test each one on examples that were not part of the vote. A very small k can be fooled by one odd example. A very large k blurs the groups together. Small odd numbers like 3 or 5 are a common place to start, because they avoid ties.

                Why do features need to be scaled?

                kNN adds up the gaps in every feature. A feature with big numbers, like weight in grams, makes huge gaps and drowns out a feature with small numbers, like height in centimeters. Scaling puts every feature on the same range so each one gets a fair say.

                Does k-nearest neighbors actually learn anything?

                Not in the usual way. It does not build a formula. It just stores the labeled examples, and the work happens later, when a new point arrives and the computer measures distances. People sometimes call it a lazy learner. To see how other methods learn, read How Do Computers Learn?

                When does k-nearest neighbors give bad answers?

                When the labels are wrong, when one group has far more examples than the others, when the features do not relate to the label, or when features are not scaled. kNN copies whatever pattern is in its data, mistakes and unfairness included.


                Check Yourself

                Quick quiz

                1. A mystery shoe has five nearest neighbors: three sneakers and two boots. What does kNN with k = 5 say?

                2. What happens if you set k to the total number of examples in the data?

                3. Why should you scale features before running kNN?

                Keep learning about AI

                kNN is one way to decide. Next, see how other methods learn from examples, how a tree asks yes-or-no questions, and why fairness matters.

                The shoes in this tutorial are made up for teaching. Results in the tools come from that small invented data set.