Nobody writes a rule for the machine. You show it examples of mangoes you already know how to classify, and it colors the map with what it "thinks" each region is. Then we test it with mangoes it has never seen.
On the map, choose ask and click anywhere: a new mango (◆) appears, linked to the k examples the machine consults, and its color comes from the vote. With the teach buttons, you decide the color: that is how you give the machine an example.
x = skin color (0 = green, 1 = yellow) and y = firmness (0 = soft, 1 = hard). To the machine, a mango is just a point on the map.
To find the nearest neighbors, the machine has to measure. We see it at a glance; it calculates the distance to each example, like a ruler:
Δx is the difference in skin color and Δy the difference in firmness between the new mango and the example. It is the Pythagorean theorem: the straight-line distance between two points.
The machine picks the k examples with the smallest distance, and the majority decides. That is why k is always odd: there are no ties.
Running the vote on every small piece of the map produces the background colors. Notice that "training" here is just storing the examples: there is no hidden formula, the machine looks at its memory every time.
From the examples. The boundary between "unripe" and "ripe" on the map is just a consequence of where the examples are. Nobody wrote "if the skin is yellow and the fruit is soft, it is ripe." Change or add an example and the rule changes with it.
Because the sample is unbalanced: many unripe, few ripe, and no mango with yellow skin. In that region, the nearest neighbors are mangoes with green or half-yellow skin, almost all unripe, and the machine extends what it saw there. Correct data is not enough: it has to represent all the cases the machine will meet.
The same thing that happened to the yellow mangoes: the machine makes more mistakes with them, without warning. There have been face recognition systems that failed far more often with Black women, and a résumé screening tool that learned, from past hiring, to penalize women. Nobody programmed the prejudice; it came with the data.
With k = 1, the wrong example creates a small "ripe island" around it: the machine memorizes the mistake. With k = 9, it loses the vote to its neighbors and the island disappears. A larger k ignores isolated mistakes, but if it is too large it also erases real details of the boundary. It is the trade-off between memorizing and generalizing.