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.
- KMeans with n_clusters and n_init
- cluster_centers_ and inertia_
- Choosing k with the elbow method
k=118416.9k=23087.7k=3367.0k=4321.0Groups without labels
The problem
You have data but no labels: customers, shops, measurements. You want to find natural groups in it, for example to treat each group of customers differently.
Think of it like this
K-means is like placing three ice cream stands on a beach. Each person walks to the nearest stand, then each stand moves to the middle of its customers, and this repeats until nobody changes stand.
n_clusters=3🍦 Put 3 stands on the beachfit_predict(X)🚶 Everyone walks to the nearest standcluster_centers_📍 Where the stands end upinertia_📏 How far people walk in total (squared)K-means divides the data into k clusters by repeating two steps: assign each point to its nearest centre, then move each centre to the mean of its points.
Key points
n_init=10runs the algorithm from 10 random starts and keeps the best result.fit_predictreturns a cluster number per point: 100 points in each cluster.inertia_is the sum of squared distances to the centres: 367.0 for k=3.- The elbow: inertia falls from 18416.9 to 367.0 up to k=3, then only slowly.
When should you use it?
- Customer and market segmentation.
- Compressing colours in images.
- Exploring data before labelling it.
When not to use it
- Clusters with odd shapes (rings, moons): try DBSCAN.
- Features on different scales: standardize first, or the large ones decide.
Example code
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}")
Result of running the code
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
Code explanation
make_blobs creates 300 points around 3 centres, and the true labels are thrown away with _ because clustering does not use them. KMeans(n_clusters=3, n_init=10) runs the algorithm from 10 random starts and keeps the best, and fit_predict returns a cluster number for every point: 100 in each. inertia_ is the sum of squared distances from each point to its centre (367.0). In the elbow loop inertia falls steeply from k=1 to k=3 and only slowly after that, which points to 3 clusters.
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
Picking k without looking at the data
Compare inertia for several values of k and look for the elbow.
KMeans(n_clusters=8).fit(X) # the default k
[KMeans(n_clusters=k, n_init=10).fit(X).inertia_ for k in range(1, 7)]
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.
All challengesTools for this lesson
- Cosine Similarity and k-Means Clustering in PythonMeasure how similar two vectors are with cosine similarity and group unlabeled data with k-means.
- 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.