Machine Learning with scikit-learn

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.

  • Intermédiaire
  • 3 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • KNeighborsClassifier and n_neighbors
  • Why distances need scaled features
  • Finding the neighbours with kneighbors
Wine test accuracy
No scaling
  • k=5: 0.722
With scaling
  • 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

  1. Without scaling, accuracy is only 0.722 because proline decides the distances.
  2. With StandardScaler in the pipeline, accuracy rises to between 0.963 and 1.000.
  3. n_neighbors=1 copies the nearest point; larger k gives smoother decisions.
  4. kneighbors returns 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

main.py
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())
Obtenir un bouton Run pour cet exemple

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.

  1. Change random_state and see how much the score moves.
  2. Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
  3. Try a different model or hyperparameter and compare the scores.
Exécuter dans le compilateur Python →

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éfis

Outils pour cette leçon