Unsupervised Learning
🎯 Learning Objectives
- Understand K-Means clustering algorithm step-by-step
- Choose optimal K using elbow method and silhouette score
- Compare hierarchical clustering approaches and linkage criteria
- Apply PCA for dimensionality reduction using eigendecomposition
- Know DBSCAN for density-based clustering and Apriori for association rules
1. K-Means Clustering
K-Means partitions n data points into K clusters by iteratively assigning points to the nearest centroid and recomputing centroids.
Input: Data X = {x_1, ..., x_n}, number of clusters K
1. INITIALISE: Randomly select K data points as initial centroids μ_1, ..., μ_K
2. REPEAT until convergence:
a. ASSIGN: For each x_i, assign to cluster c_i = argmin_k ||x_i - μ_k||^2
b. UPDATE: For each cluster k, recompute centroid μ_k = (1/|C_k|) ∑_{x_i ∈ C_k} x_i
3. Convergence: Stop when assignments no longer change (or max iterations reached)
Objective: Minimise WCSS = ∑_{k=1}^{K} ∑_{x_i ∈ C_k} ||x_i - μ_k||^2
Q: Apply K-Means (K=2) to points: A(1,1), B(1.5,2), C(3,4), D(5,7), E(3.5,5), F(4.5,5). Initial centroids: μ₁=(1,1), μ₂=(5,7).
Iteration 1 — Assignment:
- A(1,1): d(A,μ₁)=0, d(A,μ₂)=7.21 → Cluster 1
- B(1.5,2): d(B,μ₁)=1.12, d(B,μ₂)=6.10 → Cluster 1
- C(3,4): d(C,μ₁)=3.61, d(C,μ₂)=3.61 → Cluster 1 (tie, assign to first)
- D(5,7): d(D,μ₁)=7.21, d(D,μ₂)=0 → Cluster 2
- E(3.5,5): d(E,μ₁)=4.72, d(E,μ₂)=2.50 → Cluster 2
- F(4.5,5): d(F,μ₁)=5.32, d(F,μ₂)=2.06 → Cluster 2
Iteration 1 — Update:
μ₁ = ((1+1.5+3)/3, (1+2+4)/3) = (1.83, 2.33)
μ₂ = ((5+3.5+4.5)/3, (7+5+5)/3) = (4.33, 5.67)
Continue until assignments stabilise.
1.1 Choosing K: Elbow Method
Plot the Within-Cluster Sum of Squares (WCSS) against different values of K. The “elbow” point where the rate of decrease sharply changes suggests the optimal K.
1.2 Silhouette Score
For each data point i:
s(i) = (b(i) − a(i)) / max(a(i), b(i))
where a(i) = mean intra-cluster distance, b(i) = mean nearest-cluster distance. Range: [−1, 1]. Higher is better. Average over all points gives the silhouette score.
- Assumes spherical, equally-sized clusters
- Sensitive to initialisation (solution: K-Means++ or multiple runs)
- K must be specified in advance
- Sensitive to outliers (centroids get pulled toward them)
- Cannot find non-convex clusters
2. Hierarchical Clustering
Hierarchical clustering builds a tree-like structure (dendrogram) of nested clusters. There are two approaches:
2.1 Agglomerative (Bottom-Up)
1. Start: Each data point is its own cluster (n clusters) 2. REPEAT until one cluster remains: a. Find the two closest clusters b. Merge them into a single cluster 3. Use the dendrogram to choose the desired number of clusters by cutting at appropriate height
2.2 Linkage Criteria
| Linkage | Distance Between Clusters | Properties |
|---|---|---|
| Single | min distance between any two points | Can find elongated clusters; sensitive to noise (chaining effect) |
| Complete | max distance between any two points | Compact clusters; sensitive to outliers |
| Average | Average distance between all pairs | Compromise between single and complete |
| Ward’s | Increase in WCSS after merging | Minimises variance; tends to create equal-sized clusters |
Q: Points: A(0,0), B(1,0), C(4,0), D(5,0). Use single linkage. Show merge steps.
Distance matrix:
d(A,B)=1, d(A,C)=4, d(A,D)=5, d(B,C)=3, d(B,D)=4, d(C,D)=1
Step 1: Merge A&B (distance 1) and C&D (distance 1) — tie, merge both.
Step 2: Clusters: {A,B}, {C,D}. Single linkage distance = min(d(B,C)) = 3. Merge → {A,B,C,D}.
Dendrogram heights: 1, 1, 3.
3. DBSCAN
Density-Based Spatial Clustering of Applications with Noise. Unlike K-Means, DBSCAN can find arbitrarily shaped clusters and automatically identifies noise points.
- ε (eps): Radius of the neighbourhood around a point
- MinPts: Minimum number of points within ε to form a dense region
- Core point: Has ≥ MinPts within its ε-neighbourhood
- Border point: Within ε of a core point, but has < MinPts neighbours
- Noise point: Neither core nor border
For each unvisited point p:
1. Mark p as visited
2. Find all points within ε of p (N_ε(p))
3. If |N_ε(p)| < MinPts: mark p as NOISE (may later change to border)
4. Else: p is a CORE point
a. Create new cluster C, add p to C
b. For each point q in N_ε(p):
- If q is unvisited, mark visited, find N_ε(q)
- If |N_ε(q)| ≥ MinPts, add N_ε(q) to seed set
- If q is not yet in any cluster, add q to C
| Property | K-Means | DBSCAN |
|---|---|---|
| K required? | Yes | No (auto-detects clusters) |
| Cluster shapes | Spherical only | Arbitrary shapes |
| Noise handling | No | Yes (identifies outliers) |
| Scalability | O(nKt) | O(n log n) with spatial index |
| Parameters | K | ε, MinPts |
4. Principal Component Analysis (PCA)
PCA is a dimensionality reduction technique that transforms data into a new coordinate system where the axes (principal components) are ordered by the amount of variance they capture.
Input: Data matrix X (n × d), desired dimensions k 1. CENTRE: Subtract the mean of each feature: X_c = X - μ 2. COVARIANCE MATRIX: Compute C = (1/(n-1)) X_c^T X_c (d × d matrix) 3. EIGENDECOMPOSITION: Find eigenvalues λ_1 ≥ λ_2 ≥ ... ≥ λ_d and corresponding eigenvectors v_1, v_2, ..., v_d of C 4. SELECT: Choose top k eigenvectors (those with largest eigenvalues) 5. PROJECT: Z = X_c · V_k where V_k = [v_1 | v_2 | ... | v_k] (d × k) Result: Z is the n × k reduced dataset
EVR(k) = λᵈ / ∑ᵤ λᵤ
The proportion of total variance explained by the k-th principal component. Cumulative EVR tells us how much total information is retained when using the top k components.
Q: The covariance matrix of a 2D dataset is [[4, 2], [2, 3]]. Find the principal components and the proportion of variance explained by the first component.
Solution:
Eigenvalues: det(C − λI) = 0 → (4−λ)(3−λ) − 4 = 0 → λ² − 7λ + 8 = 0
λ = (7 ± √(49−32))/2 = (7 ± √17)/2
λ₁ = (7 + 4.123)/2 = 5.561, λ₂ = (7 − 4.123)/2 = 1.439
Variance explained by PC1: 5.561 / (5.561 + 1.439) = 5.561 / 7 = 79.4%
For eigenvector of λ₁: (C − 5.561I)v = 0 gives direction of maximum variance.
- Principal components are orthogonal to each other
- PCA is a linear transformation — cannot capture non-linear relationships (use Kernel PCA for that)
- Features must be centred (and typically standardised) before applying PCA
- The number of non-zero eigenvalues equals the rank of the data matrix
- Sum of all eigenvalues equals the total variance in the data
5. Association Rule Mining (Apriori)
Association rules discover interesting relationships between variables in large datasets. The classic application is market basket analysis.
- Support(A): Fraction of transactions containing itemset A. Support(A) = count(A) / N
- Confidence(A→B): P(B|A) = Support(A∪B) / Support(A)
- Lift(A→B): Confidence(A→B) / Support(B). Lift > 1 indicates positive correlation.
If an itemset is infrequent, all its supersets are also infrequent. (Contrapositive: If an itemset is frequent, all its subsets must be frequent.) Algorithm: 1. Find all frequent 1-itemsets (support ≥ min_support) 2. Generate candidate k-itemsets from frequent (k-1)-itemsets 3. Prune candidates whose subsets are not all frequent 4. Scan database to count support of remaining candidates 5. Repeat until no more frequent itemsets can be found 6. Generate rules from frequent itemsets that meet min_confidence
Transactions: T1={Bread, Milk}, T2={Bread, Diapers, Beer}, T3={Milk, Diapers, Beer}, T4={Bread, Milk, Diapers, Beer}, T5={Bread, Milk, Diapers}. N=5, min_support=0.4.
Support(Bread)=4/5=0.8, Support(Milk)=4/5=0.8, Support(Diapers)=4/5=0.8, Support(Beer)=3/5=0.6
Support({Bread,Milk})=3/5=0.6 ≥ 0.4 ✓
Confidence(Bread→Milk) = 0.6/0.8 = 0.75 (75%)
Lift(Bread→Milk) = 0.75/0.8 = 0.9375 (<1, slight negative association)
6. Summary & Comparison
| Algorithm | Type | Key Strength | Key Weakness |
|---|---|---|---|
| K-Means | Partition Clustering | Fast, scalable | Fixed K, spherical clusters |
| Hierarchical | Hierarchical Clustering | No K needed, dendrogram | O(n³) time complexity |
| DBSCAN | Density Clustering | Arbitrary shapes, noise detection | Varying density is problematic |
| PCA | Dimensionality Reduction | Captures max variance, orthogonal | Linear only, loses interpretability |
| Apriori | Association Rules | Interpretable rules | Exponential candidate generation |