Saturday, November 28, 2026
HomeC ProgrammingOk-Nearest Neighbors (KNN) in Python and C++: How It Works

Ok-Nearest Neighbors (KNN) in Python and C++: How It Works


In cross-validation on the wine dataset, k-nearest neighbors with ok = 27 labeled 70.9% of wines accurately utilizing the uncooked measurements and 97.6% after standardizing them. Nothing in regards to the algorithm modified. Earlier than scaling, a single measurement, proline, whose values run from 278 to 1,680, provided 99.7% of each squared distance between wines, so the opposite 12 chemical measurements hardly counted.

This tutorial explains KNN from the gap method to the vote, builds it from scratch in NumPy and once more in C++17, checks each towards scikit-learn and towards one another and measures what issues in observe: characteristic scaling, the selection of ok, the gap metric, the curse of dimensionality and the pace of 5 implementations on the identical knowledge. Each Python program was run for this text with Python 3.15.2, NumPy 2.5.5 and scikit-learn 1.9.1 on Ubuntu 24.04, and the output was equivalent on Python 3.13 and on Home windows 11 with Python 3.14; the C++ was constructed with GCC 13.3, Clang 18.1 and MSVC with warnings as errors. Each output block on this web page is captured from the companion repositories.

What Is Ok-Nearest Neighbors?

Ok-nearest neighbors (KNN) is a supervised studying algorithm that classifies a brand new instance by discovering the ok coaching examples closest to it and taking a majority vote of their labels. It has no coaching section past storing the information: all of the work occurs at prediction time, when it measures the gap from the question to each saved instance.

KNN known as a lazy or instance-based learner for that purpose. It makes no assumption in regards to the form of the boundary between courses, so it will possibly comply with any curve, but it surely relies upon fully on the gap it’s given: if the options are on completely different scales, or a lot of them are irrelevant, the “nearest” neighbors will not be probably the most comparable ones. The identical thought works for regression (common the neighbors’ values as an alternative of voting), however this text covers classification. In Python, the usual implementation is scikit-learn’s KNeighborsClassifier, which this text rebuilds by hand after which makes use of as a reference.

When to Use KNN (and When Not To)

Scenario Good match? Why
A number of thousand to some hundred thousand rows, tens of options Sure Brute-force search is quick sufficient and there may be nothing to tune however ok and the gap
The category boundary is irregular Sure KNN follows the information domestically as an alternative of becoming a line or a airplane
New labelled knowledge arrives on a regular basis Sure “Coaching” is appending rows; no mannequin must be refitted
You want a fast, sincere baseline Sure One parameter and no coaching; you’ll be able to clarify a end result by exhibiting the neighbors
Options on very completely different scales Solely after scaling With out it, the largest-valued characteristic decides each distance (measured beneath)
Tons of of options, a lot of them irrelevant Hardly ever Distances lose distinction and noise options swamp the helpful ones (measured beneath)
Tens of millions of rows with tight latency limits With an index Use a k-d tree, a ball tree or an approximate nearest neighbor index as an alternative of brute drive
You want chances you’ll be able to belief With care Vote shares are available steps of 1/ok and will not be calibrated

How KNN Works

  1. Retailer the coaching knowledge. Becoming a KNN mannequin solely retains the characteristic rows and their labels.
  2. Scale the options. Deliver each characteristic to a comparable vary, utilizing statistics from the coaching rows solely.
  3. Measure the gap from the question to each coaching row, normally Euclidean or Manhattan.
  4. Choose the ok nearest rows. Type by distance and hold the primary ok, with a set rule for equal distances.
  5. Vote. The commonest label among the many ok neighbors wins, optionally with nearer neighbors counting extra.
  6. Break ties deterministically. With an excellent ok or greater than two courses, votes can tie; determine the rule prematurely.

In pseudocode:

match(X, y):    retailer X and y

predict(q):
    for every coaching row i:  d[i] = distance(q, X[i])
    nearest = the ok indices with the smallest d   # equal distances: decrease index first
    votes   = depend of every label amongst y[nearest]
    return the label with probably the most votes          # tied vote: the smallest label

The Math Behind KNN

Distance

For 2 examples x and z with m options, the Euclidean distance is the straight-line distance:


The Manhattan (city-block) distance provides absolutely the variations as an alternative:


Each are particular circumstances of the Minkowski distance with p = 2 and p = 1; scikit-learn’s default is Minkowski with p = 2, which is Euclidean. Manhattan is much less dominated by a single massive distinction, as a result of variations will not be squared.

The vote

With Nok(x) the set of the ok coaching rows nearest to x, the prediction is the category with the most important complete weight amongst them:


the place [yi = c] is 1 when neighbor i has class c and 0 in any other case. With uniform weights each neighbor counts as soon as; with distance weights a neighbor counts 1/d, so nearer neighbors matter extra. A neighbor at distance 0 (an actual duplicate of the question) would get an infinite weight; the rule used right here and in scikit-learn is that such neighbors take the entire vote.

Scaling

Standardization rescales each characteristic j to imply 0 and customary deviation 1:


the place μj and σj are the imply and customary deviation of characteristic j computed on the coaching rows solely. After standardization, each characteristic contributes the identical common squared distinction between rows, so no characteristic dominates the gap simply due to its models.

Selecting ok

ok controls how native the choice is. With ok = 1 the prediction copies the one nearest row, so it follows each noisy level within the coaching knowledge (low bias, excessive variance). A big ok averages over a large neighborhood and smooths the boundary, till at ok = n it predicts the bulk class all over the place (excessive bias, low variance). Odd values keep away from two-way ties between two courses. The proper ok relies on the information and is chosen by cross-validation, by no means on the take a look at set.

A Labored Instance by Hand

Seven labelled factors, 4 of sophistication A and three of sophistication B, and one question at (3, 3); a small, made-up instance chosen in order that the reply modifications with ok:

Level (2, 4) (0, 4) (5, 4) (0, 1) (3, 6) (2, 3) (5, 5)
Class A A A A B B B

The squared distances are small integers. For (2, 4): (2 − 3)² + (4 − 3)² = 2, so the gap is √2 = 1.414. The closest level is (2, 3) at squared distance 1, and it’s class B, so with ok = 1 the prediction is B. The following two are (2, 4) and (5, 4), each class A, so with ok = 3 the vote is 2 to 1 for A. The fourth and fifth are each B, so with ok = 5 the vote is 3 to 2 for B.

This system beneath repeats the calculation with the from-scratch classifier:

"""The article's labored instance: seven labelled factors, one question, 4 values of ok."""

import numpy as np

from knn import KNNClassifier

factors = np.array([[2, 4], [0, 4], [5, 4], [0, 1], [3, 6], [2, 3], [5, 5]], float)
labels = np.array(["A", "A", "A", "A", "B", "B", "B"])
question = np.array([[3.0, 3.0]])

mannequin = KNNClassifier(ok=7).match(factors, labels)
dist, idx = mannequin.kneighbors(question)
print("question (3, 3); coaching factors sorted by distance:")
print("rank  level   class  squared  distance")
for rank, (i, d) in enumerate(zip(idx[0], dist[0], strict=True), begin=1):
    x, y = factors[i]
    sq = (x - 3) ** 2 + (y - 3) ** 2
    print(f"{rank:4}  ({x:.0f}, {y:.0f})  {labels[i]:>5}  {sq:7.0f}  {d:8.3f}")

print("n ok  votes A  votes B  prediction")
for ok in (1, 3, 5, 7):
    close to = labels[idx[0, :k]]
    a, b = int((close to == "A").sum()), int((close to == "B").sum())
    pred = KNNClassifier(ok=ok).match(factors, labels).predict(question)[0]
    print(f"{ok:2}  {a:7}  {b:7}  {pred:>10}")

Output:

question (3, 3); coaching factors sorted by distance:
rank  level   class  squared  distance
   1  (2, 3)      B        1     1.000
   2  (2, 4)      A        2     1.414
   3  (5, 4)      A        5     2.236
   4  (5, 5)      B        8     2.828
   5  (3, 6)      B        9     3.000
   6  (0, 4)      A       10     3.162
   7  (0, 1)      A       13     3.606

 ok  votes A  votes B  prediction
 1        0        1           B
 3        2        1           A
 5        2        3           B
 7        4        3           A

The prediction flips thrice as ok grows from 1 to 7. Nothing is fallacious with the algorithm: close to the boundary between two courses, the reply genuinely relies on how far you look. That’s the reason ok must be chosen with knowledge, as the following sections do.

−1 0 1 2 3 4 5 6 7 characteristic 1 0 1 2 3 4 5 6 7 characteristic 2 1 2 3 4 5 6 7 The identical question, a distinct reply for every ok ok = 1 or 5: B wins ok = 3: A wins class A class B question (3, 3)

Determine 1: The labored instance. Numbers give every level’s rank by distance from the question. The dashed circles maintain the 1, 3 and 5 nearest factors, and the vote inside each flips the prediction.

KNN in Python From Scratch

The classifier lives in knn.py and desires solely NumPy. The distances are computed for 256 question rows at a time, in order that the momentary array of variations stays a manageable dimension, and nearest kinds every row with a secure type, in order that equal distances hold the decrease coaching index first:

def pairwise_distances(
    A: FloatArray, B: FloatArray, metric: Metric = "euclidean"
) -> FloatArray:
    """Distance from each row of A to each row of B, form (len(A), len(B))."""
    out = np.empty((A.form[0], B.form[0]))
    for begin in vary(0, A.form[0], 256):  # 256 question rows at a time
        diff = A[start : start + 256, None, :] - B[None, :, :]
        if metric == "euclidean":
            out[start : start + 256] = np.sqrt(np.einsum("qnd,qnd->qn", diff, diff))
        else:
            out[start : start + 256] = np.abs(diff).sum(axis=2)
    return out


def nearest(distances: FloatArray, ok: int) -> IntArray:
    """Indices of the ok smallest distances in every row; ties go to the decrease index."""
    order = np.argsort(distances, axis=1, form="secure")
    return order[:, :k].astype(np.int64)

The vote provides every neighbor’s weight to its class and divides by the full, which provides the category shares that predict_proba returns:

def vote(
    labels: IntArray, distances: FloatArray, n_classes: int, weights: Weights
) -> FloatArray:
    """Every row's share of the vote per class, from its neighbors' labels."""
    if weights == "uniform":
        w = np.ones_like(distances)
    else:
        with np.errstate(divide="ignore"):
            w = 1.0 / distances
        actual = distances == 0.0  # a neighbor at distance 0 takes the entire vote
        has_exact = actual.any(axis=1)
        w[has_exact] = actual[has_exact].astype(np.float64)
    shares = np.zeros((labels.form[0], n_classes))
    np.add.at(shares, (np.arange(labels.form[0])[:, None], labels), w)
    complete: FloatArray = shares / shares.sum(axis=1, keepdims=True)
    return complete

match solely validates and shops the information; predict takes the category with the most important share. np.argmax returns the primary most, so a tied vote goes to the smallest label, which can also be scikit-learn’s rule:

    def predict_proba(self, X: ArrayLike) -> FloatArray:
        dist, idx = self.kneighbors(X)
        labels = self.y_codes_[idx].astype(np.int64)
        return vote(labels, dist, len(self.classes_), self.weights)

    def predict(self, X: ArrayLike) -> NDArray[np.generic]:
        # argmax returns the primary most: a tied vote goes to the smallest label
        winners = np.argmax(self.predict_proba(X), axis=1)
        end result: NDArray[np.generic] = self.classes_[winners]
        return end result

Standardization makes use of the coaching rows’ imply and inhabitants customary deviation, the identical as scikit-learn’s StandardScaler, and applies them unchanged to the take a look at rows:

def standardize(
    X_train: FloatArray, X_test: FloatArray
) -> tuple[FloatArray, FloatArray]:
    """Scale each characteristic to imply 0 and customary deviation 1 on the coaching rows."""
    imply = X_train.imply(axis=0)
    std = X_train.std(axis=0)  # inhabitants customary deviation, as StandardScaler
    return (X_train - imply) / std, (X_test - imply) / std

The repository’s 20 checks test the distances towards SciPy, the labored instance, each tie guidelines, distance-weighted votes together with the zero-distance case, that neighbors come again sorted even for big ok, equivalent predictions, chances, neighbor indices and distances to scikit-learn on the wine knowledge for 20 mixtures of ok, metric and weights, standardization from the coaching rows solely and enter validation. A separate script re-applies 16 believable bugs to a replica of the code, from a lacking sq. root to labels assumed to be 0, 1, 2; each one makes a take a look at fail.

KNN on a Actual Dataset: Why Function Scaling Issues

The Wine dataset data 13 chemical measurements of 178 wines grown in the identical area of Italy from three completely different cultivars (UCI Machine Studying Repository). It ships with scikit-learn as load_wine, and its measurements sit on very completely different scales: hue ranges from 0.48 to 1.71, magnesium from 70 to 162 and proline from 278 to 1,680.

Property Worth
Supply Aeberhard and Forina (1992), UCI Machine Studying Repository, doi:10.24432/C5PC7J; bundled with scikit-learn
License CC BY 4.0
Rows and options 178 wines, 13 numeric chemical measurements
Lessons 3 cultivars: 59, 71 and 48 wines
Break up 75/25, stratified, random_state=42: 133 coaching rows, 45 take a look at rows
Mannequin choice 5-fold cross-validation repeated 10 occasions on the coaching rows, scaler refitted inside each fold

The experiment estimates the accuracy of each odd ok from 1 to 31 by repeated cross-validation, as soon as with the uncooked options and as soon as standardized, with the scaler fitted inside every fold in order that the validation rows by no means affect it:

def cv_curve(scale: bool, metric: Metric, weights: Weights) -> FloatArray:
    """Imply accuracy for each ok in KS over 5-fold CV repeated 10 occasions."""
    scores = np.zeros(len(KS))
    for fit_idx, val_idx in FOLDS:
        A, B = X_train[fit_idx], X_train[val_idx]
        if scale:
            A, B = standardize(A, B)
        for i, ok in enumerate(KS):
            mannequin = KNNClassifier(ok=ok, metric=metric, weights=weights)
            pred = mannequin.match(A, y_train[fit_idx]).predict(B)
            scores[i] += (pred == y_train[val_idx]).imply()
    end result: FloatArray = scores / len(FOLDS)
    return end result

It then picks one of the best ok for 4 variants on the coaching rows, applies every to the 45 take a look at rows as soon as and at last checks that the from-scratch classifier and scikit-learn agree:

unscaled      proline's share of squared distance: 99.7%
standardized  proline's share of squared distance: 7.7%

cross-validated accuracy on the coaching rows (5 folds x 10 repeats)
  ok  unscaled  standardized
  1     0.741         0.952
  3     0.682         0.961
  5     0.691         0.957
  7     0.706         0.963
  9     0.684         0.965
 11     0.692         0.968
 13     0.695         0.968
 15     0.697         0.970
 17     0.702         0.972
 19     0.699         0.969
 21     0.702         0.970
 23     0.712         0.971
 25     0.707         0.974
 27     0.709         0.976
 29     0.703         0.974
 31     0.703         0.973

greatest ok for every variant (the smallest ok amongst equal scores)
unscaled, euclidean                          ok=1   0.741
standardized, euclidean                      ok=27  0.976
standardized, manhattan                      ok=7   0.985
standardized, euclidean, distance-weighted   ok=29  0.976

take a look at rows: 45
scikit-learn defaults: unscaled, ok=5         ok=5   35/45 = 0.778
unscaled, euclidean                          ok=1   33/45 = 0.733
standardized, euclidean                      ok=27  43/45 = 0.956
standardized, manhattan                      ok=7   44/45 = 0.978
standardized, euclidean, distance-weighted   ok=29  44/45 = 0.978

similar take a look at predictions as scikit-learn: 64 of 64 settings

1 5 9 13 17 21 25 29 ok (variety of neighbors) 0.60 0.65 0.70 0.75 0.80 0.85 0.90 0.95 1.00 accuracy (5-fold CV, 10 repeats) greatest ok = 27 proline provides 99.7% of each squared distance Scaling the options issues greater than selecting ok standardized options unscaled options

Determine 2: Cross-validated accuracy on the 133 coaching wines for each odd ok from 1 to 31. Standardizing the 13 options lifts each ok from about 0.68 to 0.74 to about 0.95 to 0.98. The very best ok, 27, is chosen right here, earlier than the take a look at rows are used.

Studying the outcomes:

  • Scaling is price greater than all the pieces else mixed. No worth of ok will get the unscaled mannequin above 0.741 in cross-validation; each worth of ok will get the standardized mannequin above 0.95. On the take a look at rows, scikit-learn’s defaults on uncooked options (ok = 5, no scaling) labeled 35 of 45 wines accurately; the standardized mannequin chosen by cross-validation obtained 43.
  • The reason being one characteristic. Proline is measured within the tons of to hundreds, so its variations dwarf everybody else’s: it provides 99.7% of the squared distance between coaching rows. After standardization every of the 13 options provides 1/13, or 7.7%.
  • ok issues a lot much less as soon as the options are scaled. The standardized curve stays between 0.952 and 0.976 for each ok from 1 to 31. Cross-validation picked ok = 27, however something from about 7 up would do practically as nicely.
  • Manhattan distance did greatest right here. With ok = 7 it reached 0.985 in cross-validation and 44 of 45 on the take a look at rows. That may be a property of this dataset, not a normal rule; it’s the type of option to make by cross-validation, not by behavior.
  • The from-scratch mannequin matches scikit-learn precisely. It made the identical 45 take a look at predictions in all 64 mixtures of ok, metric and weighting.

A take a look at set of 45 rows is small: one wine is 2.2 proportion factors. The cross-validated numbers, averaged over 50 suits, are the extra dependable comparability; the take a look at rows affirm them as soon as.

Selecting ok With out Fooling Your self

KNN makes two analysis errors unusually simple. The pitfall program exhibits each on the identical knowledge:

ok=1, unscaled     accuracy by itself coaching rows: 1.000
ok=1, standardized accuracy by itself coaching rows: 1.000

standardized, test-set rating for each odd ok from 1 to 31 (of 45):
1:43 3:43 5:42 7:44 9:44 11:44 13:44 15:45 17:45 19:45 21:45 23:45 25:44 27:43 29:44 31:43
greatest ok chosen on the take a look at rows: ok=15, 45/45
ok=27 chosen by cross-validation on the coaching rows: 43/45

Scored by itself coaching rows, a 1-nearest-neighbor mannequin is at all times 100% appropriate, scaled or not, as a result of each row is its personal nearest neighbor at distance 0. That quantity measures nothing.

Selecting ok by its rating on the take a look at rows is subtler. Attempting 16 values of ok and conserving one of the best one discovered ok = 15 with 45 of 45 appropriate, however that excellent rating is partly luck: with 45 rows, a number of ok values land on 44 or 45 by probability, and selecting the utmost picks the luckiest. The sincere process, selecting ok = 27 by cross-validation on the coaching rows after which scoring it as soon as, studies 43 of 45. That’s the quantity to anticipate on new wines.

The Curse of Dimensionality

KNN assumes that “close to” means “comparable”. Because the variety of options grows, that assumption weakens in two measurable methods:

uniform random factors: 1,000 reference factors, 100 queries
 dims  nearest  farthest  (far - close to) / close to
    2    0.018     1.045                90.26
    5    0.169     1.492                 8.61
   10    0.503     1.886                 2.84
   20    1.034     2.466                 1.40
   50    2.134     3.581                 0.68
  100    3.307     4.746                 0.44
  200    5.039     6.498                 0.29
  500    8.382     9.860                 0.18
 1000   12.174    13.623                 0.12

wine, standardized, ok=27: cross-validated accuracy with noise columns added
(imply over 5 completely different attracts of the noise)
noise columns  accuracy
            0     0.976
            5     0.966
           10     0.955
           20     0.940
           50     0.901
          100     0.844
          200     0.770
          500     0.650

1 0 1 1 0 2 1 0 3 dimensions (uniform random knowledge) 1 0 − 1 1 0 0 1 0 1 1 0 2 (farthest – nearest) / nearest Distances lose their distinction 0 10 100 500 noise columns added to wine 0.60 0.65 0.70 0.75 0.80 0.85 0.90 0.95 1.00 accuracy (5-fold CV, ok = 27) Irrelevant options drown the sign The curse of dimensionality, measured

Determine 3: Left, 100 random queries towards 1,000 random factors: the farthest level is about 90 occasions farther than the closest in 2 dimensions and solely 12% farther in 1,000. Proper, cross-validated accuracy on the standardized wine knowledge as columns of pure noise are added (imply of 5 noise attracts).

Distances lose distinction. With 1,000 random factors in 2 dimensions, the farthest level is on common about 90 occasions farther from a question than the closest one. In 1,000 dimensions the farthest is barely 12% farther than the closest. When each level is roughly the identical distance away, “the ok nearest” is near an arbitrary selection.

Irrelevant options drown the sign. Appending columns of pure random noise to the 13 standardized wine options lowered cross-validated accuracy from 0.976 to 0.940 with 20 noise columns, 0.844 with 100 and 0.650 with 500. Each noise column provides the identical anticipated quantity to each squared distance, and sufficient of them bury the variations that the true options present.

The sensible guidelines: hold options that carry sign, scale back dimensions (for instance with principal part evaluation) earlier than utilizing KNN on extensive knowledge, and don’t anticipate brute-force KNN on uncooked high-dimensional vectors to work in addition to it does on 13 measurements.

KNN in C++

The C++17 model in knn.hpp follows the identical guidelines because the Python one, so the 2 will be in contrast output for output. As a substitute of sorting each distance, it makes use of std::nth_element to maneuver the ok nearest to the entrance in linear time after which kinds solely these ok:

// The ok coaching rows nearest to question, nearest first.
inline std::vector<Neighbor> nearest(const Dataset& practice, const double* question, std::size_t ok,
                                     Metric metric = Metric::euclidean)
{
    if (ok == 0 || ok > practice.rows)
        throw std::invalid_argument("ok should be between 1 and the variety of coaching rows");
    std::vector<Neighbor> all(practice.rows);
    for (std::size_t r = 0; r < practice.rows; ++r)
        all[r] = {distance(question, practice.row(r), practice.cols, metric), r};
    const auto nearer = [](const Neighbor& a, const Neighbor& b)  (a.distance == b.distance && a.index < b.index);
    ;
    // nth_element places the ok nearest first in O(n); solely these ok are sorted.
    const auto kth = all.start() + static_cast<std::ptrdiff_t>(ok);
    std::nth_element(all.start(), kth - 1, all.finish(), nearer);
    std::type(all.start(), kth, nearer);
    all.resize(ok);
    return all;
}

// Majority vote of the ok nearest; a tie goes to the smallest label.
inline int predict_one(const Dataset& practice, const double* question, std::size_t ok,
                       Metric metric = Metric::euclidean)
{
    const std::vector<Neighbor> nbrs = nearest(practice, question, ok, metric);
    std::vector<std::pair<int, int>> votes;  // (label, depend), sorted by label
    for (const Neighbor& n : nbrs) {
        const int label = practice.labels[n.index];
        auto it = std::lower_bound(votes.start(), votes.finish(), std::make_pair(label, 0),
                                   [](const auto& a, const auto& b) { return a.first < b.first; });
        if (it == votes.finish() || it->first != label)
            it = votes.insert(it, {label, 0});
        ++it->second;
    }
    std::pair<int, int> greatest = votes.entrance();
    for (const auto& v : votes)
        if (v.second > greatest.second)  // strictly extra: the smaller label retains a tie
            greatest = v;
    return greatest.first;
}

The comparability operate orders by distance after which by training-row index, which provides each pair of neighbors a strict order. The result’s subsequently the identical whichever customary library implements nth_element and type. The vote retains the primary label with probably the most votes, and for the reason that labels are stored in rising order, a tie goes to the smallest label, as within the Python model and in scikit-learn. The C++ Normal Template Library information covers nth_element and the opposite choice algorithms.

The 2 variations are checked towards one another. The C++ program reads the identical wine_split.csv that the Python one reads, standardizes it the identical manner and prints the identical report; each repositories examine that report with the identical anticipated file, so a change in both language that alters a single prediction or the sixth decimal of a distance fails the construct:

wine: 133 coaching rows, 45 take a look at rows, 13 options
share of squared distance from proline, unscaled: 99.7%
share of squared distance from proline, standardized: 7.7%

appropriate take a look at predictions (of 45)
 ok  metric     unscaled  standardized
 1  euclidean        33            43
 5  euclidean        35            42
27  euclidean        35            43
 7  manhattan        38            44

nearest coaching rows to check row 0 (class 0), standardized
rank  row  class  distance
   1   50      0  1.389466
   2  108      0  1.904063
   3  130      0  1.919836
   4  122      0  1.963002
   5   52      0  1.963258

The C++ checks additionally test the labored instance, each tie guidelines, nearest towards a full secure type on random knowledge with many equal distances, standardization, error messages for malformed CSV recordsdata, Home windows line endings and a splitmix64 random-number stream that each languages generate bit for bit. They cross below AddressSanitizer, UndefinedBehaviorSanitizer and Valgrind, and a script that places 14 deliberate errors into a replica of the header confirms that every one is caught.

Efficiency: Python, NumPy, C++ and scikit-learn

Brute-force KNN prices one distance per coaching row per question, so its pace relies upon nearly fully on how that interior loop is executed. The benchmark generates 20,000 coaching rows and 1,000 queries with 8 options from the shared splitmix64 stream, and each implementation should produce the identical 1,000 predictions (checksum 502492) earlier than any time is in contrast. Every thing runs on one thread.

The Python facet occasions pure Python, this text’s NumPy classifier and scikit-learn:

20,000 coaching rows, 1,000 queries, 8 options, ok=5
checksum of predictions: 502492; accuracy 0.889
scikit-learn brute, k-d tree and pure Python agree: True

microseconds per question (median of repeated runs), x86_64
pure Python (20 queries)                  14708.3
NumPy, this text's KNNClassifier        3087.8
scikit-learn, algorithm='brute'              73.1
scikit-learn, algorithm='kd_tree'            38.9

The C++ program, constructed with GCC 13.3 in Launch mode (-O3, CMake’s default), on the identical machine:

20000 coaching rows, 1000 queries, 8 options, ok=5
checksum of predictions: 502492; accuracy 0.889
microseconds per question (median of 5 runs): 278.4

1 0 1 1 0 2 1 0 3 1 0 4 1 0 5 microseconds per question (log scale, one thread) pure Python NumPy, from scratch C++, from scratch scikit-learn, brute scikit-learn, k-d tree 14,708 µs 3,088 µs 278 µs 73 µs 39 µs Identical knowledge, similar 1,000 predictions, 5 implementations

Determine 4: Median time per question to categorise 1,000 queries towards 20,000 coaching rows with 8 options and ok = 5, on one thread of 1 Linux digital machine. All 5 make equivalent predictions.

What the numbers present:

  • NumPy from scratch is about 5 occasions sooner than pure Python, and the plain C++ loop is about 11 occasions sooner than that. The NumPy model builds a 256 × 20,000 × 8 array of variations for each block of queries and absolutely kinds 20,000 distances per question; the C++ model computes every distance in registers and selects the ok nearest with no full type.
  • scikit-learn’s brute-force search beat the easy C++ by about 4 occasions. Its Euclidean path computes distances in blocks with matrix multiplication for the cross time period and retains solely the ok greatest candidates per question in a small heap. Compiled code is just not mechanically quick; the algorithm and the reminiscence entry sample determine.
  • The k-d tree was sooner nonetheless at 8 options, as a result of it skips most coaching rows with out computing their distances. Tree indexes lose that benefit because the variety of options grows, for the explanations proven within the earlier part.

These are medians of repeated runs on one Linux digital machine (Intel Xeon at 2.10 GHz, 2 vCPUs), and so they moved between runs: throughout six runs of the Python benchmark and 5 of the C++ one, pure Python ranged from about 14,000 to 23,000 microseconds per question, NumPy from 3,000 to three,460, C++ from 269 to 292, scikit-learn brute drive from 64 to 76 and the k-d tree from 39 to 60. The order of the 5 by no means modified; absolutely the numbers belong to this machine. On the Home windows 11 desktop used for the Home windows checks (Intel Core i7-8700K at 3.70 GHz), the identical applications gave pure Python 14,640, NumPy 2,005, C++ constructed with MSVC 282, scikit-learn brute drive 73.5 and the k-d tree 43.3 microseconds per question: the identical order, with the identical checksum. The benchmark measures prediction on in-memory knowledge solely. It doesn’t measure multi-threading, bigger ok, different dimensions, approximate indexes or the time to construct the k-d tree.

Complexity and Scaling

Methodology Construct Per question Use when
Brute drive (this text) O(1): retailer the rows O(n m) distances plus O(n) choice As much as tons of of hundreds of rows; any variety of options
k-d tree O(n log n) About O(log n) in low dimensions, close to O(n) in excessive Few options (roughly as much as 20), many queries
Ball tree O(n log n) Higher than a k-d tree on many options or non-Euclidean metrics Average dimensions, different metrics
Approximate index (for instance HNSW graphs) Giant, constructed as soon as Sub-linear, might miss some true neighbors Tens of millions of high-dimensional vectors, similar to embeddings

Right here n is the variety of coaching rows and m the variety of options. Reminiscence is O(n m) in each case: KNN retains the entire coaching set. For the choice step, nth_element (common linear time) is cheaper than a full O(n log n) type, which is one purpose the C++ model beats the NumPy one; the sorting algorithms article measures the price of full kinds. The k-d tree is a binary search tree that splits on one characteristic per degree, the identical construction because the binary bushes it’s constructed from.

Frequent Errors With KNN

1. Not scaling the options. On the wine knowledge, uncooked options gave 35 of 45 appropriate with scikit-learn’s defaults and standardized options gave 43, as a result of proline alone provided 99.7% of each squared distance. Scale each characteristic, and match the scaler on the coaching rows solely.

2. Becoming the scaler on all the information. Statistics computed on the take a look at rows leak data into the mannequin. Compute the imply and customary deviation on the coaching rows (inside every cross-validation fold) and reuse them for all the pieces else, as standardize and cv_curve do above.

3. Reporting coaching accuracy. With ok = 1, accuracy on the coaching rows is 100% on any knowledge, as a result of each row finds itself.

4. Selecting ok on the take a look at set. It turned a 43/45 mannequin right into a reported 45/45. Select ok by cross-validation on the coaching rows and rating the take a look at rows as soon as.

5. Including each accessible characteristic. 100 noise columns took cross-validated accuracy from 0.976 to 0.844. Irrelevant options don’t simply fail to assist KNN; they actively push the helpful ones out of the gap.

Mannequin Coaching Determination boundary Key distinction from KNN
Ok-nearest neighbors None: shops the information Any form, follows the information domestically Prediction value grows with the coaching set
Logistic regression Suits one weight per characteristic Straight (a hyperplane) Compact mannequin, quick prediction, calibrated chances
Determination tree Learns threshold splits Axis-aligned steps Insensitive to characteristic scale; prediction value relies on depth, not knowledge dimension
Naive Bayes Estimates per-class characteristic distributions Straight or curved Generative; quick on very extensive knowledge similar to textual content
Assist vector machine Finds the maximum-margin boundary Straight, or curved with a kernel Additionally distance-based with a kernel, however retains solely the help vectors

For a linear baseline on the identical type of downside, see logistic regression from scratch, which this collection builds the identical manner.

Key Takeaways

  • KNN classifies by a majority vote of the ok closest coaching examples; it shops the information and does all of its work at prediction time.
  • Scale the options earlier than anything. On the wine knowledge, standardizing took cross-validated accuracy from at most 0.741 to at the very least 0.952, for each ok.
  • Select ok, the gap and the weighting by cross-validation on the coaching rows, by no means by the take a look at rating; selecting ok on the take a look at set reported 45/45 for a mannequin that scores 43/45 truthfully.
  • Extra options could make KNN worse. 100 columns of noise reduce accuracy from 0.976 to 0.844, and in 1,000 random dimensions the farthest level was solely 12% farther than the closest.
  • Repair the tie guidelines (equal distances, tied votes) in order that outcomes are reproducible throughout runs, languages and compilers.
  • Velocity relies on the implementation greater than the language: on the identical knowledge, a plain C++ loop was about 50 occasions sooner than pure Python, and scikit-learn’s brute drive was about 4 occasions sooner than the plain C++.

Conclusion

Ok-nearest neighbors is the only classifier that works: retailer the examples, measure distances, let the closest ones vote. Its simplicity places all the load on the gap, which is why a very powerful line in a KNN program is normally not within the classifier in any respect however within the preprocessing. On the wine knowledge, scaling the options mattered greater than any selection of ok, metric or weighting, and 100 irrelevant options undid many of the profit.

The identical questions carry over to each distance-based technique that follows, from k-means clustering to the vector search behind trendy embedding methods: what does “close to” imply for these options, and does it nonetheless imply something on this many dimensions? Extra tutorials on this collection are collected within the synthetic intelligence part, and machine studying with C++ covers operating skilled fashions exterior Python.

Supply Code and Assessments

Python k-nearest neighbors build status
C++ k-nearest neighbors build status

The Python applications are within the machine-learning/k-nearest-neighbors listing of the MYCPLUS Python examples repository, and the C++ model is within the similar listing of the C++ examples repository.

Construct and take a look at the Python model:

python -m pip set up -r requirements-dev.txt
python -m unittest uncover -s checks -v
sh run_all.sh

Construct and take a look at the C++ model:

cmake -S . -B construct
cmake --build construct --config Launch
ctest --test-dir construct -C Launch --output-on-failure

What the builds test. The Python construct runs on Linux and Home windows with Python 3.13, 3.14 and three.15 and the pinned NumPy, SciPy and scikit-learn variations: ruff and mypy --strict, the 20 unit checks, actual output of the labored instance, the wine experiment and the shared wine report, each remaining experiments and, on Linux, the 16 deliberate bugs. The C++ construct runs GCC and Clang with C++17 and C++20 and -Wall -Wextra -pedantic -Werror, the identical checks below AddressSanitizer and UndefinedBehaviorSanitizer, MSVC with /W4 /WX /permissive- on Home windows, and on Linux the 14 deliberate errors. CTest checks that the C++ wine report matches the Python one byte for byte and that the benchmark’s checksum matches Python’s. The timings themselves will not be checked in CI.

What I Verified

Verify Ubuntu 24.04 Home windows 11
Python setting Python 3.15.2, NumPy 2.5.5, scikit-learn 1.9.1, SciPy 1.18.1; each Python output on this web page captured from these runs Home windows 11 (construct 26300), Python 3.14.6, NumPy 2.5.5, scikit-learn 1.9.1, SciPy 1.18.1
Identical applications on Python 3.13.18 Similar output for the labored instance, the wine experiment, the shared report and the dimensionality experiment Not relevant
20 Python unit checks, ruff, mypy --strict Move, no points Move, no points
Precise output of the labored instance, wine experiment and shared report Matches this web page Matches this web page
16 deliberate Python bugs All 16 caught All 16 caught
C++ construct and CTest GCC 13.3 and Clang 18.1, C++17 and C++20, warnings as errors: cross MSVC (cl.exe 14.44.35229), /W4 /WX /permissive-: construct and CTest cross
C++ report equivalent to Python’s Byte for byte Byte for byte (CTest)
AddressSanitizer, UBSan, Valgrind Clear (GCC) Not relevant
14 deliberate C++ errors All 14 caught Not relevant
Benchmark Identical 1,000 predictions in all 5 implementations; timings as proven Identical checksum; Intel Core i7-8700K: pure Python 14,640 µs, NumPy 2,005, MSVC C++ 282, scikit-learn brute drive 73.5, k-d tree 43.3

Not coated: macOS, ARM processors, different library variations, multi-threaded timings and knowledge units apart from the 2 used right here.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments