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.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • 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

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.

From ice cream stands to code
n_clusters=3🍦 Put 3 stands on the beach
fit_predict(X)🚶 Everyone walks to the nearest stand
cluster_centers_📍 Where the stands end up
inertia_📏 How far people walk in total (squared)
Assign to the nearest centre, then move the centres.
In one sentence

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

  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.

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

Open in editor →
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}")
Get a Run button for this example

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.

  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.
Run in the Python compiler →

Common mistakes

Picking k without looking at the data

Compare inertia for several values of k and look for the elbow.

Problem
KMeans(n_clusters=8).fit(X)  # the default k
Fix
[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 challenges

Tools for this lesson