KNN in Python with scikit-learn (k-Nearest Neighbors)
Classify a point by asking its k nearest neighbours to vote, and see why scaling and the choice of k matter.
- KNeighborsClassifier and n_neighbors
- Why distances need scaled features
- Finding the neighbours with kneighbors
- k=5: 0.722
- k=1: 1.000
- k=5: 0.963
- k=15: 0.981
Ask the neighbours
The problem
You want to classify new items by comparing them with examples you already know, without building a complicated model. Similar items should get the same label.
Think of it like this
KNN is like guessing which team a new player supports by looking at the five people sitting closest to them in the stadium and taking a vote. With one neighbour the guess is jumpy; with more neighbours it is steadier.
fit(X_train, y_train)🏟️ Remember where everyone sitsStandardScaler()📏 Measure every direction in the same unitsn_neighbors=5👥 Look at the 5 closest peoplepredict(X_test)🗳️ Take the majority votek-nearest neighbors predicts the class of a point from the most common class among the k training points closest to it.
Key points
- Without scaling, accuracy is only 0.722 because proline decides the distances.
- With
StandardScalerin the pipeline, accuracy rises to between 0.963 and 1.000. n_neighbors=1copies the nearest point; larger k gives smoother decisions.kneighborsreturns the distances and indexes of the closest training rows.
When should you use it?
- Small datasets where a simple, explainable model is enough.
- Recommendation and
"find similar items"features. - A baseline to compare other classifiers with.
When not to use it
- Very large datasets: every prediction compares against all training rows.
- Many features: distances become less meaningful in high dimensions.
Example code
from sklearn.datasets import load_wine
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=0, stratify=y)
# Without scaling, the large "proline" column dominates the distances
raw = KNeighborsClassifier(n_neighbors=5).fit(X_train, y_train)
print(f"k=5 without scaling: {raw.score(X_test, y_test):.3f}")
for k in [1, 3, 5, 9, 15]:
model = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=k))
model.fit(X_train, y_train)
print(f"k={k:<2} with scaling: {model.score(X_test, y_test):.3f}")
knn = model[-1]
distances, indexes = knn.kneighbors(model[0].transform(X_test[:1]), n_neighbors=3)
print("3 nearest training rows:", indexes[0].tolist(), "classes", y_train[indexes[0]].tolist())
Result of running the code
k=5 without scaling: 0.722
k=1 with scaling: 1.000
k=3 with scaling: 0.963
k=5 with scaling: 0.963
k=9 with scaling: 0.963
k=15 with scaling: 0.981
3 nearest training rows: [70, 60, 73] classes [0, 0, 0]
Code explanation
Without scaling, the proline column (values in the hundreds) decides almost every distance and the model reaches only 0.722 accuracy. Inside the pipeline StandardScaler puts all 13 columns on the same scale, and accuracy jumps to 0.963-1.000. The loop tries k from 1 to 15: k=1 copies the single nearest neighbour, larger k votes over more points and gives smoother decisions. kneighbors shows the three training rows closest to the first test wine, all of class 0.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change random_state and see how much the score moves.
- Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
- Try a different model or hyperparameter and compare the scores.
Common mistakes
Using KNN on unscaled features
The column with the largest numbers dominates every distance.
KNeighborsClassifier(n_neighbors=5).fit(X_train, y_train)
make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5)).fit(X_train, y_train)
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- K-Nearest Neighbors Classifier Predict a label by majority vote of the k closest training points. Medium
Tools for this lesson
- Classification Basics: Softmax and k-Nearest Neighbors in PythonTurn scores into class probabilities with softmax, score them with cross-entropy and classify points with k-nearest neighbors.
- Jupyter Notebook Online: Run Python Cells in Your BrowserFree online Jupyter notebook: run Python cells with pandas, NumPy and Matplotlib, add Markdown text, open and download .ipynb files. No install, no account.
- pandas Online Compiler: Run pandas and NumPy in Your BrowserRun pandas and NumPy code online with nothing to install. NumPy, pandas, SciPy, Matplotlib and scikit-learn are ready in the free Python editor.