ds@mcpanalytics.aiEmail your data and your question and get an answer about your own data, with the method shown.Email your data and question. Get an answer.

K-Means vs DBSCAN: Choosing the Right Clustering Method

By MCP Analytics Team | Published , updated

A marketing team segments customers using K-Means with K=4. The results look clean: four tidy groups with distinct spending profiles. But one "cluster" contains both high-value loyal customers and bot accounts that made single large purchases. The algorithm forced every point into a cluster, even the ones that do not belong anywhere.

The same team runs DBSCAN. It finds three dense clusters and labels some points as noise, including those bot accounts. The remaining clusters are tighter and more actionable. But DBSCAN missed a small, sparse group of enterprise customers who do not look "dense" enough to form their own cluster.

Neither algorithm is wrong. K-Means partitions data into a fixed number of groups. DBSCAN discovers dense regions of arbitrary shape and identifies outliers. Understanding what each optimizes -- and what it sacrifices -- is the key to choosing correctly.

Worked Example (Simulated)

Simulated data, seed 17. The points below are made up by a script, not customer data.

Question: Which method better matches the known groups in this simulated set?

Inputs: The script makes 300 points with two features and a noise setting of 0.06. It scales both features with StandardScaler. It runs K-Means with 2 clusters and 20 starts, then DBSCAN with eps 0.22 and min_samples 5. The data are two curved groups (make_moons), and K-Means cuts the space with straight lines. The settings (eps 0.22, min_samples 5, 2 clusters) were chosen by the author for this example, and eps was not tuned for both methods.

Method: The script fits each method to the scaled points. It reports the cluster count, the number of DBSCAN noise points, and the adjusted Rand index (ARI) against the known labels.

import numpy as np
from sklearn.cluster import DBSCAN, KMeans
from sklearn.datasets import make_moons
from sklearn.metrics import adjusted_rand_score
from sklearn.preprocessing import StandardScaler

seed = 17
X, truth = make_moons(n_samples=300, noise=0.06, random_state=seed)
X_scaled = StandardScaler().fit_transform(X)
kmeans = KMeans(n_clusters=2, n_init=20, random_state=seed)
k_labels = kmeans.fit_predict(X_scaled)
dbscan = DBSCAN(eps=0.22, min_samples=5)
d_labels = dbscan.fit_predict(X_scaled)
sizes = sorted(np.bincount(d_labels[d_labels >= 0]).tolist())
k_ari = adjusted_rand_score(truth, k_labels)
d_ari = adjusted_rand_score(truth, d_labels)
print(f"seed={seed}; rows={X.shape[0]}; features={X.shape[1]}; moons_noise=0.06")
print("preprocessing=StandardScaler; KMeans n_clusters=2 n_init=20")
print("DBSCAN eps=0.22 min_samples=5")
print(f"KMeans clusters={len(set(k_labels))}; ARI={k_ari:.3f}")
print(f"DBSCAN clusters={len(sizes)}; cluster_sizes={sizes}; "
      f"noise_points={(d_labels == -1).sum()}; ARI={d_ari:.3f}")

Printed output:

seed=17; rows=300; features=2; moons_noise=0.06
preprocessing=StandardScaler; KMeans n_clusters=2 n_init=20
DBSCAN eps=0.22 min_samples=5
KMeans clusters=2; ARI=0.498
DBSCAN clusters=3; cluster_sizes=[56, 94, 146]; noise_points=4; ARI=0.739

Result: K-Means found 2 clusters and had an ARI of 0.498. DBSCAN found 3 clusters (sizes 56, 94 and 146), marked 4 points as noise, and had an ARI of 0.739. On this run, DBSCAN scored higher against the known labels. The data are two curved groups, which K-Means cannot follow, and DBSCAN's eps was chosen for this example. DBSCAN found 3 clusters, not the 2 known groups: it split one moon.

Limit: This is one simulated shape and one set of settings. The result may change with the data and settings.

Sources

How Each Algorithm Works

K-Means: Centroids and Distances

K-Means assigns every data point to the nearest of K cluster centers (centroids). K-Means assigns each point to its closest center, then updates each center to the mean of its assigned points. It repeats until the assignments stop changing. The objective function is to minimize the total within-cluster sum of squared distances (inertia).

To find the natural groups in your own data and what sets each apart, try the free cluster analysis tool.

Because K-Means minimizes distance to centroids, it naturally produces spherical (convex) clusters of roughly similar size. It always assigns every point to exactly one cluster -- there is no concept of "noise" or "outlier." The number K must be specified before running the algorithm.

DBSCAN: Density and Neighborhoods

DBSCAN (Density-Based Spatial Clustering of Applications with Noise) defines clusters as contiguous regions of high density separated by regions of low density. Two parameters control the density threshold: epsilon (the radius of a point's neighborhood) and min_samples (the minimum number of points within that radius to be considered a "core" point).

The algorithm works by expanding clusters from core points. A core point's neighbors become part of its cluster. If any of those neighbors are also core points, their neighborhoods are merged into the same cluster. Points that are reachable from core points but are not themselves core points are "border" points. Points that are not reachable from any core point are labeled as noise.

DBSCAN discovers the number of clusters automatically, can find clusters of any shape, and explicitly identifies outliers. The trade-off: it requires the density of clusters to be roughly uniform, and it struggles when clusters have very different densities.

Side-by-Side Comparison

Feature K-Means DBSCAN
Cluster shape Spherical / convex only Arbitrary shape
Number of clusters Must specify K in advance Discovered automatically
Outlier handling None (assigns all points to a cluster) Labels outliers as noise
Key parameters K (number of clusters) epsilon (radius), min_samples (density threshold)
Cluster sizes Tends toward equal-size clusters Can find clusters of very different sizes
Variable density Not applicable (no density concept) Struggles with varying density clusters
Scalability Depends on data size and settings Depends on data size and settings
Determinism Non-deterministic (random initialization) Deterministic (except border point assignment)
High dimensions Works well (but curse of dimensionality applies) Struggles (epsilon may be harder to set in high dimensions)
New data points Easy to assign (nearest centroid) No built-in prediction for new points

When K-Means Excels

K-Means is the right choice when your data and goals match its assumptions:

Practical example: A SaaS company segments users into engagement tiers based on login frequency, feature usage, and support tickets. They want 4 tiers (power users, regular, occasional, at-risk) to map to different retention strategies. K-Means with K=4 produces clean, interpretable segments with centroids that directly define each tier's profile. The spherical assumption is reasonable because the features are normalized continuous variables without unusual cluster shapes.

When DBSCAN Excels

DBSCAN is the right choice when K-Means' assumptions break down:

Practical example: See the simulated example above for a worked comparison on generated data. As a hypothetical, not a measured result, DBSCAN could group GPS pickup points that follow roads and building layouts and mark points outside dense areas as noise.

Parameter Selection: K vs Epsilon

Choosing K for K-Means

Choosing Epsilon and min_samples for DBSCAN

This is DBSCAN's biggest practical challenge:

Common pitfall: DBSCAN with a poorly chosen epsilon either merges everything into one cluster (epsilon too large) or labels most points as noise (epsilon too small). Unlike K-Means, where a bad K still produces usable results, a bad epsilon produces results that are clearly wrong. Always use the k-distance plot or HDBSCAN.

Practical Considerations

High dimensions: The effect of many features depends on the data and distance measure. Distances may be less useful. K-Means still forms groups, but distances may be less useful when data has many features. In data with many features, distances may be less useful, and DBSCAN's epsilon may be harder to set. The effect depends on the data and distance measure. PCA or UMAP can reduce the number of features before clustering. Reduce dimensionality with PCA or UMAP before clustering.

Varying cluster densities: DBSCAN's main weakness. A single epsilon cannot capture both dense and sparse clusters. Use HDBSCAN instead, which handles varying densities by extracting clusters at multiple density levels.

Feature scaling: Both algorithms are sensitive to feature scales. Standardize features before clustering -- a feature in thousands (revenue) will dominate a feature in units (rating).

Decision Guide

Use K-Means when:

Use DBSCAN when:

Consider alternatives when:

Your turn

Bring your own data and the question you actually need answered.

MCP AnalyticsData science by email Send us your data and your question, and we will reply. ds@mcpanalytics.ai

Frequently Asked Questions

Does DBSCAN require me to specify the number of clusters?

No. DBSCAN discovers the number of clusters automatically from the density structure of your data. You specify epsilon (neighborhood radius) and min_samples (density threshold), and the algorithm determines how many clusters exist. However, the results are sensitive to these parameter choices.

Can K-Means find non-spherical clusters?

No. K-Means assigns points to the nearest centroid, which inherently produces convex (roughly spherical) clusters. It will split a crescent-shaped cluster into multiple pieces. For non-spherical clusters, use DBSCAN, spectral clustering, or Gaussian Mixture Models with full covariance.

How do I choose epsilon for DBSCAN?

Use the k-distance plot: compute the distance to the k-th nearest neighbor (k = min_samples) for every point, sort these distances, and look for the elbow. The optimal epsilon is at the transition between within-cluster and between-cluster distances. Alternatively, use HDBSCAN, which eliminates the epsilon parameter entirely.

Which algorithm scales better to large datasets?

Run time depends on data size, the number of features and the settings you choose. Test both methods on a sample of your own data before you pick one for a large set.

For DBSCAN on its own, with eps and min_samples explained and a simulated example, see the DBSCAN guide.