K-Nearest Neighbors (KNN): How It Works, With Python and C++

Build k-nearest neighbors in Python and C++, see why one unscaled feature ruins it, choose k honestly and compare five implementations for speed.

Wines from three cultivars plotted on two chemical measurements, with one query wine joined to its 11 nearest neighbors inside a dashed circle.

In cross-validation on the wine dataset, k-nearest neighbors with k = 27 classified 70.9% of wines correctly using the raw measurements and 97.6% after standardizing them. Nothing about the algorithm changed. Before scaling, a single measurement, proline, whose values run from 278 to 1,680, supplied 99.7% of every squared distance between wines, so the other 12 chemical measurements hardly counted.

This tutorial explains KNN from the distance formula to the vote, builds it from scratch in NumPy and again in C++17, checks both against scikit-learn and against each other and measures what matters in practice: feature scaling, the choice of k, the distance metric, the curse of dimensionality and the speed of five implementations on the same data. Every Python program was run for this article with Python 3.15.2, NumPy 2.5.5 and scikit-learn 1.9.1 on Ubuntu 24.04, and the output was identical on Python 3.13 and on Windows 11 with Python 3.14; the C++ was built with GCC 13.3, Clang 18.1 and MSVC with warnings as errors. Every output block on this page is captured from the companion repositories.

What Is K-Nearest Neighbors?

K-nearest neighbors (KNN) is a supervised learning algorithm that classifies a new example by finding the k training examples closest to it and taking a majority vote of their labels. It has no training phase beyond storing the data: all the work happens at prediction time, when it measures the distance from the query to every stored example.

KNN is called a lazy or instance-based learner for that reason. It makes no assumption about the shape of the boundary between classes, so it can follow any curve, but it depends entirely on the distance it is given: if the features are on different scales, or many of them are irrelevant, the “nearest” neighbors are not the most similar ones. The same idea works for regression (average the neighbors’ values instead of voting), but this article covers classification. In Python, the standard implementation is scikit-learn’s KNeighborsClassifier, which this article rebuilds by hand and then uses as a reference.

When to Use KNN (and When Not To)

SituationGood fit?Why
A few thousand to a few hundred thousand rows, tens of featuresYesBrute-force search is fast enough and there is nothing to tune but k and the distance
The class boundary is irregularYesKNN follows the data locally instead of fitting a line or a plane
New labelled data arrives all the timeYes“Training” is appending rows; no model has to be refitted
You need a quick, honest baselineYesOne parameter and no training; you can explain a result by showing the neighbors
Features on very different scalesOnly after scalingWithout it, the largest-valued feature decides every distance (measured below)
Hundreds of features, many of them irrelevantRarelyDistances lose contrast and noise features swamp the useful ones (measured below)
Millions of rows with tight latency limitsWith an indexUse a k-d tree, a ball tree or an approximate nearest neighbor index instead of brute force
You need probabilities you can trustWith careVote shares come in steps of 1/k and are not calibrated

How KNN Works

  1. Store the training data. Fitting a KNN model only keeps the feature rows and their labels.
  2. Scale the features. Bring every feature to a comparable range, using statistics from the training rows only.
  3. Measure the distance from the query to every training row, usually Euclidean or Manhattan.
  4. Pick the k nearest rows. Sort by distance and keep the first k, with a fixed rule for equal distances.
  5. Vote. The most common label among the k neighbors wins, optionally with closer neighbors counting more.
  6. Break ties deterministically. With an even k or more than two classes, votes can tie; decide the rule in advance.

In pseudocode:

fit(X, y):    store X and y

predict(q):
    for each training row i:  d[i] = distance(q, X[i])
    nearest = the k indices with the smallest d   # equal distances: lower index first
    votes   = count of each label among y[nearest]
    return the label with the most votes          # tied vote: the smallest label

The Math Behind KNN

Distance

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

The Manhattan (city-block) distance adds the absolute differences instead:

Both are special cases of the Minkowski distance with p = 2 and p = 1; scikit-learn’s default is Minkowski with p = 2, which is Euclidean. Manhattan is less dominated by a single large difference, because differences are not squared.

The vote

With Nk(x) the set of the k training rows nearest to x, the prediction is the class with the largest total weight among them:

where [yi = c] is 1 when neighbor i has class c and 0 otherwise. With uniform weights every neighbor counts once; with distance weights a neighbor counts 1/d, so closer neighbors matter more. A neighbor at distance 0 (an exact duplicate of the query) would get an infinite weight; the rule used here and in scikit-learn is that such neighbors take the whole vote.

Scaling

Standardization rescales every feature j to mean 0 and standard deviation 1:

where μj and σj are the mean and standard deviation of feature j computed on the training rows only. After standardization, every feature contributes the same average squared difference between rows, so no feature dominates the distance just because of its units.

Choosing k

k controls how local the decision is. With k = 1 the prediction copies the single nearest row, so it follows every noisy point in the training data (low bias, high variance). A large k averages over a wide neighborhood and smooths the boundary, until at k = n it predicts the majority class everywhere (high bias, low variance). Odd values avoid two-way ties between two classes. The right k depends on the data and is chosen by cross-validation, never on the test set.

A Worked Example by Hand

Seven labelled points, four of class A and three of class B, and one query at (3, 3); a small, made-up example chosen so that the answer changes with k:

Point(2, 4)(0, 4)(5, 4)(0, 1)(3, 6)(2, 3)(5, 5)
ClassAAAABBB

The squared distances are small integers. For (2, 4): (2 − 3)² + (4 − 3)² = 2, so the distance is √2 = 1.414. The nearest point is (2, 3) at squared distance 1, and it is class B, so with k = 1 the prediction is B. The next two are (2, 4) and (5, 4), both class A, so with k = 3 the vote is 2 to 1 for A. The fourth and fifth are both B, so with k = 5 the vote is 3 to 2 for B.

The program below repeats the calculation with the from-scratch classifier:

"""The article's worked example: seven labelled points, one query, four values of k."""

import numpy as np

from knn import KNNClassifier

points = 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"])
query = np.array([[3.0, 3.0]])

model = KNNClassifier(k=7).fit(points, labels)
dist, idx = model.kneighbors(query)
print("query (3, 3); training points sorted by distance:")
print("rank  point   class  squared  distance")
for rank, (i, d) in enumerate(zip(idx[0], dist[0], strict=True), start=1):
    x, y = points[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 k  votes A  votes B  prediction")
for k in (1, 3, 5, 7):
    near = labels[idx[0, :k]]
    a, b = int((near == "A").sum()), int((near == "B").sum())
    pred = KNNClassifier(k=k).fit(points, labels).predict(query)[0]
    print(f"{k:2}  {a:7}  {b:7}  {pred:>10}")

Output:

query (3, 3); training points sorted by distance:
rank  point   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

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

The prediction flips three times as k grows from 1 to 7. Nothing is wrong with the algorithm: near the boundary between two classes, the answer genuinely depends on how far you look. That is why k has to be chosen with data, as the next sections do.

−1 0 1 2 3 4 5 6 7 feature 1 0 1 2 3 4 5 6 7 feature 2 1 2 3 4 5 6 7 The same query, a different answer for each k k = 1 or 5: B wins k = 3: A wins class A class B query (3, 3)
Figure 1: The worked example. Numbers give each point’s rank by distance from the query. The dashed circles hold the 1, 3 and 5 nearest points, and the vote inside each one flips the prediction.

KNN in Python From Scratch

The classifier lives in knn.py and needs only NumPy. The distances are computed for 256 query rows at a time, so that the temporary array of differences stays a manageable size, and nearest sorts each row with a stable sort, so that equal distances keep the lower training index first:

def pairwise_distances(
    A: FloatArray, B: FloatArray, metric: Metric = "euclidean"
) -> FloatArray:
    """Distance from every row of A to every row of B, shape (len(A), len(B))."""
    out = np.empty((A.shape[0], B.shape[0]))
    for start in range(0, A.shape[0], 256):  # 256 query 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, k: int) -> IntArray:
    """Indices of the k smallest distances in each row; ties go to the lower index."""
    order = np.argsort(distances, axis=1, kind="stable")
    return order[:, :k].astype(np.int64)

The vote adds each neighbor’s weight to its class and divides by the total, which gives the class shares that predict_proba returns:

def vote(
    labels: IntArray, distances: FloatArray, n_classes: int, weights: Weights
) -> FloatArray:
    """Each 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
        exact = distances == 0.0  # a neighbor at distance 0 takes the whole vote
        has_exact = exact.any(axis=1)
        w[has_exact] = exact[has_exact].astype(np.float64)
    shares = np.zeros((labels.shape[0], n_classes))
    np.add.at(shares, (np.arange(labels.shape[0])[:, None], labels), w)
    total: FloatArray = shares / shares.sum(axis=1, keepdims=True)
    return total

fit only validates and stores the data; predict takes the class with the largest share. np.argmax returns the first maximum, so a tied vote goes to the smallest label, which is also 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 first maximum: a tied vote goes to the smallest label
        winners = np.argmax(self.predict_proba(X), axis=1)
        result: NDArray[np.generic] = self.classes_[winners]
        return result

Standardization uses the training rows’ mean and population standard deviation, the same as scikit-learn’s StandardScaler, and applies them unchanged to the test rows:

def standardize(
    X_train: FloatArray, X_test: FloatArray
) -> tuple[FloatArray, FloatArray]:
    """Scale every feature to mean 0 and standard deviation 1 on the training rows."""
    mean = X_train.mean(axis=0)
    std = X_train.std(axis=0)  # population standard deviation, as StandardScaler
    return (X_train - mean) / std, (X_test - mean) / std

The repository’s 20 tests check the distances against SciPy, the worked example, both tie rules, distance-weighted votes including the zero-distance case, that neighbors come back sorted even for large k, identical predictions, probabilities, neighbor indices and distances to scikit-learn on the wine data for 20 combinations of k, metric and weights, standardization from the training rows only and input validation. A separate script re-applies 16 plausible bugs to a copy of the code, from a missing square root to labels assumed to be 0, 1, 2; every one makes a test fail.

KNN on a Real Dataset: Why Feature Scaling Matters

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

PropertyValue
SourceAeberhard and Forina (1992), UCI Machine Learning Repository, doi:10.24432/C5PC7J; bundled with scikit-learn
LicenseCC BY 4.0
Rows and features178 wines, 13 numeric chemical measurements
Classes3 cultivars: 59, 71 and 48 wines
Split75/25, stratified, random_state=42: 133 training rows, 45 test rows
Model selection5-fold cross-validation repeated 10 times on the training rows, scaler refitted inside every fold

The experiment estimates the accuracy of every odd k from 1 to 31 by repeated cross-validation, once with the raw features and once standardized, with the scaler fitted inside each fold so that the validation rows never influence it:

def cv_curve(scale: bool, metric: Metric, weights: Weights) -> FloatArray:
    """Mean accuracy for every k in KS over 5-fold CV repeated 10 times."""
    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, k in enumerate(KS):
            model = KNNClassifier(k=k, metric=metric, weights=weights)
            pred = model.fit(A, y_train[fit_idx]).predict(B)
            scores[i] += (pred == y_train[val_idx]).mean()
    result: FloatArray = scores / len(FOLDS)
    return result

It then picks the best k for four variants on the training rows, applies each to the 45 test rows once and finally 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 training rows (5 folds x 10 repeats)
  k  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

best k for each variant (the smallest k among equal scores)
unscaled, euclidean                          k=1   0.741
standardized, euclidean                      k=27  0.976
standardized, manhattan                      k=7   0.985
standardized, euclidean, distance-weighted   k=29  0.976

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

same test predictions as scikit-learn: 64 of 64 settings
1 5 9 13 17 21 25 29 k (number 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) best k = 27 proline supplies 99.7% of every squared distance Scaling the features matters more than choosing k standardized features unscaled features
Figure 2: Cross-validated accuracy on the 133 training wines for every odd k from 1 to 31. Standardizing the 13 features lifts every k from about 0.68 to 0.74 to about 0.95 to 0.98. The best k, 27, is chosen here, before the test rows are used.

Reading the results:

  • Scaling is worth more than everything else combined. No value of k gets the unscaled model above 0.741 in cross-validation; every value of k gets the standardized model above 0.95. On the test rows, scikit-learn’s defaults on raw features (k = 5, no scaling) classified 35 of 45 wines correctly; the standardized model chosen by cross-validation got 43.
  • The reason is one feature. Proline is measured in the hundreds to thousands, so its differences dwarf everyone else’s: it supplies 99.7% of the squared distance between training rows. After standardization each of the 13 features supplies 1/13, or 7.7%.
  • k matters much less once the features are scaled. The standardized curve stays between 0.952 and 0.976 for every k from 1 to 31. Cross-validation picked k = 27, but anything from about 7 up would do nearly as well.
  • Manhattan distance did best here. With k = 7 it reached 0.985 in cross-validation and 44 of 45 on the test rows. That is a property of this dataset, not a general rule; it is the kind of choice to make by cross-validation, not by habit.
  • The from-scratch model matches scikit-learn exactly. It made the same 45 test predictions in all 64 combinations of k, metric and weighting.

A test set of 45 rows is small: one wine is 2.2 percentage points. The cross-validated numbers, averaged over 50 fits, are the more reliable comparison; the test rows confirm them once.

Choosing k Without Fooling Yourself

KNN makes two evaluation mistakes unusually easy. The pitfall program shows both on the same data:

k=1, unscaled     accuracy on its own training rows: 1.000
k=1, standardized accuracy on its own training rows: 1.000

standardized, test-set score for every odd k 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
best k chosen on the test rows: k=15, 45/45
k=27 chosen by cross-validation on the training rows: 43/45

Scored on its own training rows, a 1-nearest-neighbor model is always 100% correct, scaled or not, because every row is its own nearest neighbor at distance 0. That number measures nothing.

Choosing k by its score on the test rows is subtler. Trying 16 values of k and keeping the best one found k = 15 with 45 of 45 correct, but that perfect score is partly luck: with 45 rows, several k values land on 44 or 45 by chance, and picking the maximum picks the luckiest. The honest procedure, choosing k = 27 by cross-validation on the training rows and then scoring it once, reports 43 of 45. That is the number to expect on new wines.

The Curse of Dimensionality

KNN assumes that “near” means “similar”. As the number of features grows, that assumption weakens in two measurable ways:

uniform random points: 1,000 reference points, 100 queries
 dims  nearest  farthest  (far - near) / near
    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, k=27: cross-validated accuracy with noise columns added
(mean over 5 different draws 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 data) 1 0 − 1 1 0 0 1 0 1 1 0 2 (farthest – nearest) / nearest Distances lose their contrast 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, k = 27) Irrelevant features drown the signal The curse of dimensionality, measured
Figure 3: Left, 100 random queries against 1,000 random points: the farthest point is about 90 times farther than the nearest in 2 dimensions and only 12% farther in 1,000. Right, cross-validated accuracy on the standardized wine data as columns of pure noise are added (mean of 5 noise draws).

Distances lose contrast. With 1,000 random points in 2 dimensions, the farthest point is on average about 90 times farther from a query than the nearest one. In 1,000 dimensions the farthest is only 12% farther than the nearest. When every point is roughly the same distance away, “the k nearest” is close to an arbitrary choice.

Irrelevant features drown the signal. Appending columns of pure random noise to the 13 standardized wine features lowered cross-validated accuracy from 0.976 to 0.940 with 20 noise columns, 0.844 with 100 and 0.650 with 500. Every noise column adds the same expected amount to every squared distance, and enough of them bury the differences that the real features provide.

The practical rules: keep features that carry signal, reduce dimensions (for example with principal component analysis) before using KNN on wide data, and do not expect brute-force KNN on raw high-dimensional vectors to work as well as it does on 13 measurements.

KNN in C++

The C++17 version in knn.hpp follows the same rules as the Python one, so the two can be compared output for output. Instead of sorting every distance, it uses std::nth_element to move the k nearest to the front in linear time and then sorts only those k:

// The k training rows nearest to query, nearest first.
inline std::vector<Neighbor> nearest(const Dataset& train, const double* query, std::size_t k,
                                     Metric metric = Metric::euclidean)
{
    if (k == 0 || k > train.rows)
        throw std::invalid_argument("k must be between 1 and the number of training rows");
    std::vector<Neighbor> all(train.rows);
    for (std::size_t r = 0; r < train.rows; ++r)
        all[r] = {distance(query, train.row(r), train.cols, metric), r};
    const auto closer = [](const Neighbor& a, const Neighbor& b) {
        return a.distance < b.distance || (a.distance == b.distance && a.index < b.index);
    };
    // nth_element puts the k nearest first in O(n); only those k are sorted.
    const auto kth = all.begin() + static_cast<std::ptrdiff_t>(k);
    std::nth_element(all.begin(), kth - 1, all.end(), closer);
    std::sort(all.begin(), kth, closer);
    all.resize(k);
    return all;
}

// Majority vote of the k nearest; a tie goes to the smallest label.
inline int predict_one(const Dataset& train, const double* query, std::size_t k,
                       Metric metric = Metric::euclidean)
{
    const std::vector<Neighbor> nbrs = nearest(train, query, k, metric);
    std::vector<std::pair<int, int>> votes;  // (label, count), sorted by label
    for (const Neighbor& n : nbrs) {
        const int label = train.labels[n.index];
        auto it = std::lower_bound(votes.begin(), votes.end(), std::make_pair(label, 0),
                                   [](const auto& a, const auto& b) { return a.first < b.first; });
        if (it == votes.end() || it->first != label)
            it = votes.insert(it, {label, 0});
        ++it->second;
    }
    std::pair<int, int> best = votes.front();
    for (const auto& v : votes)
        if (v.second > best.second)  // strictly more: the smaller label keeps a tie
            best = v;
    return best.first;
}

The comparison function orders by distance and then by training-row index, which gives every pair of neighbors a strict order. The result is therefore the same whichever standard library implements nth_element and sort. The vote keeps the first label with the most votes, and since the labels are kept in increasing order, a tie goes to the smallest label, as in the Python version and in scikit-learn. The C++ Standard Template Library guide covers nth_element and the other selection algorithms.

The two versions are checked against each other. The C++ program reads the same wine_split.csv that the Python one reads, standardizes it the same way and prints the same report; both repositories compare that report with the same expected file, so a change in either language that alters a single prediction or the sixth decimal of a distance fails the build:

wine: 133 training rows, 45 test rows, 13 features
share of squared distance from proline, unscaled: 99.7%
share of squared distance from proline, standardized: 7.7%

correct test predictions (of 45)
 k  metric     unscaled  standardized
 1  euclidean        33            43
 5  euclidean        35            42
27  euclidean        35            43
 7  manhattan        38            44

nearest training rows to test 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++ tests also check the worked example, both tie rules, nearest against a full stable sort on random data with many equal distances, standardization, error messages for malformed CSV files, Windows line endings and a splitmix64 random-number stream that both languages generate bit for bit. They pass under AddressSanitizer, UndefinedBehaviorSanitizer and Valgrind, and a script that puts 14 deliberate mistakes into a copy of the header confirms that each one is caught.

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

Brute-force KNN costs one distance per training row per query, so its speed depends almost entirely on how that inner loop is executed. The benchmark generates 20,000 training rows and 1,000 queries with 8 features from the shared splitmix64 stream, and every implementation must produce the same 1,000 predictions (checksum 502492) before any time is compared. Everything runs on one thread.

The Python side times pure Python, this article’s NumPy classifier and scikit-learn:

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

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

The C++ program, built with GCC 13.3 in Release mode (-O3, CMake’s default), on the same machine:

20000 training rows, 1000 queries, 8 features, k=5
checksum of predictions: 502492; accuracy 0.889
microseconds per query (median of 5 runs): 278.4
1 0 1 1 0 2 1 0 3 1 0 4 1 0 5 microseconds per query (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 Same data, same 1,000 predictions, five implementations
Figure 4: Median time per query to classify 1,000 queries against 20,000 training rows with 8 features and k = 5, on one thread of one Linux virtual machine. All five make identical predictions.

What the numbers show:

  • NumPy from scratch is about 5 times faster than pure Python, and the plain C++ loop is about 11 times faster than that. The NumPy version builds a 256 × 20,000 × 8 array of differences for every block of queries and fully sorts 20,000 distances per query; the C++ version computes each distance in registers and selects the k nearest without a full sort.
  • scikit-learn’s brute-force search beat the straightforward C++ by about 4 times. Its Euclidean path computes distances in blocks with matrix multiplication for the cross term and keeps only the k best candidates per query in a small heap. Compiled code is not automatically fast; the algorithm and the memory access pattern decide.
  • The k-d tree was faster still at 8 features, because it skips most training rows without computing their distances. Tree indexes lose that advantage as the number of features grows, for the reasons shown in the previous section.

These are medians of repeated runs on one Linux virtual machine (Intel Xeon at 2.10 GHz, 2 vCPUs), and they moved between runs: across six runs of the Python benchmark and five of the C++ one, pure Python ranged from about 14,000 to 23,000 microseconds per query, NumPy from 3,000 to 3,460, C++ from 269 to 292, scikit-learn brute force from 64 to 76 and the k-d tree from 39 to 60. The order of the five never changed; the absolute numbers belong to this machine. On the Windows 11 desktop used for the Windows checks (Intel Core i7-8700K at 3.70 GHz), the same programs gave pure Python 14,640, NumPy 2,005, C++ built with MSVC 282, scikit-learn brute force 73.5 and the k-d tree 43.3 microseconds per query: the same order, with the same checksum. The benchmark measures prediction on in-memory data only. It does not measure multi-threading, larger k, other dimensions, approximate indexes or the time to build the k-d tree.

Complexity and Scaling

MethodBuildPer queryUse when
Brute force (this article)O(1): store the rowsO(n m) distances plus O(n) selectionUp to hundreds of thousands of rows; any number of features
k-d treeO(n log n)About O(log n) in low dimensions, near O(n) in highFew features (roughly up to 20), many queries
Ball treeO(n log n)Better than a k-d tree on many features or non-Euclidean metricsModerate dimensions, other metrics
Approximate index (for example HNSW graphs)Large, built onceSub-linear, may miss some true neighborsMillions of high-dimensional vectors, such as embeddings

Here n is the number of training rows and m the number of features. Memory is O(n m) in every case: KNN keeps the whole training set. For the selection step, nth_element (average linear time) is cheaper than a full O(n log n) sort, which is one reason the C++ version beats the NumPy one; the sorting algorithms article measures the cost of full sorts. The k-d tree is a binary search tree that splits on one feature per level, the same structure as the binary trees it is built from.

Common Mistakes With KNN

1. Not scaling the features. On the wine data, raw features gave 35 of 45 correct with scikit-learn’s defaults and standardized features gave 43, because proline alone supplied 99.7% of every squared distance. Scale every feature, and fit the scaler on the training rows only.

2. Fitting the scaler on all the data. Statistics computed on the test rows leak information into the model. Compute the mean and standard deviation on the training rows (inside each cross-validation fold) and reuse them for everything else, as standardize and cv_curve do above.

3. Reporting training accuracy. With k = 1, accuracy on the training rows is 100% on any data, because every row finds itself.

4. Choosing k on the test set. It turned a 43/45 model into a reported 45/45. Choose k by cross-validation on the training rows and score the test rows once.

5. Adding every available feature. 100 noise columns took cross-validated accuracy from 0.976 to 0.844. Irrelevant features do not just fail to help KNN; they actively push the useful ones out of the distance.

ModelTrainingDecision boundaryKey difference from KNN
K-nearest neighborsNone: stores the dataAny shape, follows the data locallyPrediction cost grows with the training set
Logistic regressionFits one weight per featureStraight (a hyperplane)Compact model, fast prediction, calibrated probabilities
Decision treeLearns threshold splitsAxis-aligned stepsInsensitive to feature scale; prediction cost depends on depth, not data size
Naive BayesEstimates per-class feature distributionsStraight or curvedGenerative; fast on very wide data such as text
Support vector machineFinds the maximum-margin boundaryStraight, or curved with a kernelAlso distance-based with a kernel, but keeps only the support vectors

For a linear baseline on the same kind of problem, see logistic regression from scratch, which this series builds the same way.

Key Takeaways

  • KNN classifies by a majority vote of the k closest training examples; it stores the data and does all of its work at prediction time.
  • Scale the features before anything else. On the wine data, standardizing took cross-validated accuracy from at most 0.741 to at least 0.952, for every k.
  • Choose k, the distance and the weighting by cross-validation on the training rows, never by the test score; picking k on the test set reported 45/45 for a model that scores 43/45 honestly.
  • More features can make KNN worse. 100 columns of noise cut accuracy from 0.976 to 0.844, and in 1,000 random dimensions the farthest point was only 12% farther than the nearest.
  • Fix the tie rules (equal distances, tied votes) so that results are reproducible across runs, languages and compilers.
  • Speed depends on the implementation more than the language: on the same data, a plain C++ loop was about 50 times faster than pure Python, and scikit-learn’s brute force was about 4 times faster than the plain C++.

Conclusion

K-nearest neighbors is the simplest classifier that works: store the examples, measure distances, let the nearest ones vote. Its simplicity puts all the weight on the distance, which is why the most important line in a KNN program is usually not in the classifier at all but in the preprocessing. On the wine data, scaling the features mattered more than any choice of k, metric or weighting, and 100 irrelevant features undid most of the benefit.

The same questions carry over to every distance-based method that follows, from k-means clustering to the vector search behind modern embedding systems: what does “near” mean for these features, and does it still mean anything in this many dimensions? More tutorials in this series are collected in the artificial intelligence section, and machine learning with C++ covers running trained models outside Python.

Source Code and Tests

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

The Python programs are in the machine-learning/k-nearest-neighbors directory of the MYCPLUS Python examples repository, and the C++ version is in the same directory of the C++ examples repository.

Build and test the Python version:

python -m pip install -r requirements-dev.txt
python -m unittest discover -s tests -v
sh run_all.sh

Build and test the C++ version:

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

What the builds check. The Python build runs on Linux and Windows with Python 3.13, 3.14 and 3.15 and the pinned NumPy, SciPy and scikit-learn versions: ruff and mypy --strict, the 20 unit tests, exact output of the worked example, the wine experiment and the shared wine report, both remaining experiments and, on Linux, the 16 deliberate bugs. The C++ build runs GCC and Clang with C++17 and C++20 and -Wall -Wextra -pedantic -Werror, the same tests under AddressSanitizer and UndefinedBehaviorSanitizer, MSVC with /W4 /WX /permissive- on Windows, and on Linux the 14 deliberate mistakes. 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 are not checked in CI.

What I Verified

CheckUbuntu 24.04Windows 11
Python environmentPython 3.15.2, NumPy 2.5.5, scikit-learn 1.9.1, SciPy 1.18.1; every Python output on this page captured from these runsWindows 11 (build 26300), Python 3.14.6, NumPy 2.5.5, scikit-learn 1.9.1, SciPy 1.18.1
Same programs on Python 3.13.18Identical output for the worked example, the wine experiment, the shared report and the dimensionality experimentNot applicable
20 Python unit tests, ruff, mypy --strictPass, no issuesPass, no issues
Exact output of the worked example, wine experiment and shared reportMatches this pageMatches this page
16 deliberate Python bugsAll 16 caughtAll 16 caught
C++ build and CTestGCC 13.3 and Clang 18.1, C++17 and C++20, warnings as errors: passMSVC (cl.exe 14.44.35229), /W4 /WX /permissive-: build and CTest pass
C++ report identical to Python’sByte for byteByte for byte (CTest)
AddressSanitizer, UBSan, ValgrindClean (GCC)Not applicable
14 deliberate C++ mistakesAll 14 caughtNot applicable
BenchmarkSame 1,000 predictions in all five implementations; timings as shownSame checksum; Intel Core i7-8700K: pure Python 14,640 µs, NumPy 2,005, MSVC C++ 282, scikit-learn brute force 73.5, k-d tree 43.3

Not covered: macOS, ARM processors, other library versions, multi-threaded timings and data sets other than the two used here.

Scroll to Top