“One finds clusters by looking for crowds, the other by asking how likely each point is to belong. Neither forces every point into a box.”
Ep07 ended with K-means struggling in two situations. Clusters that aren’t round blobs, like two interlocking crescents, get cut in half by a straight line. And every point, however strange, is forced into some cluster, so a single odd transaction or broken sensor reading drags a centroid off course. K-means also hands out hard labels: a customer is 100% in one group, even when they sit right on the border.
This post covers the next two unsupervised algorithms, and each fixes part of that. DBSCAN defines clusters as dense regions, so it follows any shape, works out the number of clusters by itself, and labels isolated points as noise. Gaussian mixture models (GMMs) replace hard assignments with probabilities, let clusters be stretched ellipses instead of circles, and tell you how unusual any point is.
DBSCAN: the core idea

Think of a crowded beach seen from above. Groups of people form wherever lots of them stand close together, whatever the shape of the crowd. A person standing alone far from everyone isn’t part of any group. DBSCAN (Density-Based Spatial Clustering of Applications with Noise) turns that intuition into an algorithm with two settings:
eps(ε): the radius of a point’s neighbourhood.min_samples: how many points (including itself) must lie within ε for a neighbourhood to count as dense.
Every point then falls into one of three kinds:
- Core point: has at least
min_samplespoints within ε. It sits inside a crowd. - Border point: has fewer neighbours than that, but lies within ε of a core point. It is on the edge of a crowd.
- Noise point: neither. It is an outlier, and DBSCAN gives it the label −1 instead of forcing it into a cluster.
Clusters grow by chaining: core points that are within ε of each other join the same cluster, and border points attach to the cluster of a nearby core point. You never specify the number of clusters; it falls out of the data.
Step 1: Core, border and noise
import numpy as np
from sklearn.cluster import DBSCAN
X = np.array([[1, 1], [1.5, 1], [1, 1.5], [1.5, 1.5], [2.5, 1.5], # a dense group + one edge point
[6, 6], [6.5, 6], [6, 6.5], [6.5, 6.5], # a second dense group
[4, 9]]) # a lonely point
db = DBSCAN(eps=1.0, min_samples=4).fit(X)
core = np.zeros(len(X), dtype=bool)
core[db.core_sample_indices_] = True
for point, label, is_core in zip(X, db.labels_, core):
kind = "core" if is_core else ("noise" if label == -1 else "border")
print(f"{point} cluster={label:>2} {kind}")
Output:
[1. 1.] cluster= 0 core
[1.5 1. ] cluster= 0 core
[1. 1.5] cluster= 0 core
[1.5 1.5] cluster= 0 core
[2.5 1.5] cluster= 0 border
[6. 6.] cluster= 1 core
[6.5 6. ] cluster= 1 core
[6. 6.5] cluster= 1 core
[6.5 6.5] cluster= 1 core
[4. 9.] cluster=-1 noise
What’s actually happening here
Each of the four points in the bottom-left square has all four square points within ε = 1.0 (diagonals are about 0.71 apart), so all four are core. The point (2.5, 1.5) has only one neighbour within 1.0, itself aside, so it isn’t dense enough to be core; but that neighbour, (1.5, 1.5), is core, so it joins cluster 0 as a border point. The second square forms cluster 1. The point (4, 9) has no neighbours at all and is labelled −1, noise. DBSCAN found two clusters without being told to look for two.
Step 2: Odd shapes and outliers

Back to the crescents from Ep07, now with 15 random outliers scattered around them:
import numpy as np
from sklearn.cluster import DBSCAN, KMeans
from sklearn.datasets import make_moons
from sklearn.metrics import adjusted_rand_score
X, y = make_moons(n_samples=300, noise=0.06, random_state=0)
rng = np.random.default_rng(1)
outliers = rng.uniform([-1.5, -1.0], [2.5, 1.5], (15, 2)) # 15 random noise points
X_all = np.vstack([X, outliers])
kmeans = KMeans(n_clusters=2, n_init=10, random_state=0).fit_predict(X_all)
dbscan = DBSCAN(eps=0.2, min_samples=5).fit_predict(X_all)
print("k-means ARI on the moons:", round(adjusted_rand_score(y, kmeans[:300]), 3))
print("DBSCAN ARI on the moons:", round(adjusted_rand_score(y, dbscan[:300]), 3))
print("DBSCAN found", len(set(dbscan)) - (1 if -1 in dbscan else 0), "clusters and",
(dbscan == -1).sum(), "noise points")
print("of the 15 injected outliers, flagged as noise:", (dbscan[300:] == -1).sum())
Output:
k-means ARI on the moons: 0.234
DBSCAN ARI on the moons: 1.0
DBSCAN found 2 clusters and 10 noise points
of the 15 injected outliers, flagged as noise: 10
What’s actually happening here
As a reminder from Ep07, the adjusted Rand index (ARI) scores agreement with the true groups (1.0 = perfect). K-means scores 0.234: it slices the crescents with a straight line, and every outlier is forced into one of its two clusters. DBSCAN recovers both crescents perfectly, finds exactly two clusters without being told, and labels 10 points as noise. All 10 are injected outliers; the other 5 happened to land inside or right next to a dense crescent, where they genuinely look like normal points. That is honest behaviour: DBSCAN can only flag a point as unusual if it actually sits somewhere sparse.
Step 3: Choosing eps

DBSCAN’s results depend heavily on ε. Too small, and most points look isolated; too large, and everything merges into one blob. The standard trick is the k-distance plot: for every point, measure the distance to its k-th nearest neighbour (with k = min_samples), sort those distances, and look for the elbow where they suddenly jump.
import numpy as np
from sklearn.cluster import DBSCAN
from sklearn.datasets import make_moons
from sklearn.neighbors import NearestNeighbors
X, _ = make_moons(n_samples=300, noise=0.06, random_state=0)
X = np.vstack([X, np.random.default_rng(1).uniform([-1.5, -1.0], [2.5, 1.5], (15, 2))])
# k-distance: how far is each point's 5th nearest neighbour (itself included)?
dist, _ = NearestNeighbors(n_neighbors=5).fit(X).kneighbors(X)
k_dist = np.sort(dist[:, -1])
print("5th-neighbour distance percentiles:",
{p: round(float(np.percentile(k_dist, p)), 3) for p in (50, 90, 95, 98)})
for eps in [0.05, 0.1, 0.2, 0.4, 0.8]:
labels = DBSCAN(eps=eps, min_samples=5).fit_predict(X)
n_clusters = len(set(labels)) - (1 if -1 in labels else 0)
print(f"eps={eps:<4} clusters={n_clusters:>2} noise points={(labels == -1).sum():>3}")
Output:
5th-neighbour distance percentiles: {50: 0.079, 90: 0.117, 95: 0.149, 98: 0.402}
eps=0.05 clusters=12 noise points=247
eps=0.1 clusters=11 noise points= 24
eps=0.2 clusters= 2 noise points= 10
eps=0.4 clusters= 1 noise points= 6
eps=0.8 clusters= 1 noise points= 0
What’s actually happening here
95% of points have their 5th neighbour within 0.149, but the top few percent jump to 0.4 and beyond; those are the sparse outliers. An ε just above the bend, 0.2, gives the right answer: 2 clusters and 10 noise points. Watch the two failure modes in the table. At ε = 0.05 almost everything (247 of 315 points) is noise and the crescents shatter into 12 fragments. At ε = 0.4 the neighbourhoods are so wide that the two crescents touch and merge into one cluster. For min_samples, a common rule of thumb is at least the number of features plus one, and larger values on noisy data.
Gaussian mixture models: soft clusters

DBSCAN still gives every point exactly one label. Real groups overlap, though: a customer who visits fairly often and spends fairly well could reasonably belong to either of two segments. A Gaussian mixture model treats the data as if it were generated by a mix of several Gaussian (normal) distributions, each one a bell-shaped cloud with its own:
- mean μ: the centre of the cloud;
- covariance Σ: its spread and orientation, so a cluster can be a stretched, tilted ellipse rather than a circle;
- weight π: what share of the data it produces.
Instead of a hard label, a GMM gives each point a probability of belonging to each component, for example 90% “big spender”, 10% “regular”.
The model is fitted with the expectation–maximisation (EM) algorithm, which is K-means with soft assignments:
- E-step: for every point, compute the probability it came from each component, given the current means, covariances and weights.
- M-step: re-estimate each component’s mean, covariance and weight using those probabilities as weights.
- Repeat until the likelihood of the data stops improving.
In fact, K-means is a special case of a GMM in which every cluster is forced to be a circle of the same size and every assignment is rounded to 0 or 1.
Step 4: Probabilities instead of labels
import numpy as np
from sklearn.cluster import KMeans
from sklearn.mixture import GaussianMixture
# 400 customers: [visits per month, average spend in Rs. '000], two overlapping groups
rng = np.random.default_rng(3)
regulars = rng.normal([10, 4], [2.0, 1.5], (250, 2))
big_spenders = rng.normal([5, 12], [2.0, 3.0], (150, 2))
X = np.vstack([regulars, big_spenders])
gmm = GaussianMixture(n_components=2, random_state=0).fit(X)
km = KMeans(n_clusters=2, n_init=10, random_state=0).fit(X)
new_customers = np.array([[11, 3], [7, 8], [4, 15]])
for c, probs, hard in zip(new_customers, gmm.predict_proba(new_customers), km.predict(new_customers)):
print(f"customer {c}: GMM probabilities = {probs.round(3)} k-means says cluster {hard}")
print("GMM means:", gmm.means_.round(1).tolist())
print("GMM weights:", gmm.weights_.round(2).tolist())
print("k-means centres:", km.cluster_centers_.round(1).tolist())
Output:
customer [11 3]: GMM probabilities = [1. 0.] k-means says cluster 0
customer [7 8]: GMM probabilities = [0.093 0.907] k-means says cluster 0
customer [ 4 15]: GMM probabilities = [0. 1.] k-means says cluster 1
GMM means: [[10.0, 4.1], [4.9, 12.1]]
GMM weights: [0.62, 0.38]
k-means centres: [[9.9, 4.2], [4.9, 12.4]]
What’s actually happening here
In both models component/cluster 0 is the regulars (centred around 10 visits, Rs. 4k spend) and 1 is the big spenders (around 5 visits, Rs. 12k). The GMM also recovered the mix: weights 0.62 and 0.38, matching the 250 and 150 customers we generated.
The first and third customers are clear-cut, and both models agree. The middle one, (7, 8), is where they differ. K-means puts them with the regulars because that centre is a hair closer (4.78 vs 4.88 units away). The GMM says 90.7% big spender, because it also knows each group’s shape: big spenders vary a lot in spend (a standard deviation of 3, so the ellipse is tall), while regulars are tightly bunched. Being 4 units off in spend is ordinary for a big spender but very unusual for a regular. Distance alone can’t capture that; a probability model can.
Step 5: How many components? Use BIC

A GMM with more components always fits the training data at least as well, so likelihood alone would always pick “more”. The Bayesian information criterion (BIC) balances fit against the number of parameters: lower is better. Here we add a small third group of 60 customers and let BIC find it:
import numpy as np
from sklearn.mixture import GaussianMixture
rng = np.random.default_rng(3)
X = np.vstack([rng.normal([10, 4], [2.0, 1.5], (250, 2)),
rng.normal([5, 12], [2.0, 3.0], (150, 2)),
rng.normal([16, 14], [1.0, 1.0], (60, 2))]) # a third, small, tight group
for k in range(1, 7):
gmm = GaussianMixture(n_components=k, random_state=0).fit(X)
print(f"components={k} BIC={gmm.bic(X):8.1f}")
Output:
components=1 BIC= 5354.1
components=2 BIC= 4940.6
components=3 BIC= 4655.3
components=4 BIC= 4690.6
components=5 BIC= 4722.7
components=6 BIC= 4752.1
What’s actually happening here
BIC falls sharply up to 3 components, the true number, and rises after it: the extra components improve the fit too little to justify their extra means and covariances. This plays the role the elbow and silhouette played for K-means, but with a principled statistical basis. The related AIC (gmm.aic(X)) penalises complexity less and tends to pick slightly more components. You can also restrict cluster shapes with covariance_type: "full" (any ellipse, the default), "diag" (axis-aligned ellipses), "spherical" (circles, like K-means) or "tied" (all clusters share one shape). Simpler shapes need fewer parameters and less data.
Step 6: Anomaly detection with a GMM
Because a GMM is a full probability model, it can score how likely any point is. Points with very low likelihood are anomalies, which is the basis of many fraud and fault detectors:
import numpy as np
from sklearn.mixture import GaussianMixture
rng = np.random.default_rng(3)
X = np.vstack([rng.normal([10, 4], [2.0, 1.5], (250, 2)),
rng.normal([5, 12], [2.0, 3.0], (150, 2))])
gmm = GaussianMixture(n_components=2, random_state=0).fit(X)
threshold = np.percentile(gmm.score_samples(X), 1) # bottom 1% likelihood = unusual
suspects = np.array([[10, 5], [6, 11], [30, 2], [1, 30]])
for s, score in zip(suspects, gmm.score_samples(suspects)):
flag = "ANOMALY" if score < threshold else "normal"
print(f"{s}: log-likelihood = {score:7.2f} -> {flag}")
print("threshold:", round(threshold, 2))
Output:
[10 5]: log-likelihood = -3.40 -> normal
[ 6 11]: log-likelihood = -4.62 -> normal
[30 2]: log-likelihood = -50.40 -> ANOMALY
[ 1 30]: log-likelihood = -23.62 -> ANOMALY
threshold: -8.98
What’s actually happening here
score_samples returns the log-likelihood of each point under the fitted mixture: values near zero are typical, very negative values are improbable. We set the alarm threshold at the 1st percentile of the training scores, so about 1% of normal customers would be flagged. A customer with 30 visits a month (far beyond anyone seen) scores −50.4 and is flagged, and so is one spending Rs. 30k per visit. The two ordinary customers sit comfortably above the threshold. In production you would tune that percentile against the cost of false alarms, exactly the precision-versus-recall trade-off from Ep06.
DBSCAN vs GMM: when to use which
- DBSCAN when clusters have irregular shapes, you don’t know how many there are, and you want outliers flagged rather than absorbed: GPS hotspots and geographic clusters, fraud and anomaly detection, sensor or network-traffic data, image regions, and cleaning outliers out of a dataset before other modelling.
- Gaussian mixture models when groups overlap, clusters are elliptical or differ in size and spread, and you need probabilities rather than hard labels: soft customer segmentation, speaker or voice modelling, density estimation, and likelihood-based anomaly detection.
- K-means (Ep07) remains the fast default for large datasets with compact, similar-sized clusters.
Common first-time mistakes
- Not scaling features. DBSCAN’s ε and a GMM’s covariances are both measured in feature units. A feature in thousands dominates one in decimals.
- Guessing ε. Use the k-distance plot, then check the resulting cluster and noise counts.
- Expecting DBSCAN to handle varying densities. One ε can’t fit both a tight cluster and a sparse one; the sparse one turns into noise. HDBSCAN (
sklearn.cluster.HDBSCAN) adapts to varying densities and is often a better starting point today. - Reading GMM probabilities as certainty. They are only as good as the Gaussian assumption; skewed or multi-peaked groups can produce confident but wrong probabilities.
- Fitting a GMM with full covariances on little data. Each component needs enough points to estimate its covariance; with few samples, use
"diag"or"spherical". - Choosing the number of components by likelihood alone. It always prefers more. Use BIC.
The honest limitations
DBSCAN struggles in high dimensions, where distances become similar and density is hard to define; reduce dimensions first (Ep09). It is sensitive to ε and min_samples, assumes one density level across the data, and its border points can land in different clusters depending on processing order. GMMs assume each cluster is roughly Gaussian, need the number of components chosen (BIC helps), can converge to a local optimum like K-means (n_init runs several starts), and become slow and data-hungry with many features because covariance matrices grow with the square of the number of features.
Where to go next
- scikit-learn: Clustering user guide, covering DBSCAN, HDBSCAN and OPTICS.
- scikit-learn: Gaussian mixture models, covering EM, covariance types, BIC and the Bayesian variant.
Both algorithms in this post struggle once you have dozens or hundreds of features, and so do K-means and KNN. Ep09 tackles that head-on with dimensionality reduction. PCA compresses many correlated features into a few principal components while keeping most of the information, and autoencoders do the same job with a neural network that learns to squeeze data through a bottleneck and rebuild it.
This post is part of the CeyTech series Machine Learning: From 0 to Machine – deep tech, no fluff. Try DBSCAN with eps=0.4 on the crescents, or score your own made-up customers with the GMM, and tell me which ones got flagged.

Comments (...)
You must be signed in to join the discussion.