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
Découvrez KNN in Python with scikit-learn (k-Nearest Neighbors) avec un exemple pratique modifiable et exécutable en ligne.
Points clés
- 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.
Quand l’utiliser ?
- Train and evaluate classic machine learning models on tabular data.
- Prepare features: split, scale and encode data the way real projects do.
- Compare models fairly with cross-validation and the right metric.
Code d’exemple
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())
Résultat de l’exécution
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]
Explication du code
Cet exemple montre KNN in Python with scikit-learn (k-Nearest Neighbors) en pratique. Modifiez les valeurs d’entrée et relancez le code pour voir ce qui change.
Modifiez les valeurs et exécutez le programme avec le compilateur Python en ligne CodeUtility, sans installation locale.
Exercices d’approfondissement
Essayez de modifier le code en suivant les pistes ci-dessous. Changer le code et observer le résultat vous fera bien mieux comprendre la leçon que la simple lecture.
- 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.
Leçon terminée ?
Marquez-la comme apprise pour suivre votre progression.
S'entraîner avec un défi
Utilisez le contenu de cette leçon pour résoudre un vrai problème. Chaque défi s'exécute dans le navigateur, avec des tests instantanés et une revue par l'IA.
Tous les défisOutils pour cette leçon
- Bases de la classification : softmax et k plus proches voisins en PythonTransformez des scores en probabilités de classes avec softmax, évaluez-les avec l'entropie croisée et classez des points avec les k plus proches voisins.
- Jupyter Notebook en ligne : exécuter des cellules Python dans le navigateurJupyter Notebook en ligne gratuit : exécutez des cellules Python avec pandas, NumPy et Matplotlib, ajoutez du texte en Markdown, ouvrez et téléchargez des fichiers .ipynb. Sans installation, sans compte.
- Basthon, Capytale ou CodeUtility : quel outil pour Python en ligne ?Basthon, Capytale et CodeUtility comparés pour écrire du Python en ligne au lycée : à quoi sert chaque outil, compte, débogueur, exercices et classes.