k-NN classifier: let your nearest neighbors vote

Paint two labeled clouds of points, slide k from 1 to 11, drop a query dot, and watch dashed lines connect to the voters. No training loop: the whole model is your sketch.

y26w46

Last week softmax sampling turned logits into a weighted lottery for the next token. This week there is no softmax and no hidden weights: you store examples and let geometry decide. That lazy, gloriously simple trick is k-nearest neighbors (k-NN), one of the oldest workhorses of supervised learning.

Imagine sorting fruit by height and sweetness on a napkin. Every new dot asks: who are my k closest labeled friends? Majority vote wins. Change k and you change the story: k = 1 trusts a single noisy neighbor; a large k smooths the border but can swallow an outlier whole. The gadget is a tiny machine-learning model that never forgets your training set (for better or worse).

How to play:

  1. Pick class A or class B, stay in Paint training, and click the canvas to sprinkle labeled dots.
  2. Choose Neighbors (k) (try 1, then 11 on the same layout).
  3. Switch to Place query and click where you wonder; dashed lines show who voted.
  4. Load Fuzzy border and drag the query across the overlap; watch the verdict flip as k changes.
  5. Open Lone outlier with k = 1 vs k = 11 and see one far dot boss the vote or get outvoted.

Try this:

  1. Clean split, k = 3, query in the middle gap: the winner should match the closer cloud.
  2. Same preset, k = 11: the vote should stay stable until you cross deep into the other side.
  3. Lone outlier, k = 1, query hugging the stray dot: class A should win even inside class B territory.
  4. Same outlier layout, k = 11: class B should reclaim the center.

Why this matters

Before deep nets ate benchmarks, k-NN was the honest baseline on tabular data and low-dimensional toys. The ImageNet era and AlexNet shift pushed representation learning to the foreground, but k-NN still appears inside retrieval, vector databases, and “we need a sanity check” benchmarks. It also rhymes with the perceptron: both separate space, but k-NN memorizes while the perceptron compresses.

Missed the earlier editions? Train a perceptron, watch a Markov chain babble, lose to unbeatable tic-tac-toe, teach a filter to see edges, watch an agent learn from reward, see how a model reads text in tokens, watch one roll downhill to learn, let a machine find groups on its own, see a line learn to bend, watch words decide who to listen to, explore vs exploit on slot machines, chat with ELIZA, scribble Hopfield memory, count words for spam, paint walls for A*, or spin softmax temperature.

Neighbors (k)

Pick a class, paint training dots, choose k, switch to “Place query”, and click where you wonder. The gadget draws lines to the k closest dots and lets them vote. No training step: the “model” is just the memory of your points.