Classifying by Resemblance
The k-nearest neighbors rule is the simplest classifier most people will ever meet. To label a new example, find the k training examples closest to it and let them vote. There is no training phase in the usual sense. The model is the dataset, kept whole, and every prediction is a search through it.
The idea is old. Evelyn Fix and Joseph Hodges described it in a 1951 technical report for the US Air Force School of Aviation Medicine, as a nonparametric way to discriminate between populations without assuming their distributions. In 1967 Thomas Cover and Peter Hart gave it a theoretical footing in «Nearest Neighbor Pattern Classification» (IEEE Transactions on Information Theory). They proved that, as the number of samples grows without limit, the error of the single nearest neighbor rule is less than twice the Bayes error, the lowest error any classifier could reach on that problem. A rule with no parameters and no fitting gets within a factor of two of the best possible. The catch is in the phrase «as the number of samples grows», and most of the later history of the method is about that catch.
Choosing k and the Distance
Two decisions define the classifier. The first is k. With k equal to 1, the decision boundary follows every noisy point and mislabeled example in the training set. With a large k, the boundary smooths out, but small classes get outvoted by their neighbors. In practice k is picked by cross-validation, often an odd number in two-class problems so votes cannot tie, and neighbors are sometimes weighted by the inverse of their distance so the closest ones count more.
The second decision matters more and gets less attention: what «close» means. Euclidean distance on raw features treats a column measured in meters and a column measured in millimeters very differently, so the millimeter column dominates. Scaling features is not optional for this method. Beyond scaling, the distance encodes everything the model believes about similarity. Two photographs that differ by a one-pixel shift are far apart in pixel space and nearly identical to a person. For decades this was why nearest neighbors on raw images worked badly, and it is why the method came back once neural networks started producing embeddings, vectors in which distance tracks meaning far better than pixels do. Most modern vector search compares embeddings by cosine similarity or inner product rather than by Euclidean distance.
Distance Stops Discriminating
In 1999, Kevin Beyer, Jonathan Goldstein, Raghu Ramakrishnan and Uri Shaft published «When Is Nearest Neighbor Meaningful?» at the International Conference on Database Theory. They showed that under broad conditions on how data is distributed, as the number of dimensions grows, the distance from a query to its nearest point approaches the distance to its farthest point. If almost every point sits at roughly the same distance, the «nearest» one is close to arbitrary. Their experiments found the effect showing up with as few as 10 to 15 dimensions.
This result is often quoted as a death sentence for nearest neighbor methods in high dimensions, and the authors said explicitly that it was not. Real data rarely fills its space uniformly. Images, sentences and user histories sit near much lower dimensional structures, and well-trained embeddings are built so that related items cluster. The paper also made a sharper practical point: many proposed high-dimensional indexes had never been compared against a plain linear scan, and some of them lost.
Trees That Split Space
The first serious answer to «how do we avoid comparing the query against everything» was the k-d tree, introduced by Jon Bentley in 1975 in Communications of the ACM. It is a binary search tree that splits the data along one coordinate at each level, cycling through the coordinates. A nearest neighbor query descends to the leaf containing the query, then backtracks only into branches whose region could still hold something closer than the best point found so far. In two or three dimensions this prunes almost the whole tree, which is why k-d trees remain standard in graphics, robotics and geographic software.
In a few hundred dimensions the pruning collapses. The sphere around the query that might hold a closer point intersects nearly every region, so the search visits most of the tree, and the overhead makes it slower than brute force. Exact search in high dimensions has no known shortcut that works in general. The methods that took over all accept a different contract: return points that are very probably among the nearest, and measure how often that is true with a number called recall.
Hashing Similar Things Together
Piotr Indyk and Rajeev Motwani formalized that contract in their 1998 STOC paper «Approximate Nearest Neighbors: Towards Removing the Curse of Dimensionality». Their tool was locality-sensitive hashing. An ordinary hash function scatters similar inputs to unrelated buckets on purpose. A locality-sensitive one does the opposite: similar inputs collide with high probability, dissimilar ones rarely. For cosine similarity, one such family is a random hyperplane, where each vector gets a bit depending on which side of the plane it falls.
Concatenating several such bits gives a bucket key, and building several independent tables raises the chance that a true neighbor shares a bucket with the query in at least one of them. The query then compares itself only against the points in its buckets. LSH came with provable guarantees, which made it attractive in theory. In practice it often needs many tables, and therefore a lot of memory, to reach high recall, and benchmarks over the following decades mostly favored the two families that came next.
Compressing Vectors Into Codes
The second family attacks memory instead of comparisons. Hervé Jégou, Matthijs Douze and Cordelia Schmid introduced product quantization in IEEE TPAMI in 2011. A vector is cut into several sub-vectors, each sub-vector is replaced by the index of its nearest centroid in a small codebook learned with k-means, and the whole vector becomes a short code of a few bytes. Distances between a query and millions of codes can then be computed with table lookups. Combined with an inverted file, which first assigns vectors to coarse clusters and searches only the clusters nearest the query, this made billion-scale search fit in the memory of one machine.
Jégou and Douze, with Jeff Johnson at Facebook AI Research, released «Billion-scale similarity search with GPUs» in 2017. Their GPU k-selection ran nearest neighbor search 8.5 times faster than the previous GPU state of the art, and they built an approximate k-nearest-neighbor graph over one billion vectors in under 12 hours on four GPUs. The code became the FAISS library, which is still one of the most widely used tools in this area.
Navigable Small World Graphs
The third family stores the data as a graph in which each point links to some of its neighbors, and answers a query by greedy walking: start somewhere, move to whichever neighbor is closer to the query, stop when no neighbor improves. Yury Malkov and Dmitry Yashunin’s Hierarchical Navigable Small World graphs (arXiv 2016, published in IEEE TPAMI in 2020) added layers to this walk. Each point is assigned a random maximum level, with exponentially fewer points at each higher level, much like a skip list. A search starts at the sparse top layer, takes long jumps across the dataset, then drops down layer by layer for finer steps. The authors report that this gives logarithmic scaling, and that a heuristic for choosing which neighbors to link, one that favors links pointing in different directions over links to a tight cluster, improves results on clustered data and at high recall.
HNSW became the default index in most vector databases, with one weakness: the graph lives in RAM. DiskANN, from Suhas Jayaram Subramanya and colleagues at Microsoft Research (NeurIPS 2019), moved the graph to an SSD and kept only compressed vectors in memory. On the SIFT1B benchmark, a single workstation with 64 GB of RAM served more than 5,000 queries per second with mean latency under 3 milliseconds and over 95 percent 1-recall@1.
Case: A Language Model With a Lookup Table
In «Generalization through Memorization» (ICLR 2020), Urvashi Khandelwal and colleagues at Stanford and Facebook took a trained transformer language model and stored the hidden representation of every context in its training data, paired with the word that followed it. At prediction time, the model’s current context is used as a query, its nearest stored contexts are retrieved with FAISS, and the words that followed them form a second distribution that is mixed with the model’s own prediction.
Nothing was retrained. On Wikitext-103, perplexity fell from 18.65 for the base model to 16.12 with nearest neighbor retrieval alone, and to 15.79 when a cache model was added, a new state of the art at the time. The gains were largest on rare patterns, such as factual knowledge and names, which a network struggles to store in its weights but which a lookup returns exactly. The same paper showed a model could be adapted to a new domain by swapping the datastore rather than the weights.
Closing Thought
The nearest neighbor rule never learned anything. It needed someone else to supply a distance in which closeness meant similarity, and for fifty years nobody could supply one for images or text, so the method sat in textbooks as a baseline. Deep learning supplied the missing ingredient instead of replacing the method. Today the division of labor is almost the reverse of what early researchers expected: the network learns the geometry, and a search index over that geometry does the remembering. That changes what a model failure looks like. When a system built this way gives a wrong answer, the fault may sit in the embedding, in the data that was stored, or in an index that returned the 95 percent of neighbors it promised and missed the one that mattered.
By: Max Johnson B.
Deja una respuesta