Angad Sandhu
Search
Browse
On this page

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-based

Clustering vs Classification

AspectClusteringClassification
LabelsNo labels (unsupervised)Labels required (supervised)
GoalDiscover structurePredict known classes
EvaluationInternal metricsAccuracy, F1, etc.
OutputGroup assignmentsClass 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 centroids

Visualization:

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 sklearn

Initialization Methods

Random:

- Pick K random points as initial centroids
- Problem: Can converge to poor local minimum
- Solution: Run multiple times, keep best

K-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 optimal

Choosing K

Elbow Method:

WCSS
  |
  |\
  | \
  |  \___________
  |      ↑
  |    "elbow"
  └──────────────── K
        
Plot WCSS vs K, look for "elbow" where improvement slows

Silhouette 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 points

Gap Statistic:

Compare WCSS to expected WCSS under null reference distribution
Gap(K) = E[log(WCSS_null)] - log(WCSS)
Choose K that maximizes Gap

Limitations 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 shapes

Variants

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 iteration

Mini-Batch K-Means:

- Use random mini-batches for updates
- Much faster for large datasets
- Slightly worse quality

4.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 noise

Visualization:

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 clusters

Advantages and Disadvantages

AdvantagesDisadvantages
No need to specify KSensitive to ε and minPts
Finds arbitrary shapesStruggles with varying densities
Identifies outliersNot suitable for high dimensions
Deterministic (no random init)O(n^2) without spatial index
Robust to outliersCan't handle clusters of different densities

DBSCAN vs K-Means

K-Means:                    DBSCAN:
    ● ● ●                      ●●●●●●●●●
    ● ★ ●   <- centroid        ●●●●●●●●●
    ● ● ●                         ○○○○○○○
       ○ ○ ○                      ○○○○○○○
       ○ ☆ ○                   
       ○ ○ ○                   Handles elongated!

Spherical only              Arbitrary shapes

4.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 expensive

Agglomerative 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 dendrogram

Linkage 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 expensive

Ward'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 cuts

Complexity

Time:  O(n^3) naive, O(n^2 log n) with heap
Space: O(n^2) for distance matrix

Not suitable for very large datasets

4.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) = 1

Visualization:

         ╱╲
        ╱  ╲        ╱╲
       ╱    ╲      ╱  ╲
      ╱      ╲    ╱    ╲
     ╱   ●    ╲  ╱  ○   ╲
    ╱    ●●    ╲╱   ○○   ╲
   ╱     ●●●        ○○○   ╲
  ────────────────────────────
  
  Two Gaussians with different means
  Overlap region: soft assignment

Soft 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 boundaries

EM 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 assignments

Covariance Types

Full:        Diagonal:      Spherical:    Tied:
╱╲           │ │            ○             Same Σ
╲╱           │ │                          for all

Flexible     Axis-aligned   Circular      Shared
Most params  Fewer params   Fewest        covariance
TypeParameters per clusterUse case
Fulld(d+1)/2General, enough data
DiagonaldFeatures independent
Spherical1Isotropic clusters
Tiedd(d+1)/2 totalSimilar 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 AIC

GMM vs K-Means

AspectK-MeansGMM
AssignmentHardSoft (probabilistic)
Cluster shapeSphericalElliptical
OutputCentroidsFull distribution
ObjectiveWCSSLikelihood
InitializationSensitiveSensitive
ComplexityO(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 better

Davies-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 better

External Metrics (with ground truth)

Adjusted Rand Index (ARI):

Measures agreement between clusterings
Adjusted for chance

Range: [-1, 1]
  1: Perfect agreement
  0: Random clustering

Normalized Mutual Information (NMI):

NMI = 2 * I(Y; C) / (H(Y) + H(C))

I = mutual information
H = entropy

Range: [0, 1], higher is better

Questions & 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 clustering

2. 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 compression

3. 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 density

4. Association Rules:

Find co-occurrence patterns

- Apriori: frequent itemsets
- FP-Growth: faster frequent pattern mining
- Market basket analysis

5. Density Estimation:

Model data distribution

- KDE: kernel density estimation
- GMM: mixture of Gaussians

When to use each:

TechniqueUse Case
K-MeansCustomer segmentation, image compression
DBSCANSpatial data, outlier detection
HierarchicalTaxonomy, when K unknown
PCAFeature reduction, visualization
t-SNE/UMAPHigh-dim visualization
Anomaly detectionFraud, 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 change

Objective:

Minimize WCSS = sum_k sum_{x in C_k} ||x - μ_k||^2

Limitations:

LimitationProblemSolution
Must specify KOften unknownElbow method, silhouette
Spherical clusters onlyCan't handle elongated/irregularUse DBSCAN or GMM
Sensitive to initializationLocal minimaK-means++, multiple runs
Sensitive to outliersCentroids pulled awayK-medoids, remove outliers
Equal cluster size assumptionLarge clusters dominateGMM with different covariances
Only convex clustersCan't wrap aroundSpectral clustering, DBSCAN

Visual Example of Failure:

K-Means fails:              DBSCAN succeeds:
    ●●●●●●●●●                  ●●●●●●●●●
    ●●●●●●●●●                  ●●●●●●●●●
       ★                          (one cluster)
    ○○○○○○○○○                  ○○○○○○○○○
    ○○○○○○○○○                  ○○○○○○○○○
       ☆                          (another cluster)

K-Means splits horizontally, missing the true structure

When 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 Bath

3. Algorithm Choice:

LevelAlgorithmWhy
Top categoriesK-Means or HierarchicalBroad separation
Sub-categoriesDBSCAN or GMMHandle varying sizes
Fine-grainedNearest neighborsSimilar 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 data

Use 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 centroids

Comparison:

ScenarioK-MeansDBSCAN
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 shapes

Q5: 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 i

E-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_k

Algorithm:

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 < threshold

Why 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 clear

2. Silhouette Score:

For each K, compute average silhouette

s = (b - a) / max(a, b)

Choose K with highest average silhouette
More reliable than elbow method

3. 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 principled

4. Information Criteria (for GMM):

BIC = -2*log(L) + p*log(n)
AIC = -2*log(L) + 2*p

Lower is better
BIC penalizes complexity more

5. Domain Knowledge:

- Business requirements (e.g., "we want 5 customer segments")
- Known structure (e.g., product categories)
- Interpretability needs

Practical 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:

MethodProsCons
ElbowSimple, visualSubjective, unclear elbow
SilhouetteQuantitativeComputationally expensive
Gap statisticStatistically groundedComplex to implement
BIC/AICModel-basedOnly for probabilistic models
Domain knowledgePracticalMay not match data structure

Browse the library