Unsupervised Learning

GATE Relevance: Medium

🎯 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.

K-Means Algorithm (Lloyd’s Algorithm)
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
GATE Numerical: K-Means Step-by-Step

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

Silhouette Coefficient

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.

K-Means Limitations
  • 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)

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

LinkageDistance Between ClustersProperties
Singlemin distance between any two pointsCan find elongated clusters; sensitive to noise (chaining effect)
Completemax distance between any two pointsCompact clusters; sensitive to outliers
AverageAverage distance between all pairsCompromise between single and complete
Ward’sIncrease in WCSS after mergingMinimises variance; tends to create equal-sized clusters
GATE Numerical: Agglomerative Clustering

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.

Key Concepts
  • ε (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
DBSCAN Algorithm
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
PropertyK-MeansDBSCAN
K required?YesNo (auto-detects clusters)
Cluster shapesSpherical onlyArbitrary shapes
Noise handlingNoYes (identifies outliers)
ScalabilityO(nKt)O(n log n) with spatial index
ParametersKε, 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.

PCA Algorithm
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
Explained Variance Ratio

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.

GATE Numerical: PCA

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.

Key PCA Properties
  • 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.

Key Metrics
  • 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.
Apriori Principle
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
Example: Market Basket

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

AlgorithmTypeKey StrengthKey Weakness
K-MeansPartition ClusteringFast, scalableFixed K, spherical clusters
HierarchicalHierarchical ClusteringNo K needed, dendrogramO(n³) time complexity
DBSCANDensity ClusteringArbitrary shapes, noise detectionVarying density is problematic
PCADimensionality ReductionCaptures max variance, orthogonalLinear only, loses interpretability
AprioriAssociation RulesInterpretable rulesExponential candidate generation