Pulse Data Hub

K-Means Clustering Explained: How It Works, with a Python Example

K-means clustering splits a dataset into k groups so that each point belongs to the group whose center is nearest. It’s the most widely used clustering method because it’s simple, fast and easy to explain, and it’s often the first thing people try for customer segmentation, grouping products or finding structure in unlabeled data.

This guide explains how the algorithm works by writing it from scratch in NumPy, then applies scikit-learn’s KMeans to a real dataset of 333 penguins: scaling the data, choosing k, reading the clusters and spotting where k-means fails. Every output shown is what the code printed when we ran it.

How k-means clustering works

K-means is an unsupervised method: there are no labels to learn from, only the data. You choose the number of clusters, k, and the algorithm repeats two steps:

  1. Assign: put every point in the cluster of its nearest center.
  2. Update: move each center to the average (the mean) of the points assigned to it.

It starts from k initial centers and repeats until the centers stop moving. Each round can only lower the inertia, the total squared distance from every point to its center, so the algorithm always settles down, usually within a few rounds.

K-means clustering from scratch in Python

pip install scikit-learn pandas seaborn matplotlib

Here’s the whole algorithm in about 15 lines, run on 300 generated points that form three groups:

import numpy as np
from sklearn.datasets import make_blobs

X_toy, _ = make_blobs(n_samples=300, centers=3, cluster_std=1.0, random_state=7)

def kmeans(X, k, n_iter=10, seed=0):
    rng = np.random.default_rng(seed)
    centers = X[rng.choice(len(X), size=k, replace=False)]   # 1. pick k random points
    for step in range(1, n_iter + 1):
        # 2. assign every point to its nearest center
        dist = np.linalg.norm(X[:, None, :] - centers[None, :, :], axis=2)
        labels = dist.argmin(axis=1)
        # 3. move each center to the mean of its points
        new_centers = np.array([X[labels == j].mean(axis=0) for j in range(k)])
        inertia = ((X - new_centers[labels]) ** 2).sum()
        print(f"step {step}: inertia {inertia:.1f}")
        if np.allclose(new_centers, centers):                 # 4. stop when nothing moves
            break
        centers = new_centers
    return labels, centers

labels, centers = kmeans(X_toy, k=3)
print(centers.round(2))

Output:

step 1: inertia 16419.3
step 2: inertia 7182.0
step 3: inertia 6592.5
step 4: inertia 4494.7
step 5: inertia 706.9
step 6: inertia 573.4
step 7: inertia 573.4
[[-1.26  4.38]
 [ 9.63  0.54]
 [-8.55  5.57]]

Inertia falls fast and stops changing at step 7, when no point switches cluster and the centers stop moving. The three printed centers sit in the middle of the three groups. That’s all k-means is: assign, average, repeat.

Two things follow directly from this loop. The result depends on where the centers start, and the algorithm uses straight-line distance, so features measured on bigger scales count for more. Both matter in practice, as the next sections show.

Step 1: Load real data

The Palmer penguins dataset has body measurements for three species of penguin. We’ll pretend we don’t know the species, cluster the measurements, and then check whether the clusters match the real species.

import pandas as pd
import seaborn as sns

penguins = sns.load_dataset("penguins").dropna()
features = ["bill_length_mm", "bill_depth_mm", "flipper_length_mm", "body_mass_g"]
X = penguins[features]

print(X.shape)
print(X.describe().loc[["mean", "std"]].round(1))

Output:

(333, 4)
      bill_length_mm  bill_depth_mm  flipper_length_mm  body_mass_g
mean            44.0           17.2              201.0       4207.1
std              5.5            2.0               14.0        805.2

After dropping rows with missing values, there are 333 penguins and four measurements. Look at the standard deviations: body mass varies by about 805 grams, bill depth by 2 millimeters.

Step 2: Scale the features first

Because k-means measures straight-line distance, a column with big numbers dominates. Here’s what happens with and without scaling. The adjusted Rand index (ARI) measures how well the clusters match the true species: 1 is a perfect match and 0 is no better than chance.

from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import adjusted_rand_score

scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

for name, data in [("unscaled", X), ("scaled", X_scaled)]:
    km = KMeans(n_clusters=3, n_init=10, random_state=0).fit(data)
    print(f"{name:9} agreement with species (ARI): {adjusted_rand_score(penguins['species'], km.labels_):.3f}")

Output:

unscaled  agreement with species (ARI): 0.316
scaled    agreement with species (ARI): 0.799

Without scaling, k-means mostly groups penguins by body mass, because a difference of 100 grams counts 50 times more than a difference of 2 millimeters. After StandardScaler puts every column on the same scale, the clusters match the species far better: an ARI of 0.80 against 0.32. Scale your features before running k-means unless they’re already in the same units.

Step 3: Choose the number of clusters

K-means needs you to pick k. Two common guides are the elbow method, which looks for the point where adding clusters stops reducing inertia much, and the silhouette score, which measures how well each point fits its own cluster compared with the next closest one, from −1 to 1.

from sklearn.metrics import silhouette_score

for k in range(2, 9):
    km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X_scaled)
    print(f"k={k}  inertia {km.inertia_:7.1f}  silhouette {silhouette_score(X_scaled, km.labels_):.3f}")

Output:

k=2  inertia   552.7  silhouette 0.531
k=3  inertia   370.8  silhouette 0.446
k=4  inertia   293.9  silhouette 0.398
k=5  inertia   228.5  silhouette 0.374
k=6  inertia   200.3  silhouette 0.368
k=7  inertia   183.1  silhouette 0.327
k=8  inertia   166.9  silhouette 0.297
Two line charts for k from 2 to 8: inertia falls steeply until k equals 3 and then more slowly, while the silhouette score is highest at k equals 2 and declines after that
Inertia bends at k = 3; the silhouette score is highest at k = 2.

The two guides disagree, which is common. Inertia drops sharply up to k = 3 and more slowly after, an elbow at 3. The silhouette score is highest at k = 2, because one species, Gentoo, is very different from the other two, so splitting the data in two gives the cleanest separation.

Neither number is the right answer on its own. They’re evidence. Combine them with what the clusters are for: if you need three marketing segments, or you know there are three species, use 3. Here we’ll use k = 3.

Step 4: Fit the model and inspect the clusters

km = KMeans(n_clusters=3, n_init=10, random_state=0).fit(X_scaled)
penguins["cluster"] = km.labels_

print(penguins["cluster"].value_counts().sort_index())
print(pd.crosstab(penguins["cluster"], penguins["species"]))

Output:

cluster
0     85
1    119
2    129
Name: count, dtype: int64
species  Adelie  Chinstrap  Gentoo
cluster                           
0            22         63       0
1             0          0     119
2           124          5       0

Cluster 1 is all 119 Gentoo penguins and nothing else. Almost all of cluster 2 is Adelie (124 of 129). Cluster 0 is mostly Chinstrap, but it also contains 22 Adelie penguins. Chinstrap and Adelie penguins are similar in size, and they differ mainly in bill length, so some overlap is expected.

Remember that cluster numbers are arbitrary labels. Run with a different random seed and the same groups may come back as 2, 0 and 1.

Describe each cluster

A cluster is only useful if you can say what it is. Average the original, unscaled measurements for each one:

profile = penguins.groupby("cluster")[features].mean().round(1)
profile["size"] = penguins["cluster"].value_counts().sort_index()
print(profile)

Output:

         bill_length_mm  bill_depth_mm  flipper_length_mm  body_mass_g  size
cluster                                                                     
0                  47.7           18.7              196.9       3898.2    85
1                  47.6           15.0              217.2       5092.4   119
2                  38.3           18.1              188.6       3593.8   129

Now the clusters have a story. Cluster 1 is the large penguins with long flippers and shallow bills. The small penguins with short bills make up cluster 2. Cluster 0 is small-bodied but has long, deep bills. In customer segmentation, this table is the deliverable: it tells the business who is in each segment.

To see the clusters, plot two of the four measurements:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(7, 5))
for c in range(3):
    pts = penguins[penguins["cluster"] == c]
    ax.scatter(pts["flipper_length_mm"], pts["bill_length_mm"], label=f"cluster {c}", alpha=0.7)
ax.set_xlabel("Flipper length (mm)")
ax.set_ylabel("Bill length (mm)")
ax.legend()
plt.show()
Scatter plot of flipper length against bill length for 333 penguins, colored by cluster, showing three groups: long flippers, short bills, and long bills with short flippers
The three clusters on two of the four measurements.

Assign new data to a cluster

New observations must be scaled with the same scaler before you call predict:

new = pd.DataFrame([{"bill_length_mm": 47.0, "bill_depth_mm": 15.0,
                     "flipper_length_mm": 215, "body_mass_g": 5200}])
print(km.predict(scaler.transform(new)))

Output:

[1]

A heavy penguin with long flippers and a shallow bill goes into cluster 1, the Gentoo-like group.

Why the starting centers matter

Because k-means only ever improves on where it starts, a bad start can leave it stuck in a poor solution. Scikit-learn uses two defenses: a smarter start called k-means++, which spreads the first centers out, and running the whole algorithm several times (n_init) and keeping the best result. To see the difference, run each start method 50 times with a single run each, using six clusters:

for init in ["random", "k-means++"]:
    inertias = [KMeans(n_clusters=6, init=init, n_init=1, random_state=s).fit(X_scaled).inertia_
                for s in range(50)]
    print(f"{init:10} best {min(inertias):.1f}  worst {max(inertias):.1f}  "
          f"runs within 1% of best: {sum(i <= min(inertias) * 1.01 for i in inertias)}/50")

Output:

random     best 200.3  worst 276.7  runs within 1% of best: 13/50
k-means++  best 200.3  worst 272.0  runs within 1% of best: 24/50

Both methods can find the best solution, but k-means++ gets within 1% of it about twice as often (24 runs in 50 against 13). Neither is reliable from a single run, which is why you should keep n_init at 10 or more, as all the other examples here do.

When k-means clustering fails

K-means assumes clusters are roughly round blobs of similar size, because each point simply goes to its nearest center. Data with other shapes breaks that assumption. Two interlocking half-moons are the classic example:

from sklearn.datasets import make_moons
from sklearn.cluster import DBSCAN

X_moons, y_moons = make_moons(n_samples=400, noise=0.06, random_state=0)

km_moons = KMeans(n_clusters=2, n_init=10, random_state=0).fit(X_moons)
db_moons = DBSCAN(eps=0.2, min_samples=5).fit(X_moons)

print("k-means ARI:", round(adjusted_rand_score(y_moons, km_moons.labels_), 3))
print("DBSCAN ARI: ", round(adjusted_rand_score(y_moons, db_moons.labels_), 3))
print("DBSCAN clusters found:", len(set(db_moons.labels_) - {-1}),
      " noise points:", (db_moons.labels_ == -1).sum())

Output:

k-means ARI: 0.274
DBSCAN ARI:  1.0
DBSCAN clusters found: 2  noise points: 0
Two scatter plots of the same two half-moon shapes: k-means cuts across both moons with a straight boundary, while DBSCAN correctly separates the two moons
Left: k-means splits the moons with a straight boundary. Right: DBSCAN follows their shape.

K-means cuts the moons in half with a straight line, an ARI of only 0.27. DBSCAN, a density-based method, grows clusters from dense regions instead of measuring distance to a center, so it follows the curved shapes and recovers both moons perfectly. It also decides the number of clusters itself and can mark outliers as noise (label −1).

K-means vs DBSCAN vs hierarchical clustering

K-meansDBSCANHierarchical (agglomerative)
You chooseNumber of clusters, kNeighborhood size (eps) and min_samplesNumber of clusters or a distance cut-off
Cluster shapesRound, similar sizeAny shapeDepends on the linkage
OutliersForced into a clusterLabeled as noiseForced into a cluster
Speed on large dataFast; MiniBatchKMeans scales to millions of rowsModerateSlow; memory grows with the square of the rows
Predict new pointsYes, nearest centerNo built-in predictNo built-in predict
Best forSegmentation, compression, a first lookIrregular shapes, noisy data, spatial dataSmall datasets where you want a tree of groups

Common mistakes

  1. Not scaling. On the penguins, skipping scaling cut agreement with the true species from 0.80 to 0.32.
  2. Trusting one method to pick k. The elbow and silhouette disagreed here. Check both and think about how the clusters will be used.
  3. Using n_init=1. A single run can land in a poor solution. Keep several restarts.
  4. Using k-means on categorical data. Averages of one-hot columns aren’t meaningful. Use k-modes or k-prototypes, or a method built for mixed data.
  5. Reading cluster numbers as meaningful. They’re arbitrary labels; describe clusters by their averages instead.
  6. Expecting it to find any shape. For curved or uneven clusters, try DBSCAN or a Gaussian mixture model.

Keep learning

The scikit-learn user guide on k-means documents every option of the KMeans class used above.

FAQ

What is k-means clustering in simple terms?

It groups data points into k clusters. Each cluster has a center, every point belongs to the nearest center, and the centers are moved to the middle of their points until nothing changes.

How do I choose k?

Try a range of values and look at the elbow in the inertia curve and at the silhouette score, then pick the value that also makes sense for how you’ll use the clusters. On the penguin data, the elbow pointed to 3 and the silhouette score to 2.

Do I need to scale data for k-means?

Yes, whenever features are measured in different units. K-means uses distances, so unscaled features with large values dominate the result.

Is k-means supervised or unsupervised?

Unsupervised. It never sees labels. In this guide the species labels were used only afterwards, to check how sensible the clusters were.

What is inertia in k-means?

The sum of squared distances from every point to its cluster’s center. Lower is tighter, but it always falls as you add clusters, so it can’t choose k on its own.

What’s the difference between k-means and k-means++?

K-means++ is a way to choose the starting centers so they’re spread out, which makes good results more likely. It’s the default in scikit-learn; the clustering steps afterwards are the same.

When should I use DBSCAN instead of k-means?

When clusters have irregular shapes or different densities, when there are outliers you want flagged rather than forced into a group, or when you don’t know how many clusters to expect.

Newsletter Signup Form

Latest tutorials

Latest articles

On this page
Verified by MonsterInsights