k-nearest neighbors in Python takes about four lines with scikit-learn, but three details decide whether it works: feature scaling, the choice of k, and the number of useless columns in your data. This tutorial tests each one on the wine dataset that ships with scikit-learn (178 wines, 13 chemical measurements, 3 grape varieties) and reports what actually happened.
Versions: scikit-learn 1.9.1 and pandas 3.0.5. We hold out 25% of the data (133 training rows and 45 test rows, stratified) and use 5-fold stratified cross-validation inside the training set. For the splitting basics see train test split in Python.
How k-NN works
To classify a wine, k-NN finds the k training wines closest to it and takes a majority vote. There is no training step beyond storing the data, so all the work happens at prediction time. “Closest” means a distance computed across all features, which is where the problems start.
Baseline and the unscaled model
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.dummy import DummyClassifier
X, y = load_wine(return_X_y=True, as_frame=True)
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
print("dummy", round(DummyClassifier().fit(Xtr, ytr).score(Xte, yte), 3))
print("raw k=5", round(KNeighborsClassifier(5).fit(Xtr, ytr).score(Xte, yte), 3))
sc = make_pipeline(StandardScaler(), KNeighborsClassifier(5)).fit(Xtr, ytr)
print("scaled k=5", round(sc.score(Xte, yte), 3))Output:
dummy 0.4
raw k=5 0.667
scaled k=5 0.933Guessing the majority class scores 0.40. Plain k-NN reaches 0.667, but the same model with one extra line of scaling reaches 0.933. The reason is in the units: proline ranges from 278 to 1,680, while hue ranges from 0.48 to 1.71. In the raw distance, proline alone accounts for about 98% of the squared distance between a training wine and the others (0.979 on average), so the other twelve features barely vote.
Choosing k with cross-validation
from sklearn.model_selection import cross_val_score, StratifiedKFold
cv = StratifiedKFold(5, shuffle=True, random_state=0)
for k in range(1, 31, 2):
s = cross_val_score(make_pipeline(StandardScaler(), KNeighborsClassifier(k)), Xtr, ytr, cv=cv).mean()
print(k, round(s, 3))Output:
1 0.918
3 0.933
5 0.955
7 0.955
9 0.955
11 0.955
13 0.947
15 0.955
17 0.947
19 0.948
21 0.948
23 0.955
25 0.962
27 0.970
29 0.955Accuracy is 0.918 at k=1, which memorises noise, and then sits on a plateau of 0.947 to 0.970 for every k from 5 to 29. The best value is k=27 (0.970), and the final model scored 0.978 on the 45 held-out wines, but with only 133 training rows the gap between k=5 and k=27 is about two rows, well inside the noise. The practical advice: pick any k on the plateau, and prefer an odd number to avoid ties. The unscaled model never exceeded 0.758 at any k, so scaling mattered far more than k.
Weights and distance metric
At k=27, uniform voting gave 0.970 and distance weighting gave 0.962. Euclidean distance gave 0.970 and Manhattan gave 0.948. On this small dataset the defaults were as good as anything else, and we would not read much into differences of one or two rows.
What happens when you add useless columns
k-NN has no way to ignore a bad feature. To test this we appended columns of pure random noise to the 13 real features and re-ran cross-validation with k=27:
rng = np.random.default_rng(0)
for nn in [0, 10, 50, 200, 500]:
N = pd.DataFrame(rng.normal(size=(len(Xtr), nn)))
XX = pd.concat([Xtr.reset_index(drop=True), N], axis=1); XX.columns = XX.columns.astype(str)
s = cross_val_score(make_pipeline(StandardScaler(), KNeighborsClassifier(27)), XX, ytr.values, cv=cv).mean()
print(nn, round(s, 3))Output:
0 0.97
10 0.962
50 0.948
200 0.73
500 0.715
This is the curse of dimensionality in practice: with 200 noise columns against 13 real ones, the noise dominates the distances and accuracy falls from 0.970 to 0.730. Drop irrelevant features before using k-NN, or choose a model that selects features itself, such as the ones in our feature engineering tests.
Leakage and speed
Scaling the whole training set before cross-validation is a form of leakage, because each fold’s scaler sees the validation rows. Here it made no visible difference (0.970 both ways), but the habit matters; put the scaler in a pipeline, as above. On speed, we timed 1,000 predictions against a synthetic 200,000-row, 13-feature training set: the default automatic algorithm took 3.23 seconds and algorithm="brute" took 0.34 seconds, so on this machine and this dimensionality the tree index was slower than brute force. Time your own case before assuming a tree helps. Because every prediction scans the stored data, k-NN gets slow on large training sets compared with a fitted model such as logistic regression (see logistic regression in Python).
Summary
Scale first, choose k from a plateau rather than a peak, remove noisy features, and keep everything inside a pipeline. The official reference is the scikit-learn nearest neighbors guide. Cross-validation details are in cross-validation in Python.
Frequently asked questions
Does k-nearest neighbors need feature scaling?
Yes. On the wine data, scaling raised test accuracy from 0.667 to 0.933 because one large-unit feature dominated the distance.
How do I choose k?
Cross-validate several odd values and pick one on the plateau. In our run anything from 5 to 29 scored between 0.947 and 0.970.
Is k-NN good for high-dimensional data?
Usually not. Adding 200 noise columns cut cross-validated accuracy from 0.970 to 0.730.
Can k-NN do regression?
Yes, KNeighborsRegressor averages the neighbours’ target values; the same scaling advice applies.
