Cluster Analysis — k-Means, Hierarchical, DBSCAN
Statistics
Grouping Similar Observations Without Labels
Cluster analysis partitions data into groups where members are more similar to each other than to outsiders. Each algorithm — k-means, hierarchical, DBSCAN — offers different strengths for different data structures.
-
Customer Segmentation — Group buyers by purchasing behavior for targeted campaigns
-
Genomics — Classify genes with similar expression patterns into functional groups
-
Anomaly Detection — Identify fraud or defects as points that don't belong to any cluster
Finding groups that nature created but didn't label is the essence of unsupervised discovery.
Cluster analysis groups similar observations together without predefined labels. The goal is to maximize within-cluster similarity and between-cluster differences.
k-Means Clustering
k-Means partitions data into k clusters by minimizing the within-cluster sum of squares.
Choosing k: The Elbow Method
Plot against and look for the "elbow" where the rate of decrease slows.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.60, random_state=42)
inertias = []
K_range = range(1, 10)
for k in K_range:
km = KMeans(n_clusters=k, random_state=42, n_init=10)
km.fit(X)
inertias.append(km.inertia_)
plt.figure(figsize=(8, 4))
plt.plot(K_range, inertias, 'bo-')
plt.xlabel('Number of Clusters (k)')
plt.ylabel('Inertia (WCSS)')
plt.title('Elbow Method')
plt.show()
Hierarchical Clustering
Builds a dendrogram — a tree-like hierarchy of clusters.
Agglomerative (Bottom-Up)
-
Start with each point as its own cluster
-
Merge the two closest clusters
-
Repeat until one cluster remains
Distance Metrics
| Metric | Formula | When to Use |
|--------|---------|-------------|
| Euclidean | | Continuous data |
| Manhattan | | High-dimensional data |
| Cosine | | Text data |
Linkage Methods
| Linkage | Definition |
|---------|-----------|
| Single | Minimum distance between any two points in different clusters |
| Complete | Maximum distance between any two points in different clusters |
| Average | Mean distance between all pairs of points |
| Ward | Minimizes total within-cluster variance |
DBSCAN
Density-Based Spatial Clustering of Applications with Noise finds clusters of arbitrary shape and identifies outliers.
| Point Type | Condition |
|-----------|-----------|
| Core | Has at least MinPts within e |
| Border | Within e of a core point but has < MinPts neighbors |
| Noise | Neither core nor border — treated as outlier |
Cluster Evaluation
Silhouette Score
Measures how similar each point is to its own cluster vs. other clusters.
| Score | Interpretation |
|-------|---------------|
| 0.7 - 1.0 | Strong structure |
| 0.5 - 0.7 | Reasonable structure |
| 0.25 - 0.5 | Weak structure |
| < 0.25 | No substantial structure |
Python Implementation
import numpy as np
from sklearn.cluster import KMeans, AgglomerativeClustering, DBSCAN
from sklearn.metrics import silhouette_score
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.60, random_state=42)
# k-Means
km = KMeans(n_clusters=4, random_state=42, n_init=10)
labels_km = km.fit_predict(X)
print(f"k-Means Silhouette: {silhouette_score(X, labels_km):.3f}")
# Hierarchical
hc = AgglomerativeClustering(n_clusters=4)
labels_hc = hc.fit_predict(X)
print(f"Hierarchical Silhouette: {silhouette_score(X, labels_hc):.3f}")
# DBSCAN
db = DBSCAN(eps=0.5, min_samples=5)
labels_db = db.fit_predict(X)
n_clusters = len(set(labels_db)) - (1 if -1 in labels_db else 0)
print(f"DBSCAN found {n_clusters} clusters")
if n_clusters > 1:
mask = labels_db != -1
print(f"DBSCAN Silhouette: {silhouette_score(X[mask], labels_db[mask]):.3f}")
Comparison
| Method | Pros | Cons |
|--------|------|------|
| k-Means | Fast, simple | Must specify k; assumes spherical clusters |
| Hierarchical | Dendrogram; no k needed | Slow for large datasets; irreversible merges |
| DBSCAN | Arbitrary shapes; handles outliers | Sensitive to parameters; struggles with varying densities |
Key Takeaways
Related Topics
-
See Dimensionality Reduction for preprocessing before clustering
-
See Gaussian Mixture Models for probabilistic clustering
-
See k-Nearest Neighbors for distance-based classification
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions