Pulse Data Hub

K-Nearest Neighbors in Python: Scaling, K and Noise, Tested

K-nearest neighbors in Python is the simplest classifier to understand: to label a new point, look at the k closest labelled points and take a vote. It is also easy to break, and this tutorial shows exactly how, using the 178-wine data set that ships with scikit-learn. We measure what scaling does (it changes accuracy from 69.9% to 96.2%), how the choice of k matters, what happens when you add useless columns, and how much a grid search flatters its own result. Everything ran on 23 November 2026 with Python 3.13 and scikit-learn 1.9.1.

The data: 178 wines, 13 chemical measurements

The wine data set has three grape varieties (59, 71 and 48 wines) described by 13 numeric measurements such as alcohol, magnesium and proline. Always predicting the biggest class is right 39.9% of the time. The feature ranges differ enormously: proline spans 1,402 units, magnesium 92 and hue only 1.2. That matters, because k-nearest neighbors measures distance, and a column with big numbers dominates it.

import numpy as np, pandas as pd
from sklearn.datasets import load_wine
from sklearn.model_selection import RepeatedStratifiedKFold, cross_val_score, GridSearchCV
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_wine(return_X_y=True, as_frame=True)
print(X.shape, y.value_counts().sort_index().to_dict())
print("feature ranges:", {c: round(float(X[c].max() - X[c].min()), 1) for c in ["proline", "magnesium", "hue"]})
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=5, random_state=0)
def acc(model, X=X):
    s = cross_val_score(model, X, y, cv=cv); return round(s.mean(), 3), round(s.std(), 3)
print("majority", round(y.value_counts(normalize=True).max(), 3))
(178, 13) {0: 59, 1: 71, 2: 48}
feature ranges: {'proline': 1402.0, 'magnesium': 92.0, 'hue': 1.2}
majority 0.399

Why K-nearest neighbors in Python needs scaling

Run the same model with and without a StandardScaler in front of it. Both use k = 5 and the same 25 cross-validation folds.

print("k=5 unscaled", acc(KNeighborsClassifier(5)))
print("k=5 scaled  ", acc(make_pipeline(StandardScaler(), KNeighborsClassifier(5))))
k=5 unscaled (0.699, 0.053)
k=5 scaled   (0.962, 0.018)

Scaling lifts accuracy from 69.9% to 96.2%, a gain of 26 points from one line. Without it, distances are mostly about proline, and the other 12 columns hardly count. Putting the scaler inside a pipeline matters too: it is fitted on each training fold only, so nothing leaks from the test fold.

Bar chart of KNN accuracy: unscaled 69.9%, scaled 96.2%, with 50 noise columns 90.3%, with 200 noise columns 75.9%

Choosing k

A small k follows every quirk of the training data (high variance); a large k averages over so many neighbors that it ignores local structure (high bias). We scored nine values of k.

res = {}
for k in (1, 3, 5, 7, 11, 15, 25, 45, 101):
    res[k] = acc(make_pipeline(StandardScaler(), KNeighborsClassifier(k)))[0]
print("k curve", res)
print("weights distance, k=11", acc(make_pipeline(StandardScaler(), KNeighborsClassifier(11, weights="distance"))))
k curve {1: 0.954, 3: 0.963, 5: 0.962, 7: 0.966, 11: 0.969, 15: 0.969, 25: 0.976, 45: 0.958, 101: 0.757}
weights distance, k=11 (0.969, 0.023)

Accuracy is high and flat from k = 3 to k = 25 (96.3% to 97.6%), then it collapses at k = 101 (75.7%), because with only 178 wines a vote among 101 neighbors always includes the whole other classes. The best single value, k = 25, is only 0.7 points above k = 11, well inside the 2-point fold-to-fold noise. Weighting neighbors by distance gave the same 96.9% at k = 11. Pick an odd k somewhere in the stable range rather than chasing the maximum.

The curse of dimensionality, measured

K-nearest neighbors treats every column as equally important, so useless columns hurt. We appended columns of random numbers to the 13 real ones and scored the scaled model with k = 11.

rng = np.random.default_rng(0)
for n in (0, 10, 50, 200):
    Xn = pd.concat([X, pd.DataFrame(rng.normal(size=(len(X), n)), columns=[f"noise{i}" for i in range(n)])], axis=1) if n else X
    print(n, "noise columns", acc(make_pipeline(StandardScaler(), KNeighborsClassifier(11)), Xn))
0 noise columns (0.969, 0.023)
10 noise columns (0.953, 0.019)
50 noise columns (0.903, 0.031)
200 noise columns (0.759, 0.062)

Ten noise columns cost 1.6 points, fifty cost 6.6 and two hundred cost 21. The real signal is still there, but the random columns swamp the distance. This is why k-nearest neighbors usually needs feature selection or dimensionality reduction first; our PCA guide covers one way.

Tuning with a grid search: how optimistic is the score?

Searching over k, distance weighting and the distance metric (p = 1 is Manhattan, p = 2 Euclidean) is standard practice. But the best score from a grid search is optimistic, because you picked the winner on the same data. Nesting the search inside an outer cross-validation gives an honest estimate.

grid = GridSearchCV(make_pipeline(StandardScaler(), KNeighborsClassifier()),
                    {"kneighborsclassifier__n_neighbors": range(1, 30, 2),
                     "kneighborsclassifier__weights": ["uniform", "distance"],
                     "kneighborsclassifier__p": [1, 2]}, cv=5)
nested = cross_val_score(grid, X, y, cv=RepeatedStratifiedKFold(n_splits=5, n_repeats=2, random_state=1))
grid.fit(X, y)
print("best params", grid.best_params_, "inner CV", round(grid.best_score_, 3), "nested CV", round(nested.mean(), 3))
best params {'kneighborsclassifier__n_neighbors': 11, 'kneighborsclassifier__p': 1, 'kneighborsclassifier__weights': 'uniform'} inner CV 0.978 nested CV 0.963

The grid search reports 97.8% for its best setting, but the nested estimate is 96.3%, 1.5 points lower. That is no better than the untuned scaled model at k = 5 (96.2%). On this data set, tuning bought nothing real, and the headline number would have overstated it. Report the nested score, or a final test set you never touched.

When to use k-nearest neighbors in Python

  • Small, low-dimensional data where distance means something, and you have time to scale and select features.
  • A quick baseline before trying heavier models. It needs no training, but predictions get slow as the data grows, because every prediction searches the whole training set.
  • Not for many noisy columns or millions of rows. A tree-based model such as a random forest handles irrelevant features far better.

For the surrounding workflow of splitting, pipelines and leakage, see our scikit-learn model tutorial, and for an unsupervised use of distances see k-means clustering. The scikit-learn neighbors guide lists the algorithms (KD-tree, ball tree) it uses to speed up the search.

FAQ

What does k mean in k-nearest neighbors?

K is the number of closest training points that vote on a new point’s label. In our wine test, any k from 3 to 25 gave about 96 to 98% accuracy, while k = 101 fell to 75.7%.

Do I need to scale data for KNN?

Yes. KNN uses distances, so large-valued columns dominate. Scaling raised accuracy from 69.9% to 96.2% on the wine data.

Is KNN good for large datasets?

Not usually. It stores all the training data and searches it for every prediction, so it gets slower as data grows, and many irrelevant columns reduce its accuracy (200 noise columns cut it to 75.9% in our test).

How do I choose the best k?

Cross-validate several odd values of k, prefer a value in the stable middle of the range rather than the single best score, and use nested cross-validation if you also tune other settings.

Newsletter Signup Form

Latest tutorials

Latest articles

On this page
Verified by MonsterInsights