
K-Means vs DBSCAN: Clustering in Python Made Easy
K-Means vs DBSCAN is the comparison most people face when they first cluster real data. Both are unsupervised learning methods, which find structure in data that has no labels. Its two workhorses are clustering, which groups similar data points, and dimensionality reduction, which compresses many features into a few. This guide compares the most popular clustering methods, K-Means and DBSCAN (plus HDBSCAN), explains PCA, t-SNE and UMAP, and shows how to judge results when there is no “right answer” to check against.
What clustering is used for
Clustering automatically groups data points so that points in the same group are more similar to each other than to points in other groups. Typical uses:
- Customer segmentation for targeted marketing.
- Anomaly detection, such as unusual transactions that fit no group.
- Grouping content, such as songs by genre or documents by topic.
- Image segmentation and compressing data for faster processing.
- Feature engineering: a cluster label can become a new input feature for a supervised model.
Clustering methods fall into three broad families: partition-based (K-Means), density-based (DBSCAN, HDBSCAN) and hierarchical (agglomerative or divisive trees of clusters, shown as a dendrogram).
K-Means clustering
K-Means splits the data into k clusters, each represented by its centre (centroid):
- Pick k starting centroids.
- Assign every point to its nearest centroid.
- Move each centroid to the mean of its assigned points.
- Repeat until the assignments stop changing.
K-Means is fast and simple, but it assumes clusters are roughly round and similar in size, it is sensitive to outliers, and you must choose k in advance. The elbow method and silhouette score help you pick k.
DBSCAN and HDBSCAN
DBSCAN groups points that sit in dense regions and labels isolated points as noise. It needs two settings: eps, the neighbourhood radius, and min_samples, the number of neighbours that makes a point a “core” point. It finds clusters of any shape and does not need k, but a single eps struggles when clusters have different densities.
HDBSCAN builds a hierarchy of density levels and keeps the most stable clusters. It adapts to varying densities and needs less tuning, which makes it a strong default for messy real-world data.

K-Means vs DBSCAN: which to choose?
| K-Means | DBSCAN / HDBSCAN | |
|---|---|---|
| Cluster shape | Round, similar sizes | Any shape |
| Number of clusters | You choose k | Found automatically |
| Outliers | Forced into a cluster | Labelled as noise |
| Speed on large data | Very fast | Slower, depends on data |
| Key settings | n_clusters | eps, min_samples (DBSCAN); min_cluster_size (HDBSCAN) |
Dimensionality reduction: PCA, t-SNE and UMAP
High-dimensional data is hard to visualise and can slow down or confuse models. Dimensionality reduction keeps the important information in fewer features.
- PCA (principal component analysis) finds new axes, the principal components, that capture the most variance. It is linear, fast and often used to remove noise or redundant features before modelling.
- t-SNE preserves local neighbourhoods and produces striking 2D maps of clusters. It is slow on large datasets and distances between far-apart clusters are not meaningful.
- UMAP also builds a neighbourhood graph but tends to preserve global structure better and scales to larger datasets than t-SNE.

How to evaluate unsupervised models
Without labels, evaluation relies on how well the structure holds together:
- Silhouette score (−1 to 1): how close each point is to its own cluster compared with the next one. Higher is better.
- Davies–Bouldin index: average similarity between each cluster and its most similar neighbour. Lower is better.
- Inertia: the within-cluster sum of squares used by K-Means and the elbow method.
- External metrics such as the adjusted Rand index apply when you do have reference labels.
- For PCA, the explained variance ratio shows how much information each component keeps.
Numbers are only half the story. Plot the clusters, inspect examples from each group and ask a domain expert whether the groups make sense.
Clustering and PCA in Python
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans, DBSCAN, HDBSCAN
from sklearn.decomposition import PCA
from sklearn.metrics import silhouette_score
X_scaled = StandardScaler().fit_transform(X)
kmeans_labels = KMeans(n_clusters=4, n_init=10, random_state=0).fit_predict(X_scaled)
print("K-Means silhouette:", silhouette_score(X_scaled, kmeans_labels))
dbscan_labels = DBSCAN(eps=0.5, min_samples=5).fit_predict(X_scaled) # -1 = noise
hdb_labels = HDBSCAN(min_cluster_size=15).fit_predict(X_scaled)
pca = PCA(n_components=2).fit(X_scaled)
print("Variance kept:", pca.explained_variance_ratio_.sum())HDBSCAN is included in scikit-learn from version 1.3 onward. For more algorithms and parameter advice, see the scikit-learn clustering guide.
Worked example: K-Means vs DBSCAN on customer data
Imagine an online shop with three features per customer: number of orders, average basket value and days since the last purchase.
- K-Means with k = 4 gives you four tidy segments, such as frequent low spenders or rare big spenders. Every customer lands in a segment, including a handful of extreme accounts that distort the averages.
- DBSCAN or HDBSCAN finds the dense, typical groups and flags unusual customers as noise. Those outliers might be resellers, test accounts or fraud worth reviewing.
In practice, many teams combine the two: HDBSCAN first, to remove outliers and discover how many natural groups exist, then K-Means on the remaining customers for simple, stable segments that marketing can act on. Whichever side of K-Means vs DBSCAN you choose, scale the features first and check the result with the silhouette score and a few real customer profiles from each cluster.
For the full learning path, see our complete guide to machine learning with Python.
Learn unsupervised learning hands-on
Module 4 of IBM’s Machine Learning with Python covers clustering, DBSCAN, HDBSCAN, PCA, t-SNE and UMAP with labs. Read our review or view the course on Coursera.
FAQ
How do I choose the number of clusters in K-Means?
Plot inertia for several values of k and look for the “elbow” where improvements level off, then confirm with the silhouette score and common sense about the business problem.
Should I scale data before clustering?
Almost always. K-Means and DBSCAN use distances, so features with larger ranges would otherwise dominate.
Is PCA a clustering method?
No. PCA reduces the number of features. It is often used before clustering or to visualise clusters, but it does not assign group labels.
Next in the series: How to Evaluate Machine Learning Models.








