4.1 Clustering
4.1 Clustering
Key Concepts
4.1.1 Overview of Clustering
Clustering is unsupervised learning that groups similar data points together without labels.
Types of Clustering
Clustering Methods
|
┌─────────────────────┼─────────────────────┐
| | |
Partitioning Hierarchical Density-based
(K-means, K-medoids) (Agglomerative) (DBSCAN, OPTICS)
| | |
Fixed K clusters Tree structure Arbitrary shapes
Spherical clusters No K needed Finds outliers
| | |
└─────────────────────┼─────────────────────┘
|
Probabilistic
(GMM, LDA)
|
Soft assignments
Model-basedClustering vs Classification
| Aspect | Clustering | Classification |
|---|---|---|
| Labels | No labels (unsupervised) | Labels required (supervised) |
| Goal | Discover structure | Predict known classes |
| Evaluation | Internal metrics | Accuracy, F1, etc. |
| Output | Group assignments | Class predictions |
4.1.2 K-Means Clustering
Partition data into K clusters by minimizing within-cluster variance.
Algorithm
Input: Data X, number of clusters K
1. Initialize K centroids (randomly or K-means++)
2. Repeat until convergence:
a. ASSIGN: Each point to nearest centroid
c_i = argmin_k ||x_i - μ_k||^2
b. UPDATE: Recompute centroids as cluster means
μ_k = (1/|C_k|) * sum(x_i for x_i in C_k)
3. Return cluster assignments and centroidsVisualization:
Iteration 0: Iteration 1: Converged:
● ● ●
● ● ● ★ ● ● ● ● ● ● ★
● ○ ○ ● ★ ○ ○ ● ○ ○
○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ☆
○ ☆ ○ ○
★☆ = centroids (moving) ●○ = data points (two clusters)Objective Function
J = sum_k sum_{x_i in C_k} ||x_i - μ_k||^2
Minimize total within-cluster sum of squares (WCSS)
Also called "inertia" in sklearnInitialization Methods
Random:
- Pick K random points as initial centroids
- Problem: Can converge to poor local minimum
- Solution: Run multiple times, keep bestK-means++ (default in sklearn):
1. Choose first centroid uniformly at random
2. For each subsequent centroid:
- Compute D(x) = distance to nearest existing centroid
- Choose next centroid with probability proportional to D(x)^2
3. Points far from existing centroids more likely to be chosen
Result: Better spread of initial centroids
O(log K) competitive with optimalChoosing K
Elbow Method:
WCSS
|
|\
| \
| \___________
| ↑
| "elbow"
└──────────────── K
Plot WCSS vs K, look for "elbow" where improvement slowsSilhouette Score:
For each point i:
a(i) = avg distance to points in same cluster
b(i) = avg distance to points in nearest other cluster
s(i) = (b(i) - a(i)) / max(a(i), b(i))
Range: [-1, 1]
1: Well clustered
0: On boundary
-1: Wrong cluster
Overall: average s(i) across all pointsGap Statistic:
Compare WCSS to expected WCSS under null reference distribution
Gap(K) = E[log(WCSS_null)] - log(WCSS)
Choose K that maximizes GapLimitations of K-Means
1. Must specify K in advance
- Often don't know true number of clusters
2. Assumes spherical clusters
✓ Works: ✗ Fails:
● ● ● ●●●●●●●●●●
● ● ● ●●●●●●●●●●
● ● ● ○○○○○○○○○○
○ ○ ○ ○○○○○○○○○○
○ ○ ○ (elongated clusters)
3. Sensitive to outliers
Outliers pull centroids away from true centers
4. Sensitive to initialization
Can converge to local minimum (use K-means++)
5. Assumes equal cluster sizes
Large clusters can "steal" points from small ones
6. Only finds convex clusters
Can't handle arbitrary shapesVariants
K-Medoids (PAM):
- Use actual data points as centers (medoids)
- More robust to outliers
- Works with any distance metric
- Slower: O(K * (n-K)^2) per iterationMini-Batch K-Means:
- Use random mini-batches for updates
- Much faster for large datasets
- Slightly worse quality4.1.3 DBSCAN (Density-Based Spatial Clustering)
Cluster based on density, not distance to centroids.
Core Concepts
Parameters:
- ε (eps): neighborhood radius
- minPts: minimum points to form dense region
Point types:
- Core point: has >= minPts within ε radius
- Border point: within ε of core point, but not core itself
- Noise point: neither core nor border
ε
┌───┐
● ● ● ● <- Core points (>= minPts neighbors)
● ●
○ <- Border point (near core, < minPts)
× <- Noise point (isolated)Algorithm
1. For each point p:
- Find all points within ε distance
- If |neighbors| >= minPts: mark as core point
2. For each core point (not yet assigned):
- Create new cluster
- Add all density-reachable points:
- Direct: within ε of a core point
- Transitive: chain of core points
3. Assign border points to nearest core's cluster
4. Mark remaining points as noiseVisualization:
Cluster 1: Cluster 2: Noise:
● ● ● ○ ○
● ● ● ● ● ○ ○ ○ ○ ×
● ● ● ○ ○
● ×
Arbitrary shapes! Different sizes! Outliers detected!Choosing Parameters
ε (eps):
K-distance plot:
1. For each point, compute distance to K-th nearest neighbor
2. Sort distances and plot
3. Look for "elbow" - sharp increase indicates good ε
Distance
| /
| /
|____/ <- elbow = good ε
|
└────────── Points (sorted)minPts:
Rule of thumb: minPts >= d + 1 (d = dimensions)
minPts >= 2 * d for noisy data
Larger minPts:
- More robust to noise
- May miss small clustersAdvantages and Disadvantages
| Advantages | Disadvantages |
|---|---|
| No need to specify K | Sensitive to ε and minPts |
| Finds arbitrary shapes | Struggles with varying densities |
| Identifies outliers | Not suitable for high dimensions |
| Deterministic (no random init) | O(n^2) without spatial index |
| Robust to outliers | Can't handle clusters of different densities |
DBSCAN vs K-Means
K-Means: DBSCAN:
● ● ● ●●●●●●●●●
● ★ ● <- centroid ●●●●●●●●●
● ● ● ○○○○○○○
○ ○ ○ ○○○○○○○
○ ☆ ○
○ ○ ○ Handles elongated!
Spherical only Arbitrary shapes4.1.4 Hierarchical Clustering
Build a tree (dendrogram) of clusters without specifying K.
Types
Agglomerative (bottom-up):
- Start: each point is its own cluster
- Merge: closest clusters iteratively
- Stop: single cluster or desired K
Divisive (top-down):
- Start: all points in one cluster
- Split: recursively divide
- Less common, more expensiveAgglomerative Algorithm
1. Initialize: each point is a cluster
2. Compute distance matrix between all clusters
3. Repeat until one cluster remains:
a. Find two closest clusters
b. Merge them into one
c. Update distance matrix
4. Return dendrogramLinkage Methods
How to measure distance between clusters:
Single Linkage (MIN):
d(A, B) = min(d(a, b)) for a in A, b in B
Pros: Can find elongated clusters
Cons: "Chaining" effect - can merge distant clusters
A ●───────● B
↑
Single link (shortest)Complete Linkage (MAX):
d(A, B) = max(d(a, b)) for a in A, b in B
Pros: Compact clusters
Cons: Sensitive to outliers
A ●───────────────● B
↑
Complete link (longest)Average Linkage (UPGMA):
d(A, B) = (1/(|A|*|B|)) * sum(d(a, b))
Pros: Balanced between single and complete
Cons: Computationally more expensiveWard's Method:
Minimize increase in total within-cluster variance
d(A, B) = increase in WCSS when merging A and B
Pros: Tends to create equal-sized clusters
Cons: Assumes spherical clusters
Most commonly used!Dendrogram
Height
(distance)
|
5 | ┌───────┐
| ┌───┤ │
3 | ┌───┤ │ │
| │ │ │ │
1 |──┤ │ │ │
| │ │ │ │
└──┴───┴───┴───────┴──
A B C D E
Cut at height 3: {A,B}, {C}, {D,E}
Cut at height 5: {A,B,C}, {D,E}Choosing Number of Clusters
1. Cut dendrogram at desired height
2. Look for large gaps in merge distances
3. Use domain knowledge
4. Silhouette score at different cutsComplexity
Time: O(n^3) naive, O(n^2 log n) with heap
Space: O(n^2) for distance matrix
Not suitable for very large datasets4.1.5 Gaussian Mixture Models (GMM)
Probabilistic clustering with soft assignments.
Model
Assume data generated from K Gaussian distributions:
P(x) = sum_k π_k * N(x | μ_k, Σ_k)
Where:
- π_k = mixing coefficient (prior probability of cluster k)
- μ_k = mean of cluster k
- Σ_k = covariance matrix of cluster k
- sum(π_k) = 1Visualization:
╱╲
╱ ╲ ╱╲
╱ ╲ ╱ ╲
╱ ╲ ╱ ╲
╱ ● ╲ ╱ ○ ╲
╱ ●● ╲╱ ○○ ╲
╱ ●●● ○○○ ╲
────────────────────────────
Two Gaussians with different means
Overlap region: soft assignmentSoft vs Hard Assignment
K-Means (hard):
Point x belongs to cluster 2 (probability = 1)
GMM (soft):
Point x: P(cluster 1) = 0.3, P(cluster 2) = 0.7
Soft assignments useful when:
- Clusters overlap
- Need uncertainty estimates
- Points near boundariesEM Algorithm for GMM
E-step (Expectation):
Compute responsibility (posterior probability):
γ_ik = P(z_i = k | x_i) = (π_k * N(x_i | μ_k, Σ_k)) / P(x_i)
"How much does cluster k explain point i?"M-step (Maximization):
Update parameters using responsibilities:
N_k = sum_i γ_ik (effective cluster size)
μ_k = (1/N_k) * sum_i γ_ik * x_i (weighted mean)
Σ_k = (1/N_k) * sum_i γ_ik * (x_i - μ_k)(x_i - μ_k)^T
π_k = N_k / N (mixing coefficient)Algorithm:
1. Initialize parameters (K-means++ or random)
2. Repeat until convergence:
- E-step: compute responsibilities
- M-step: update parameters
3. Return parameters and assignmentsCovariance Types
Full: Diagonal: Spherical: Tied:
╱╲ │ │ ○ Same Σ
╲╱ │ │ for all
Flexible Axis-aligned Circular Shared
Most params Fewer params Fewest covariance| Type | Parameters per cluster | Use case |
|---|---|---|
| Full | d(d+1)/2 | General, enough data |
| Diagonal | d | Features independent |
| Spherical | 1 | Isotropic clusters |
| Tied | d(d+1)/2 total | Similar cluster shapes |
Model Selection
BIC (Bayesian Information Criterion):
BIC = -2 * log(L) + p * log(n)
Where:
- L = likelihood
- p = number of parameters
- n = number of samples
Lower BIC = better model
Penalizes complexity more than AICGMM vs K-Means
| Aspect | K-Means | GMM |
|---|---|---|
| Assignment | Hard | Soft (probabilistic) |
| Cluster shape | Spherical | Elliptical |
| Output | Centroids | Full distribution |
| Objective | WCSS | Likelihood |
| Initialization | Sensitive | Sensitive |
| Complexity | O(nKd) | O(nKd^2) per iteration |
4.1.6 Cluster Evaluation Metrics
Internal Metrics (no ground truth)
Silhouette Score:
s(i) = (b(i) - a(i)) / max(a(i), b(i))
a(i) = avg intra-cluster distance
b(i) = avg nearest-cluster distance
Range: [-1, 1], higher is betterDavies-Bouldin Index:
DB = (1/K) * sum_k max_{j≠k} (σ_k + σ_j) / d(c_k, c_j)
σ_k = avg distance to centroid in cluster k
d(c_k, c_j) = distance between centroids
Lower is better (compact, well-separated)Calinski-Harabasz Index:
CH = (B / (K-1)) / (W / (n-K))
B = between-cluster dispersion
W = within-cluster dispersion
Higher is betterExternal Metrics (with ground truth)
Adjusted Rand Index (ARI):
Measures agreement between clusterings
Adjusted for chance
Range: [-1, 1]
1: Perfect agreement
0: Random clusteringNormalized Mutual Information (NMI):
NMI = 2 * I(Y; C) / (H(Y) + H(C))
I = mutual information
H = entropy
Range: [0, 1], higher is betterQuestions & Answers
⭐ Q1: What are the common techniques used in unsupervised learning?
Answer:
Unsupervised learning discovers patterns without labels. Main categories:
1. Clustering:
Group similar data points together
- K-Means: partition into K spherical clusters
- DBSCAN: density-based, arbitrary shapes, finds outliers
- Hierarchical: builds tree of clusters (dendrogram)
- GMM: probabilistic soft clustering2. Dimensionality Reduction:
Reduce features while preserving information
- PCA: linear projection maximizing variance
- t-SNE: non-linear, preserves local structure (visualization)
- UMAP: faster t-SNE alternative
- Autoencoders: neural network compression3. Anomaly Detection:
Find unusual data points
- Isolation Forest: isolate anomalies with random trees
- One-class SVM: learn boundary of normal data
- LOF: local outlier factor based on density4. Association Rules:
Find co-occurrence patterns
- Apriori: frequent itemsets
- FP-Growth: faster frequent pattern mining
- Market basket analysis5. Density Estimation:
Model data distribution
- KDE: kernel density estimation
- GMM: mixture of GaussiansWhen to use each:
| Technique | Use Case |
|---|---|
| K-Means | Customer segmentation, image compression |
| DBSCAN | Spatial data, outlier detection |
| Hierarchical | Taxonomy, when K unknown |
| PCA | Feature reduction, visualization |
| t-SNE/UMAP | High-dim visualization |
| Anomaly detection | Fraud, defect detection |
⭐ Q2: How does K-means work? What are its limitations?
Answer:
How K-Means Works:
1. Initialize K centroids (randomly or K-means++)
2. Repeat until convergence:
- ASSIGN: each point to nearest centroid
- UPDATE: move centroids to cluster means
3. Converges when assignments don't changeObjective:
Minimize WCSS = sum_k sum_{x in C_k} ||x - μ_k||^2Limitations:
| Limitation | Problem | Solution |
|---|---|---|
| Must specify K | Often unknown | Elbow method, silhouette |
| Spherical clusters only | Can't handle elongated/irregular | Use DBSCAN or GMM |
| Sensitive to initialization | Local minima | K-means++, multiple runs |
| Sensitive to outliers | Centroids pulled away | K-medoids, remove outliers |
| Equal cluster size assumption | Large clusters dominate | GMM with different covariances |
| Only convex clusters | Can't wrap around | Spectral clustering, DBSCAN |
Visual Example of Failure:
K-Means fails: DBSCAN succeeds:
●●●●●●●●● ●●●●●●●●●
●●●●●●●●● ●●●●●●●●●
★ (one cluster)
○○○○○○○○○ ○○○○○○○○○
○○○○○○○○○ ○○○○○○○○○
☆ (another cluster)
K-Means splits horizontally, missing the true structureWhen K-Means Works Well:
- Clusters are roughly spherical
- Clusters are similar size
- Data is not too high-dimensional
- K is known or can be estimated
Q3: How would you classify products into categories and sub-categories?
Answer:
This is a hierarchical clustering problem. Approach:
1. Feature Engineering:
- Text features: TF-IDF of product names/descriptions
- Categorical: brand, department (if available)
- Numerical: price, ratings, dimensions
- Image features: CNN embeddings (if images available)2. Hierarchical Approach:
Option A: Top-down (Divisive)
1. Cluster all products into broad categories
2. Within each category, cluster into sub-categories
3. Repeat for finer granularity
Option B: Bottom-up (Agglomerative)
1. Start with each product as its own cluster
2. Merge similar products
3. Cut dendrogram at different levels for hierarchy
All Products
|
┌─────────┼─────────┐
| | |
Electronics Clothing Home
| | |
┌─┴─┐ ┌─┴─┐ ┌─┴─┐
Phones TV Mens Womens Kitchen Bath3. Algorithm Choice:
| Level | Algorithm | Why |
|---|---|---|
| Top categories | K-Means or Hierarchical | Broad separation |
| Sub-categories | DBSCAN or GMM | Handle varying sizes |
| Fine-grained | Nearest neighbors | Similar products |
4. Practical Pipeline:
# 1. Extract features
features = extract_text_features(products) # TF-IDF
features = np.hstack([features, numerical_features])
# 2. Reduce dimensions (optional)
features_reduced = PCA(n_components=50).fit_transform(features)
# 3. Top-level clustering
top_clusters = KMeans(n_clusters=10).fit_predict(features_reduced)
# 4. Sub-clustering within each
for cluster_id in range(10):
mask = top_clusters == cluster_id
sub_features = features_reduced[mask]
sub_clusters = KMeans(n_clusters=5).fit_predict(sub_features)5. Validation:
- Silhouette score for cluster quality
- Manual inspection of samples from each cluster
- Business stakeholder review
- A/B test if used for recommendations⭐ Q4: When would you use DBSCAN over K-means?
Answer:
Use DBSCAN when:
1. Number of clusters is unknown
- DBSCAN finds K automatically
- K-Means requires K as input
2. Clusters have arbitrary shapes
K-Means: DBSCAN:
● ● ● ●●●●●●●●●●
● ★ ● (spherical) ●●●●●●●●●● (elongated)
● ● ● ○○○○○○○○
○○○○○○○○
3. Outliers/noise present
- DBSCAN explicitly identifies noise points
- K-Means assigns every point to a cluster
4. Clusters have varying densities (with care)
- Can use HDBSCAN for varying densities
5. Spatial/geographic data
- Natural fit for location-based clustering
- Example: finding hotspots in crime dataUse K-Means when:
1. Clusters are roughly spherical
2. K is known or easily estimated
3. Need fast, scalable algorithm
4. Clusters are similar size
5. Want interpretable centroidsComparison:
| Scenario | K-Means | DBSCAN |
|---|---|---|
| Customer segmentation (spherical) | ✓ | |
| Geographic hotspots | ✓ | |
| Image compression | ✓ | |
| Anomaly detection | ✓ | |
| Known number of groups | ✓ | |
| Irregular cluster shapes | ✓ | |
| Very large datasets | ✓ | (need spatial index) |
Example: Fraud Detection
DBSCAN better because:
- Fraudulent transactions are outliers (noise)
- Normal behavior forms dense regions
- Don't know how many "types" of fraud exist
- Fraud patterns may have irregular shapesQ5: Explain the EM algorithm for GMM.
Answer:
EM (Expectation-Maximization) iteratively finds maximum likelihood parameters when there are latent variables.
Setup:
Model: P(x) = sum_k π_k * N(x | μ_k, Σ_k)
Parameters: θ = {π_k, μ_k, Σ_k} for k = 1..K
Latent variable: z_i = which cluster generated point iE-Step (Expectation):
Compute posterior probability (responsibility):
γ_ik = P(z_i = k | x_i, θ)
= (π_k * N(x_i | μ_k, Σ_k)) / sum_j (π_j * N(x_i | μ_j, Σ_j))
"Given current parameters, how likely is point i from cluster k?"M-Step (Maximization):
Update parameters to maximize expected log-likelihood:
N_k = sum_i γ_ik (soft cluster size)
π_k = N_k / N (mixing coefficient)
μ_k = sum_i (γ_ik * x_i) / N_k (weighted mean)
Σ_k = sum_i (γ_ik * (x_i - μ_k)(x_i - μ_k)^T) / N_kAlgorithm:
1. Initialize: K-means or random
2. Repeat until convergence:
- E-step: compute γ_ik for all i, k
- M-step: update π, μ, Σ
- Compute log-likelihood
3. Converged when log-likelihood change < thresholdWhy It Works:
EM guarantees log-likelihood increases (or stays same) each iteration
Converges to local maximum
Log-likelihood:
L(θ) = sum_i log(sum_k π_k * N(x_i | μ_k, Σ_k))Intuition:
E-step: "If I knew the parameters, which cluster does each point belong to?"
M-step: "If I knew the cluster assignments, what are the best parameters?"
Iterate until consistent.Q6: How do you choose the number of clusters?
Answer:
Methods:
1. Elbow Method:
Plot WCSS vs K, look for "elbow"
WCSS
|
|\
| \
| \____
| ↑
| elbow (K=3)
└──────────── K
Limitation: elbow not always clear2. Silhouette Score:
For each K, compute average silhouette
s = (b - a) / max(a, b)
Choose K with highest average silhouette
More reliable than elbow method3. Gap Statistic:
Compare WCSS to null reference (uniform distribution)
Gap(K) = E[log(WCSS_null)] - log(WCSS)
Choose smallest K where Gap(K) >= Gap(K+1) - s_{K+1}
Statistically principled4. Information Criteria (for GMM):
BIC = -2*log(L) + p*log(n)
AIC = -2*log(L) + 2*p
Lower is better
BIC penalizes complexity more5. Domain Knowledge:
- Business requirements (e.g., "we want 5 customer segments")
- Known structure (e.g., product categories)
- Interpretability needsPractical Approach:
from sklearn.metrics import silhouette_score
scores = []
for k in range(2, 11):
kmeans = KMeans(n_clusters=k, random_state=42)
labels = kmeans.fit_predict(X)
scores.append(silhouette_score(X, labels))
best_k = range(2, 11)[np.argmax(scores)]Comparison:
| Method | Pros | Cons |
|---|---|---|
| Elbow | Simple, visual | Subjective, unclear elbow |
| Silhouette | Quantitative | Computationally expensive |
| Gap statistic | Statistically grounded | Complex to implement |
| BIC/AIC | Model-based | Only for probabilistic models |
| Domain knowledge | Practical | May not match data structure |