Machine Learning with scikit-learn

K-Means Clustering in Python with scikit-learn

Group unlabeled points into k clusters, read the centres and inertia, and choose k with the elbow method.

  • Intermédiaire
  • 2 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • KMeans with n_clusters and n_init
  • cluster_centers_ and inertia_
  • Choosing k with the elbow method
Elbow method
k=118416.9
k=23087.7
k=3367.0
k=4321.0

Groups without labels

Découvrez K-Means Clustering in Python with scikit-learn avec un exemple pratique modifiable et exécutable en ligne.

Points clés

  1. n_init=10 runs the algorithm from 10 random starts and keeps the best result.
  2. fit_predict returns a cluster number per point: 100 points in each cluster.
  3. inertia_ is the sum of squared distances to the centres: 367.0 for k=3.
  4. The elbow: inertia falls from 18416.9 to 367.0 up to k=3, then only slowly.

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
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs

# 300 points around 3 centres; the true labels are ignored
X, _ = make_blobs(n_samples=300, centers=3, cluster_std=0.8, random_state=7)

kmeans = KMeans(n_clusters=3, n_init=10, random_state=0)
labels = kmeans.fit_predict(X)

print("Points per cluster:", np.bincount(labels).tolist())
print("Cluster centres:")
print(np.round(kmeans.cluster_centers_, 2))
print(f"Inertia: {kmeans.inertia_:.1f}")
print("New point [0, 0] goes to cluster", int(kmeans.predict([[0, 0]])[0]))

# Elbow method: inertia drops sharply until k reaches the real number of groups
for k in range(1, 7):
    inertia = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X).inertia_
    print(f"k={k}: inertia {inertia:8.1f}")
Obtenir un bouton Run pour cet exemple

Résultat de l’exécution

Points per cluster: [100, 100, 100]
Cluster centres:
[[-8.54  5.57]
 [ 9.62  0.59]
 [-1.25  4.4 ]]
Inertia: 367.0
New point [0, 0] goes to cluster 2
k=1: inertia  18416.9
k=2: inertia   3087.7
k=3: inertia    367.0
k=4: inertia    321.0
k=5: inertia    278.3
k=6: inertia    239.5

Explication du code

Cet exemple montre K-Means Clustering in Python with scikit-learn 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