Skip to content
Visual explainer 3h to learn 5 steps

K-means and DBSCAN clustering in Python

Cluster scaled data with k-means and DBSCAN, test cluster stability and explain what silhouette scores do not tell you.

By Invicly Tech, , in AI and Machine Learning with Python. About 13 minutes to read.

Topic 14 of 34

In short

Clustering groups rows that look alike when you have no labels to learn from. K-means finds a fixed number of round groups around centre points, while DBSCAN finds dense regions of any shape and marks lonely points as noise. Both depend heavily on feature scaling, and neither proves that the groups mean anything in the real world.

Think of it like this: K-means is like placing k ice-cream vans so every house is close to one van; DBSCAN is like drawing a line around every crowded street and ignoring the houses in between.

Explained simply

Most machine learning you have seen so far learns from labels: each row comes with the right answer. Clustering has no answers. You hand it a table and ask which rows look alike. The result is a group number for each row, such as cluster 0, 1 or 2. The algorithm does not know what the groups mean; that part is your job.

K-means is the simplest method. You pick how many groups you want, called k. It drops k centre points into the data, assigns each row to its nearest centre, moves each centre to the middle of its rows, and repeats until nothing changes. It is fast and easy to explain, but it likes round groups of similar size.

DBSCAN works differently. It looks for crowded areas. If a point has enough neighbours within a small radius, it is part of a dense region, and connected dense regions become clusters. Points in empty space are labelled noise. You do not choose the number of groups, but you do choose the radius, called eps.

Both methods measure distance, so units matter. If one column is income in pounds and another is age in years, income differences of thousands will drown out age differences of tens. Scaling every column to a similar range fixes this. Without scaling, you are mostly clustering on your biggest column.

Finally, a clustering result is a suggestion, not a fact. Scores like the silhouette tell you whether groups are tidy and separate. They cannot tell you whether the groups are stable, useful or real. You check that by refitting on different samples and by asking someone who knows the domain.

Press Play on a diagram to walk through it one step at a time.

FlowA careful clustering workflow
  1. 1
    Pick features

    Only columns that should define similarity

  2. 2
    Scale

    StandardScaler so no unit dominates distance

  3. 3
    Fit

    KMeans with a range of k, or DBSCAN with a range of eps

  4. 4
    Check stability

    Refit on resamples and different seeds

  5. 5
    Profile clusters

    Describe each group and ask a domain expert

CompareK-means versus DBSCAN
K-means
  • You choose k up front
  • Assumes roughly round, similar-sized groups
  • Every point joins a cluster
  • Fast on large data
DBSCAN
  • You choose eps and min_samples
  • Finds groups of any shape
  • Sparse points are labelled -1 (noise)
  • Struggles when densities differ a lot
CycleThe k-means loop
  1. 1
    Place k centres

    k-means++ picks spread-out starting points

  2. 2
    Assign

    Each point joins its nearest centre

  3. 3
    Update

    Move each centre to the mean of its points

  4. 4
    Check

    Stop when assignments no longer change

  5. Back to step 1

In depth

Choosing k without fooling yourself

K-means needs k before it starts. The usual tools are the elbow plot and the silhouette score. The elbow plot shows inertia, the total squared distance from points to their centres, for k from 2 to about 10. Inertia always falls as k grows, because more centres means shorter distances, so you look for the bend where adding a cluster stops helping much. The silhouette score compares, for each point, the average distance to its own cluster with the average distance to the nearest other cluster. Values near 1 mean tight, separate groups; near 0 means overlapping groups.

The two often disagree, and real data rarely has a sharp elbow. Treat them as a shortlist. Then pick the k whose groups you can describe and act on. In scikit-learn 1.4 and later, KMeans defaults to n_init="auto"; setting n_init=10 explicitly runs ten random starts and keeps the best, which reduces bad local solutions.

  • Plot inertia and silhouette for k = 2 to 10
  • Fix random_state while comparing k values
  • Prefer a k you can explain over a slightly higher score

Tuning DBSCAN with a k-distance plot

DBSCAN has two settings. min_samples is how many points, including the point itself, must sit within eps for it to be a core point; the default is 5, and a common rule of thumb is about twice the number of features. eps is the radius, in scaled units, with a default of 0.5 that is rarely right for your data.

To choose eps, compute each point's distance to its min_samples-th nearest neighbour with NearestNeighbors, sort these distances and plot them. Most points have small distances; noise points have large ones. The curve bends upward at a knee, and that distance is a good first eps. Too small and almost everything becomes noise; too large and everything merges into one cluster. Always report the share of points labelled -1, because a result with 40 percent noise means something very different from one with 2 percent.

FlowHow DBSCAN labels a point
  1. 1
    Count neighbours

    Points within eps, including itself

  2. 2
    Core point

    At least min_samples neighbours

  3. 3
    Border point

    Fewer neighbours but within eps of a core point

  4. 4
    Noise

    Neither core nor border: label -1

  5. 5
    Join clusters

    Core points within eps of each other share a cluster

Testing cluster stability

A real structure should survive small changes. A practical test: draw several bootstrap samples or random 80 percent subsets, refit the clustering on each, and compare the labels on the rows they share using the adjusted Rand index (ARI). ARI is 1 for identical groupings and about 0 for random agreement, and it does not care that cluster 2 in one run is called cluster 0 in another.

Also refit k-means with different random seeds and DBSCAN with eps nudged up and down by 10 to 20 percent. If ARI stays above about 0.8, the groups are fairly stable. If it swings between 0.3 and 0.9, the clusters depend on luck or on a fragile setting, and you should not build decisions on them. Report stability next to any cluster profile you share.

  • Use adjusted_rand_score from sklearn.metrics
  • Compare labels only on rows present in both fits
  • Check seeds, subsets and nearby parameter values

What cluster scores do not tell you

Silhouette, Davies-Bouldin and Calinski-Harabasz scores all measure geometry: how compact and separated the groups are in the features you chose. They inherit every choice you made. Drop a column, change the scaling or add a log transform and the scores change, even though the customers did not.

They also favour certain shapes. Silhouette rewards round, convex groups, so it can score a good DBSCAN result on long curved clusters lower than a poor k-means split. And none of them can see usefulness. A perfectly separated cluster of test accounts or of rows with missing values scores well and is useless. The honest workflow is to profile each cluster with simple summaries, look at example rows, check stability, and ask whether a team would treat these groups differently.

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Scale features before clustering~35m
  2. 2
    Fit k-means and choose k~35m
  3. 3
    Fit DBSCAN and tune eps~35m
  4. 4
    Test cluster stability~35m
  5. 5
    Know the limits of cluster scores~35m

Key points

  • Distance-based methods treat a 1,000-unit column as far more important than a 0-to-1 column, so scale first.
  • Choose k with the elbow plot, silhouette scores and, most of all, whether the groups are useful.
  • Tune DBSCAN's eps with a k-distance plot rather than by trial and error.
  • A cluster that disappears when you resample the data or change the seed is not a real finding.
  • A high silhouette score says groups are compact and separated, not that they are correct or useful.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
from sklearn.datasets import make_blobs
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

X, _ = make_blobs(n_samples=600, centers=4, random_state=0)
Xs = StandardScaler().fit_transform(X)
for k in range(2, 8):
    km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(Xs)
    print(k, round(km.inertia_, 1), round(silhouette_score(Xs, km.labels_), 3))

Inertia always drops as k grows; look for the bend and the silhouette peak together.

Scaling changes the answer

You have 500 synthetic customers with annual spend (0 to 20,000) and visits per month (0 to 30). Step 1: run k-means with k=3 on the raw columns. The groups split almost entirely on spend because its numbers are a thousand times larger. Step 2: scale both columns with StandardScaler and refit. Now visits matter too and a group of frequent, low-spend visitors appears. Step 3: compare the two labelings with the adjusted Rand index; a low value shows how much scaling changed the result. Lesson: decide what similar means before you cluster.

python
import numpy as np
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import adjusted_rand_score

rng = np.random.default_rng(1)
X = np.c_[rng.gamma(2, 3000, 500), rng.poisson(8, 500)]
raw = KMeans(3, n_init=10, random_state=0).fit_predict(X)
Xs = StandardScaler().fit_transform(X)
scaled = KMeans(3, n_init=10, random_state=0).fit_predict(Xs)
print("ARI raw vs scaled:", round(adjusted_rand_score(raw, scaled), 2))

DBSCAN on two moons

make_moons creates two curved, interlocking half circles. Step 1: fit k-means with k=2; it cuts straight across both moons because it only draws straight borders between centres. Step 2: scale the data, then fit DBSCAN with eps=0.3 and min_samples=5. It follows each curve and recovers both moons. Step 3: count labels equal to -1 to see how many points were called noise. Step 4: try eps=0.1 and eps=1.0 to see too much noise and a single merged cluster.

python
from sklearn.datasets import make_moons
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import DBSCAN
import numpy as np

X, _ = make_moons(n_samples=400, noise=0.06, random_state=0)
Xs = StandardScaler().fit_transform(X)
for eps in [0.1, 0.3, 1.0]:
    labels = DBSCAN(eps=eps, min_samples=5).fit_predict(Xs)
    n = len(set(labels) - {-1})
    print(eps, "clusters:", n, "noise:", np.mean(labels == -1).round(2))

Quick reference

  • Scale first: StandardScaler before KMeans or DBSCAN
  • KMeans(n_clusters=k, n_init=10, random_state=0); inertia_ always falls as k rises
  • silhouette_score ranges -1 to 1; higher means tighter, more separate groups
  • DBSCAN defaults: eps=0.5, min_samples=5; label -1 means noise
  • Pick eps from the knee of a sorted k-nearest-neighbour distance plot
  • adjusted_rand_score compares two clusterings and ignores label names
  • Report noise share, stability and a profile of each cluster

Common mistakes

  • Clustering raw columns where one feature, such as annual income, swamps all the others.
  • Including an ID or date column, so the clusters just rediscover row order.
  • Presenting cluster names like loyal shoppers as facts before anyone has checked them.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Why does inertia alone make a poor way to choose k?

Question 2

2DBSCAN labels 45 percent of your points as -1. What is the most likely fix to try first?

Question 3

3Which data shape suits DBSCAN better than k-means?

Question 4

4Refitting k-means on five random subsets gives pairwise ARI values from 0.35 to 0.9. What should you conclude?

Question 5

5A cluster has a high silhouette score and contains only rows with a missing postcode. What does this show?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Generate 300 points with make_blobs(centers=3), scale them and fit k-means for k from 2 to 6. Print inertia and silhouette for each k.

  2. Exercise 2medium

    Draw a k-distance plot for scaled make_moons data with min_samples=5 and use the knee to choose eps for DBSCAN.

  3. Exercise 3hard

    Measure k-means stability: fit k=4 on ten random 80 percent subsets of a scaled dataset and report the mean pairwise ARI on shared rows.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I need labels to evaluate clustering?
No, but labels help if you have some. Without them you rely on internal scores, stability checks and domain review; with a few known labels you can also measure agreement with the adjusted Rand index.
Can k-means handle categorical columns?
Not directly, because the mean of categories is meaningless. One-hot encoding works for a few categories, or use a method designed for mixed data, such as k-prototypes from a separate library.
Should I use HDBSCAN instead of DBSCAN?
HDBSCAN, available in scikit-learn since version 1.3, handles clusters of different densities better and removes the need to pick eps. Learn DBSCAN first, because HDBSCAN builds on the same ideas.

Go deeper

ShareXLinkedInWhatsApp