Machine Learning | Clustering Algorithms

Master K-Means, hierarchical clustering, DBSCAN, and GMM

Table of Contents
  1. Clustering Fundamentals
  2. K-Means Clustering
  3. Hierarchical Clustering
  4. DBSCAN
  5. Gaussian Mixture Models
  6. Evaluation Metrics
  7. Choosing the Number of Clusters
  8. Interview Questions

Clustering Fundamentals

What is Clustering?

Clustering is unsupervised learning that groups similar data points together without predefined labels. The goal is to maximize intra-cluster similarity and minimize inter-cluster similarity.

K-Means

Type: Centroid-based

  • Fast, scalable
  • Spherical clusters
  • Requires K upfront
Hierarchical

Type: Connectivity-based

  • Dendrogram visualization
  • No K needed upfront
  • O(n²) or O(n³)
DBSCAN

Type: Density-based

  • Finds arbitrary shapes
  • Handles noise
  • No K needed
GMM

Type: Distribution-based

  • Soft assignments
  • Elliptical clusters
  • Probabilistic

K-Means Clustering

Objective Function

Minimize within-cluster sum of squares (inertia):

\[J = \sum_{i=1}^{K} \sum_{x \in C_i} \|x - \mu_i\|^2\]

Where \(\mu_i\) is the centroid of cluster \(C_i\)

Lloyd's Algorithm:

  1. Initialize K centroids randomly
  2. Assign each point to nearest centroid
  3. Update centroids as cluster means
  4. Repeat until convergence
K-Means++ Initialization

Smart initialization to avoid poor local minima:

  1. Choose first centroid uniformly at random
  2. For each point x, compute D(x) = distance to nearest centroid
  3. Choose next centroid with probability \(\propto D(x)^2\)
  4. Repeat until K centroids chosen

Benefits:

  • O(log K) competitive with optimal
  • Faster convergence
  • Default in sklearn

Python Implementation

import numpy as np
from sklearn.cluster import KMeans, MiniBatchKMeans
from sklearn.preprocessing import StandardScaler

# Standard K-Means
kmeans = KMeans(
    n_clusters=5,
    init='k-means++',      # Smart initialization
    n_init=10,             # Run 10 times with different seeds
    max_iter=300,
    random_state=42
)

# Scale features first (important for distance-based methods)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# Fit and predict
labels = kmeans.fit_predict(X_scaled)
centroids = kmeans.cluster_centers_
inertia = kmeans.inertia_

# For large datasets, use MiniBatchKMeans
minibatch_km = MiniBatchKMeans(
    n_clusters=5,
    batch_size=1024,
    random_state=42
)
labels_mb = minibatch_km.fit_predict(X_scaled)

# Manual implementation to understand the algorithm
class KMeansManual:
    def __init__(self, n_clusters=3, max_iter=100, tol=1e-4):
        self.k = n_clusters
        self.max_iter = max_iter
        self.tol = tol

    def fit(self, X):
        n_samples = X.shape[0]

        # K-means++ initialization
        self.centroids = self._kmeans_plusplus(X)

        for iteration in range(self.max_iter):
            # Assign clusters
            distances = self._compute_distances(X)
            self.labels = np.argmin(distances, axis=1)

            # Update centroids
            new_centroids = np.array([
                X[self.labels == k].mean(axis=0) if np.sum(self.labels == k) > 0
                else self.centroids[k]
                for k in range(self.k)
            ])

            # Check convergence
            if np.all(np.abs(new_centroids - self.centroids) < self.tol):
                break

            self.centroids = new_centroids

        return self

    def _kmeans_plusplus(self, X):
        centroids = [X[np.random.randint(len(X))]]

        for _ in range(1, self.k):
            distances = np.min([
                np.sum((X - c) ** 2, axis=1) for c in centroids
            ], axis=0)
            probs = distances / distances.sum()
            centroids.append(X[np.random.choice(len(X), p=probs)])

        return np.array(centroids)

    def _compute_distances(self, X):
        return np.array([
            np.sum((X - c) ** 2, axis=1) for c in self.centroids
        ]).T

    def predict(self, X):
        distances = self._compute_distances(X)
        return np.argmin(distances, axis=1)
Interview Tip: K-Means Limitations

When K-Means fails:

  • Non-spherical clusters (use DBSCAN or spectral clustering)
  • Clusters of different sizes/densities
  • High-dimensional data (curse of dimensionality)
  • Presence of outliers (consider K-Medoids)

Hierarchical Clustering

Agglomerative (Bottom-Up)
  1. Start with each point as its own cluster
  2. Merge two closest clusters
  3. Repeat until one cluster remains

Linkage methods:

  • Single: min distance between clusters
  • Complete: max distance
  • Average: mean pairwise distance
  • Ward: minimize variance increase
Divisive (Top-Down)
  1. Start with all points in one cluster
  2. Split the cluster recursively
  3. Repeat until each point is its own cluster

Less common because:

  • More computationally expensive
  • Need to decide how to split
  • Often use K-Means for splitting
from scipy.cluster.hierarchy import dendrogram, linkage, fcluster
from sklearn.cluster import AgglomerativeClustering
import matplotlib.pyplot as plt

# Compute linkage matrix
Z = linkage(X_scaled, method='ward')  # Ward minimizes variance

# Plot dendrogram
plt.figure(figsize=(12, 6))
dendrogram(
    Z,
    truncate_mode='lastp',  # Show only last p merged clusters
    p=30,
    leaf_rotation=90,
    leaf_font_size=10,
    show_contracted=True
)
plt.title('Hierarchical Clustering Dendrogram')
plt.xlabel('Sample index or (cluster size)')
plt.ylabel('Distance')
plt.axhline(y=50, color='r', linestyle='--', label='Cut threshold')
plt.show()

# Cut dendrogram to get clusters
labels = fcluster(Z, t=50, criterion='distance')
# Or by number of clusters
labels = fcluster(Z, t=5, criterion='maxclust')

# Using sklearn (more convenient for prediction)
agg = AgglomerativeClustering(
    n_clusters=5,
    linkage='ward',
    # Can also use distance_threshold instead of n_clusters
)
labels = agg.fit_predict(X_scaled)

DBSCAN

Density-Based Spatial Clustering

DBSCAN groups points that are closely packed together, marking points in low-density regions as outliers. It can find clusters of arbitrary shape.

Key Concepts
  • ε (eps): Radius of neighborhood
  • MinPts: Minimum points to form dense region
  • Core point: Has ≥ MinPts within ε
  • Border point: Within ε of core point, but not core itself
  • Noise point: Neither core nor border

Complexity: O(n log n) with spatial index, O(n²) without

Algorithm
  1. For each unvisited point P:
  2. Find all points within ε of P
  3. If ≥ MinPts: start new cluster, expand
  4. If < MinPts: mark as noise (may later become border)
  5. Continue until all points visited

Choosing parameters:

  • MinPts ≥ dim + 1 (typically 2×dim)
  • ε: Use k-distance plot (knee method)
from sklearn.cluster import DBSCAN
from sklearn.neighbors import NearestNeighbors
import numpy as np

# Finding optimal eps using k-distance plot
def find_optimal_eps(X, min_samples=5):
    """Use k-distance graph to find eps"""
    neighbors = NearestNeighbors(n_neighbors=min_samples)
    neighbors.fit(X)
    distances, _ = neighbors.kneighbors(X)

    # Sort distances to kth nearest neighbor
    k_distances = np.sort(distances[:, -1])

    # Plot to find "knee"
    plt.figure(figsize=(10, 6))
    plt.plot(k_distances)
    plt.xlabel('Points sorted by distance')
    plt.ylabel(f'{min_samples}-th nearest neighbor distance')
    plt.title('K-Distance Graph for DBSCAN eps selection')
    plt.grid(True)
    plt.show()

    return k_distances

# Run DBSCAN
dbscan = DBSCAN(
    eps=0.5,
    min_samples=5,
    metric='euclidean',
    n_jobs=-1
)

labels = dbscan.fit_predict(X_scaled)

# Identify results
n_clusters = len(set(labels)) - (1 if -1 in labels else 0)
n_noise = list(labels).count(-1)
print(f'Clusters: {n_clusters}, Noise points: {n_noise}')

# Core samples
core_mask = np.zeros(len(labels), dtype=bool)
core_mask[dbscan.core_sample_indices_] = True

# HDBSCAN - Hierarchical DBSCAN (handles varying densities)
import hdbscan

clusterer = hdbscan.HDBSCAN(
    min_cluster_size=15,
    min_samples=5,
    cluster_selection_epsilon=0.5
)
labels = clusterer.fit_predict(X_scaled)
probabilities = clusterer.probabilities_  # Soft cluster membership

Gaussian Mixture Models

Model

Data is generated from K Gaussian distributions:

\[p(x) = \sum_{k=1}^{K} \pi_k \mathcal{N}(x | \mu_k, \Sigma_k)\]

Where:

  • \(\pi_k\): Mixing coefficients (\(\sum \pi_k = 1\))
  • \(\mu_k\): Mean of component k
  • \(\Sigma_k\): Covariance of component k
EM Algorithm

E-step: Compute responsibilities

\[\gamma_{nk} = \frac{\pi_k \mathcal{N}(x_n | \mu_k, \Sigma_k)}{\sum_j \pi_j \mathcal{N}(x_n | \mu_j, \Sigma_j)}\]

M-step: Update parameters

\[\mu_k = \frac{\sum_n \gamma_{nk} x_n}{\sum_n \gamma_{nk}}\]

Iterate until log-likelihood converges

from sklearn.mixture import GaussianMixture

# Fit GMM
gmm = GaussianMixture(
    n_components=5,
    covariance_type='full',  # 'spherical', 'diag', 'tied', 'full'
    n_init=10,
    max_iter=100,
    random_state=42
)

gmm.fit(X_scaled)

# Hard assignment
labels = gmm.predict(X_scaled)

# Soft assignment (probabilities)
probs = gmm.predict_proba(X_scaled)

# Model parameters
print(f"Means shape: {gmm.means_.shape}")
print(f"Covariances shape: {gmm.covariances_.shape}")
print(f"Weights: {gmm.weights_}")

# Model selection with BIC/AIC
n_components_range = range(1, 11)
bic_scores = []
aic_scores = []

for n in n_components_range:
    gmm = GaussianMixture(n_components=n, random_state=42)
    gmm.fit(X_scaled)
    bic_scores.append(gmm.bic(X_scaled))
    aic_scores.append(gmm.aic(X_scaled))

optimal_k = n_components_range[np.argmin(bic_scores)]
print(f"Optimal K by BIC: {optimal_k}")
GMM vs K-Means
  • GMM: Soft assignments, elliptical clusters
  • K-Means: Hard assignments, spherical clusters
  • K-Means is a special case of GMM (spherical, equal covariance)
  • GMM provides uncertainty estimates
Covariance Types
  • spherical: σ²I (like K-Means)
  • diag: Diagonal matrix (axis-aligned)
  • tied: All clusters share same Σ
  • full: Each cluster has own Σ (most flexible)

Evaluation Metrics

Internal Metrics (No labels)

Silhouette Score:

\[s(i) = \frac{b(i) - a(i)}{\max(a(i), b(i))}\]

  • a(i): Mean distance to same cluster
  • b(i): Mean distance to nearest other cluster
  • Range: [-1, 1], higher is better

Calinski-Harabasz Index:

\[\text{CH} = \frac{\text{Between-cluster dispersion}}{\text{Within-cluster dispersion}} \times \frac{n-k}{k-1}\]

External Metrics (With labels)

Adjusted Rand Index (ARI):

  • Measures agreement with ground truth
  • Range: [-1, 1], 1 = perfect match
  • Adjusted for chance

Normalized Mutual Information (NMI):

\[\text{NMI} = \frac{2 \cdot I(Y; C)}{H(Y) + H(C)}\]

  • Based on information theory
  • Range: [0, 1], 1 = perfect
from sklearn.metrics import (
    silhouette_score, calinski_harabasz_score, davies_bouldin_score,
    adjusted_rand_score, normalized_mutual_info_score, homogeneity_score
)

# Internal metrics (no ground truth needed)
silhouette = silhouette_score(X_scaled, labels)
calinski = calinski_harabasz_score(X_scaled, labels)
davies_bouldin = davies_bouldin_score(X_scaled, labels)  # Lower is better

print(f"Silhouette Score: {silhouette:.3f}")
print(f"Calinski-Harabasz Index: {calinski:.1f}")
print(f"Davies-Bouldin Index: {davies_bouldin:.3f}")

# External metrics (when ground truth available)
ari = adjusted_rand_score(y_true, labels)
nmi = normalized_mutual_info_score(y_true, labels)
homogeneity = homogeneity_score(y_true, labels)

print(f"Adjusted Rand Index: {ari:.3f}")
print(f"Normalized Mutual Information: {nmi:.3f}")
print(f"Homogeneity: {homogeneity:.3f}")

Choosing the Number of Clusters

Elbow Method

Plot inertia vs K, find the "elbow"

  • Look for diminishing returns
  • Subjective interpretation
  • May not have clear elbow
Silhouette Analysis

Maximize average silhouette score

  • Check silhouette plot per cluster
  • Uniform cluster sizes preferred
  • More reliable than elbow
Gap Statistic

Compare to null reference distribution

\[\text{Gap}(k) = E[\log W_k^*] - \log W_k\]

  • Statistically principled
  • Computationally expensive
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
import matplotlib.pyplot as plt

def find_optimal_k(X, max_k=10):
    """Use multiple methods to find optimal K"""
    inertias = []
    silhouettes = []

    for k in range(2, max_k + 1):
        kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)
        labels = kmeans.fit_predict(X)

        inertias.append(kmeans.inertia_)
        silhouettes.append(silhouette_score(X, labels))

    # Plot
    fig, axes = plt.subplots(1, 2, figsize=(14, 5))

    # Elbow plot
    axes[0].plot(range(2, max_k + 1), inertias, 'bo-')
    axes[0].set_xlabel('Number of clusters (K)')
    axes[0].set_ylabel('Inertia')
    axes[0].set_title('Elbow Method')

    # Silhouette plot
    axes[1].plot(range(2, max_k + 1), silhouettes, 'ro-')
    axes[1].set_xlabel('Number of clusters (K)')
    axes[1].set_ylabel('Silhouette Score')
    axes[1].set_title('Silhouette Analysis')

    plt.tight_layout()
    plt.show()

    optimal_k = range(2, max_k + 1)[np.argmax(silhouettes)]
    return optimal_k

# For GMM, use BIC
def find_optimal_k_gmm(X, max_k=10):
    bics = []
    for k in range(1, max_k + 1):
        gmm = GaussianMixture(n_components=k, random_state=42)
        gmm.fit(X)
        bics.append(gmm.bic(X))

    return np.argmin(bics) + 1  # +1 because range starts at 1

Interview Questions

Multiple approaches:

  1. Elbow method: Plot inertia vs K, find diminishing returns
  2. Silhouette analysis: Maximize average silhouette score
  3. Gap statistic: Compare to null distribution
  4. BIC/AIC: For GMM, penalize model complexity
  5. Domain knowledge: Business context may dictate K

Best practice: Use multiple methods and validate with domain experts. There's rarely one "correct" K - it depends on the use case.

Use DBSCAN when:

  • Clusters have arbitrary (non-spherical) shapes
  • Data has noise/outliers that should be excluded
  • Number of clusters is unknown
  • Clusters have varying densities (consider HDBSCAN)

Use K-Means when:

  • Clusters are roughly spherical and similar size
  • You need to assign new points to clusters
  • Scalability is critical (K-Means is O(nkd))
  • Interpretability via centroids is important

Hard clustering:

  • Each point belongs to exactly one cluster
  • Examples: K-Means, DBSCAN, Hierarchical
  • Output: Label per point

Soft clustering:

  • Each point has probability of belonging to each cluster
  • Examples: GMM, Fuzzy C-Means
  • Output: Probability vector per point

When to use soft: When cluster boundaries are ambiguous, when you need uncertainty estimates, or when points naturally belong to multiple groups (e.g., customer segments).

Approach:

  1. Feature engineering: RFM (Recency, Frequency, Monetary), demographics, behavior
  2. Preprocessing: Scale features, handle missing values, reduce dimensionality if needed
  3. Algorithm selection: Start with K-Means for simplicity, try GMM for soft assignments
  4. Choose K: Use silhouette analysis, but also consider business constraints (can you handle 10 segments?)
  5. Validation: Profile clusters, ensure they're actionable and distinct
  6. Production: Save model, assign new customers to clusters

Key insight: The "best" clustering is one that's actionable for business, not just statistically optimal.

Distance-based algorithms are affected by scale:

  • Feature with range [0, 1000] dominates feature with range [0, 1]
  • K-Means, DBSCAN, Hierarchical all use distances
  • Unscaled data leads to biased clusters

Scaling options:

  • StandardScaler: Zero mean, unit variance (most common)
  • MinMaxScaler: Scale to [0, 1] range
  • RobustScaler: Use median/IQR, robust to outliers

Exception: GMM with full covariance can handle different scales, but scaling still helps convergence.

Previous: Anomaly Detection Next: Model Interpretability