Home/Articles/Artificial intelligence

How does a computer "learn"? The nearest-neighbor algorithm

Before huge neural networks, there was a simple idea that explains the core of machine learning: something is usually the same kind as the things most like it.

Illustration generated by code.

Learning from examples

We do not write the computer a rule like "if it is this, then it is an apple." Instead, we give it labeled examples: these fruits weigh this much and are this color, and they are apples; those are oranges. Then we ask it about a new fruit it has never seen.

The idea: look at your neighbors

We represent each fruit as a point on a graph: weight on one axis, and color shade on another. When a new fruit arrives, we find the k points closest to it and see which type is most common among them. If k is 5, and among the five nearest neighbors there are four apples and one orange, we say it is most likely an apple.

This is the nearest-neighbor algorithm (k-NN). It does not need "training" in the usual sense; it stores the examples and compares when asked.

Choosing k

If k is too small, such as 1, the answer is influenced by a single example that may have been labeled wrongly. If it is too large, the most numerous class dominates the answer. We choose k by testing: we hide some of the examples, and see which value gives the most accurate results on them.

What can we learn from it?

  • Data matters more than the algorithm: a few examples, or biased ones, give poor or unfair results.
  • Choosing features matters: if we measured weight in grams and color from 0 to 1, weight would dominate the distance. That is why we put the scales on the same footing first.
  • Accuracy must be measured on examples the model has not seen, otherwise we fool ourselves.

An educational article written by the Madar team to simplify a scientific idea. Madar is a center in its founding stage, and what appears here about its programs consists of proposed plans.