K-Nearest Neighbor (KNN) in Python

K nearest neighbor in Python is easiest with scikit-learn’s KNeighborsClassifier: scale the features, fit it on labeled data, and it classifies each new point by a vote among its k closest training points:

from sklearn.neighbors import KNeighborsClassifier
knn = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5)).fit(X_train, y_train)

I tested this with Python 3.12.5 and scikit-learn 1.9.1, using the wine dataset that comes with scikit-learn plus a tiny T-shirt size table for the from-scratch version.

We’ll train a KNN model, choose k with cross-validation, see how much scaling matters, build KNN by hand with NumPy, and plot accuracy against k.

K nearest neighbor in Python with scikit-learn

The wine dataset has 178 wines, 13 chemical measurements each, and three cultivars to predict. I keep 30% for testing:

from sklearn.datasets import load_wine
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1, stratify=y)

knn = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5))
knn.fit(X_train, y_train)
pred = knn.predict(X_test)

print("samples, features:", X.shape)
print(f"test accuracy (k=5): {accuracy_score(y_test, pred):.3f}")
print("confusion matrix:\n", confusion_matrix(y_test, pred))
print("class probabilities for the first test wine:", knn.predict_proba(X_test[:1]).round(2))

Output:

samples, features: (178, 13)
test accuracy (k=5): 0.926
confusion matrix:
 [[18  0  0]
 [ 3 17  1]
 [ 0  0 15]]
class probabilities for the first test wine: [[0. 0. 1.]]
Command Prompt output of a scikit-learn KNeighborsClassifier on the wine dataset with test accuracy, confusion matrix and class probabilities
High accuracy with k = 5, a nearly diagonal confusion matrix, and vote shares as probabilities.

KNN doesn’t really “train”; fit() just stores the data. All the work happens at prediction time, when it measures distances to every stored point.

How do you choose k in KNN?

A small k follows the training data closely and is sensitive to noise; a large k smooths things out. Cross-validation tells you which works best, and here I also compare scaled and unscaled features:

from sklearn.datasets import load_wine
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_wine(return_X_y=True)
print(" k  scaled  unscaled")
for k in [1, 3, 5, 7, 9, 11, 15, 21]:
    scaled = cross_val_score(make_pipeline(StandardScaler(), KNeighborsClassifier(k)), X, y, cv=5).mean()
    raw = cross_val_score(KNeighborsClassifier(k), X, y, cv=5).mean()
    print(f"{k:>2}  {scaled:.3f}   {raw:.3f}")

Output:

 k  scaled  unscaled
 1  0.950   0.725
 3  0.944   0.703
 5  0.949   0.691
 7  0.967   0.681
 9  0.966   0.703
11  0.955   0.680
15  0.955   0.714
21  0.967   0.720
Command Prompt table of KNN cross-validation accuracy for several k values with and without StandardScaler
Scaled features beat unscaled ones at every k, by a wide margin.

I usually pick an odd k for two-class problems to avoid ties. Scaling matters because distances are dominated by whichever feature has the biggest numbers, like proline in this dataset.

KNN from scratch with NumPy

The algorithm is short enough to write yourself: measure distances, take the k smallest, and vote. Here it predicts T-shirt sizes from height and weight:

import numpy as np
from collections import Counter
from sklearn.neighbors import KNeighborsClassifier

# height (inches), weight (lb) -> T-shirt size
X = np.array([[63, 120], [64, 130], [66, 140], [67, 155], [69, 165], [70, 180], [72, 195], [74, 210], [65, 135], [71, 185]])
y = np.array(["S", "S", "M", "M", "L", "L", "XL", "XL", "S", "L"])

def knn_predict(X_train, y_train, point, k=3):
    distances = np.sqrt(((X_train - point) ** 2).sum(axis=1))    # Euclidean distance to every row
    nearest = np.argsort(distances)[:k]
    votes = Counter(y_train[nearest])
    return votes.most_common(1)[0][0], [(str(s), round(float(d), 1)) for s, d in zip(y_train[nearest], distances[nearest])]

for customer in [[69, 172], [73, 200], [64, 125]]:
    size, neighbors = knn_predict(X, y, np.array(customer))
    sk = KNeighborsClassifier(n_neighbors=3).fit(X, y).predict([customer])[0]
    print(f"{customer} -> {size} (scikit-learn: {sk}) neighbors: {neighbors}")

Output:

[69, 172] -> L (scikit-learn: L) neighbors: [('L', 7.0), ('L', 8.1), ('L', 13.2)]
[73, 200] -> XL (scikit-learn: XL) neighbors: [('XL', 5.1), ('XL', 10.0), ('L', 15.1)]
[64, 125] -> S (scikit-learn: S) neighbors: [('S', 5.0), ('S', 5.1), ('S', 10.0)]
Command Prompt output of a from-scratch Python KNN with NumPy predicting T-shirt sizes and matching scikit-learn
My version agrees with scikit-learn, and it shows which neighbors voted.

Counter.most_common() does the voting; see what is defaultdict in Python for related tools. For real data, use scikit-learn, which uses faster search trees.

One thing I hit while testing: when two training points are exactly the same distance away, your code and scikit-learn can pick different ones and disagree. Avoid ties with an odd k and more data.

Plot KNN accuracy against k

A plot makes the best range of k obvious and shows the scaling gap at every value:

import matplotlib.pyplot as plt
from sklearn.datasets import load_wine
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_wine(return_X_y=True)
ks = range(1, 31)
scaled = [cross_val_score(make_pipeline(StandardScaler(), KNeighborsClassifier(k)), X, y, cv=5).mean() for k in ks]
raw = [cross_val_score(KNeighborsClassifier(k), X, y, cv=5).mean() for k in ks]

plt.figure(figsize=(8, 4.5))
plt.plot(ks, scaled, marker="o", label="with StandardScaler")
plt.plot(ks, raw, marker="s", label="without scaling")
plt.xlabel("k (number of neighbors)"); plt.ylabel("5-fold CV accuracy")
plt.title("KNN accuracy vs k on the wine dataset")
plt.legend(); plt.grid(alpha=0.3); plt.tight_layout()
plt.show()
Matplotlib line chart of KNN cross-validation accuracy for k from 1 to 30 with and without feature scaling on the wine dataset
The scaled model stays far above the unscaled one across all k.

KNN pros and cons

StrengthsWeaknesses
Simple and easy to explainSlow predictions on big datasets
No training stepNeeds feature scaling
Works for classification and regressionStruggles with many features
Naturally handles several classesMemory grows with the training set

For regression, KNeighborsRegressor averages the neighbors’ values instead of voting. Compare with support vector machines in Python.

More machine learning guides:

Frequently asked questions

How do I use k nearest neighbor in Python?

Use KNeighborsClassifier(n_neighbors=5) from scikit-learn in a pipeline with StandardScaler, then fit and predict.

What’s a good value of k?

Test several with cross-validation. Values between 3 and 15 are common starting points.

Do I need to scale features for KNN?

Yes. KNN uses distances, so unscaled features with large numbers dominate.

What’s the difference between KNN and k-means?

KNN is supervised classification using labeled data; k-means is unsupervised clustering without labels.

Can KNN do regression?

Yes, with KNeighborsRegressor, which averages the neighbors’ values.

Where is KNN documented?

See Nearest Neighbors in the scikit-learn user guide.