Unit 1: Introduction to Unsupervised Learning & K-Means
1. Foundations of the Unsupervised Learning Paradigm
1.1 Machine Learning Taxonomy and Unsupervised Learning Principles
Machine learning algorithms are traditionally classified into four primary paradigms based on the nature of the learning feedback and the presence or absence of supervisory ground-truth signals:
- Supervised Learning: The learning algorithm is provided with a labeled training dataset , where each instance is paired with a continuous target or discrete category label . The objective is to induce a hypothesis function that minimizes an empirical risk objective and generalizes accurately to unseen test distributions.
- Unsupervised Learning: The algorithm receives an unannotated sample collection consisting strictly of feature vectors without target labels . Rather than predicting an external ground truth, the objective is to uncover underlying intrinsic structures, discover latent generative factors, estimate underlying probability density functions , identify topological manifolds, or partition the data into meaningful homogeneous subsets.
- Semi-Supervised Learning: The algorithm operates over a small corpus of labeled instances augmented by a substantially larger volume of unannotated instances (where ), leveraging structural smoothness and cluster assumptions over to regularize decision boundaries.
- Self-Supervised Learning: Supervisory signals are derived automatically from the intrinsic structure of unannotated data by formulating pretext tasks (e.g., masked token reconstruction, contrastive instance discrimination, next-frame video prediction), enabling representation learning without human annotations.
CODE+-----------------------------------------------------------------------------------------+ | UNSUPERVISED LEARNING PARADIGM | +-----------------------------------------------------------------------------------------+ | Input: Unlabeled Data X in R^d | | | | +-----------------------+-------------------------+-----------------------+ | | | | | | | | v v v v | | [ Clustering ] [ Dimensionality Reduction ] [ Density Estimation ] [ Anomaly Detect ] | Group data into Project d dimensions into Estimate underlying Identify points | | cohesive subsets latent subspace k << d probability P(X) deviating from | | (e.g., K-Means, (e.g., PCA, t-SNE, UMAP, (e.g., GMMs, KDE, norm (e.g., | | DBSCAN, Hierarchical) Autoencoders) Normalizing Flows) iForest, LOF) | +-----------------------------------------------------------------------------------------+
1.2 Core Objectives of Unsupervised Learning
Unsupervised learning addresses distinct analytical challenges:
- Clustering: Discovering natural groupings within unlabeled data such that instances within the same group exhibit high internal similarity (cohesion) while instances across different groups exhibit high dissimilarity (separation).
- Dimensionality Reduction: Compressing high-dimensional feature spaces into lower-dimensional manifolds () while preserving maximal statistical variance (PCA), pairwise geometric distances (MDS), or local neighborhood topologies (t-SNE, UMAP).
- Density Estimation: Modeling the joint probability density function underlying the observed samples, facilitating synthetic data sampling and probabilistic inference.
- Anomaly and Novelty Detection: Quantifying instance deviation from expected structural or density norms to flag outliers, sensor failures, and fraudulent transactions.
- Association Rule Mining: Uncovering transactional co-occurrence patterns (e.g., Apriori, FP-Growth) across multi-item relational databases.
1.3 Mathematical Formulation of the Clustering Problem
Let represent a dataset of instances residing in a -dimensional continuous vector space . The clustering problem seeks to partition into non-empty, disjoint subsets (clusters) satisfying:
- Exhaustive Coverage: (every data point belongs to at least one cluster).
- Mutual Exclusivity (Hard Clustering): for all (no data point belongs to more than one cluster).
- Non-Triviality: for all .
Alternatively, in Soft (Fuzzy/Probabilistic) Clustering, each instance possesses a membership probability vector such that , representing the degree of belonging to each respective cluster.
1.4 Taxonomy of Clustering Algorithms
Clustering methodologies differ fundamentally in how clusters are mathematically conceptualized:
- Partitional Clustering: Partitions data directly into non-overlapping subsets without hierarchical structure by optimizing an objective function (e.g., K-Means, K-Medoids / PAM, K-Modes).
- Hierarchical Clustering: Constructs nested tree structures (dendrograms) either agglomeratively (bottom-up merging of pairs) or divisively (top-down recursive splitting) based on linkage metrics (e.g., Single, Complete, Average, Ward's linkage).
- Density-Based Clustering: Defines clusters as continuous, dense spatial regions separated by low-density noise regions, capable of discovering arbitrary non-convex geometries (e.g., DBSCAN, OPTICS, HDBSCAN).
- Distribution-Based (Probabilistic) Clustering: Assumes data instances are generated from a mixture of underlying parametric probability distributions (e.g., Gaussian Mixture Models optimized via the Expectation-Maximization algorithm).
- Grid-Based Clustering: Quantizes continuous object space into a finite number of multi-dimensional cells forming a grid structure over which clustering operations execute independently of data size (e.g., STING, CLIQUE).
- Graph-Based and Spectral Clustering: Represents pairwise instance affinities as weighted graphs, performing dimensionality reduction via graph Laplacian graph spectra before partitional clustering.
2. K-Means Clustering: Mathematical Formulation & Lloyd's Algorithm
2.1 The Optimization Objective Function (Inertia / WCSS)
K-Means is a partitional clustering algorithm that assigns observations into clusters, where each cluster is parameterized by its mean vector (centroid) .
Let denote a binary indicator variable representing cluster membership:
subject to the constraint for all .
The objective of K-Means is to find cluster assignments and centroid locations that minimize the Within-Cluster Sum of Squares (WCSS), also termed Inertia:
where denotes the standard Euclidean norm ( norm).
CODEK-MEANS INERTIA (WCSS) GEOMETRY Cluster C_1 Cluster C_2 x^(1) x^(2) x^(4) x^(5) \ / \ / \ d_1 / \ d_4 / v v v v [ mu_1 ] [ mu_2 ] ^ ^ ^ ^ / d_3 \ / d_6 \ / \ / \ x^(3) x^(N) x^(6) x^(7) WCSS = sum ||x^(i) - mu_1||^2 + sum ||x^(j) - mu_2||^2
2.2 Coordinate Descent: Lloyd's Algorithm
Minimizing simultaneously over discrete assignment variables and continuous coordinates is an NP-hard combinatorial optimization problem. Lloyd's algorithm solves this by decoupling the optimization via Block Coordinate Descent, alternating iteratively between two conditional minimization steps:
Step 1: Expectation / Cluster Assignment Step (E-Step)
Holding centroid positions fixed, minimize with respect to cluster indicator variables . Because the inner sum over is unconstrained across different observations , each instance is independently assigned to its closest centroid:
Ties are broken arbitrarily. Geometrically, this step partitions the feature space into a Voronoi tessellation generated by the centroids .
Step 2: Maximization / Centroid Update Step (M-Step)
Holding cluster assignments fixed, minimize with respect to centroid vectors . Since is convex and unconstrained with respect to , we compute the partial derivative with respect to and set it to zero:
Thus, the optimal centroid is the empirical arithmetic mean of all data points currently assigned to cluster .
CODE+-----------------------------------------------------------------------------------------+ | LLOYD'S ALGORITHM WORKFLOW | +-----------------------------------------------------------------------------------------+ | | | 1. Initialize Centroids mu_1, mu_2, ..., mu_K in R^d | | | | | v | | +-------------------> [ Assignment Step ] | | | Assign each x^(i) to nearest mu_k: | | | c^(i) = argmin_k ||x^(i) - mu_k||^2 | | | | | | | v | | | [ Centroid Update Step ] | | | Recalculate centroids as cluster means: | | | mu_k = (1 / |C_k|) * sum_{i in C_k} x^(i) | | | | | | | v | | | [ Convergence Check ] | | | Did centroids shift by < tolerance epsilon, | | | or did assignments stabilize, or iter == max_iter? | | | | | | | No | Yes | | +--------------------------------+-----------------+ | | | | | v | | [ Terminate & Output ] | | Final Clusters & Centroids | +-----------------------------------------------------------------------------------------+
2.3 Proof of Monotonic Convergence and Termination
- Monotonic Non-Increasing Cost:
- In Step 1, assigning each point to its closest centroid strictly decreases or maintains : .
- In Step 2, setting each centroid to the cluster mean minimizes the sum of squared Euclidean distances, ensuring: .
- Therefore, at every iteration :
- Finite Configuration Space:
- For a dataset of points and clusters, there are at most distinct assignments of data points to clusters.
- Because decreases strictly at every step unless assignments remain unchanged, no assignment partition can be revisited.
- Consequently, Lloyd's algorithm is guaranteed to converge to a local minimum or stationary point in a finite number of iterations.
- Non-Convexity and Local Minima:
- While the algorithm is guaranteed to terminate, the objective function is non-convex with numerous local minima, saddle points, and poor basin configurations.
- The final partition reached depends heavily on initial centroid coordinates.
- Finding the global minimum of WCSS is known to be NP-hard, even for in arbitrary dimensions, and for with arbitrary .
3. Centroid Initialization Schemes & K-Means++
3.1 Standard Initialization Techniques and Their Vulnerabilities
Early formulations of K-Means relied on naive initialization heuristics:
- Forgy Method: Randomly selects distinct observations from dataset to serve as initial centroids .
- Random Partition Method: Randomly assigns each data point to one of the clusters with uniform probability, then computes the initial cluster means. This method places all initial centroids close to the global dataset center of mass, leading to poor partition initializations.
The Pathological Initialization Trap
When initial centroids are placed close together or clustered within a single dense cluster, K-Means can become trapped in suboptimal local minima. A cluster with high variance may be split into multiple sub-clusters, while two distinct distant clusters may be forced into a single centroid.
CODEPATHOLOGICAL INITIALIZATION DESIRED OPTIMAL INITIALIZATION True Cluster A True Cluster B True Cluster A True Cluster B * * * * * * * * * * * * * * * * * * * * * (X)(X) * * * * (X) * * (X) * * * * * * * * * * * * * * * * * * * * * Two centroids Zero centroids One centroid One centroid trapped in A! assigned to B!
3.2 The K-Means++ Initialization Algorithm
To overcome initialization sensitivity, David Arthur and Sergei Vassilvitskii (2007) introduced K-Means++, which seeds initial centroids by selecting points spread out across the feature space using a distance-weighted probability distribution.
K-Means++ Algorithmic Protocol
- First Centroid: Choose the first centroid uniformly at random from dataset .
- Subsequent Centroids ():
- For each data point , compute its shortest squared Euclidean distance to any already selected centroid:
- Select the next centroid from according to the categorical probability distribution:
- For each data point , compute its shortest squared Euclidean distance to any already selected centroid:
- Repeat Step 2 until all centroids have been selected.
- Proceed with standard Lloyd's coordinate descent iterations.
CODE+-----------------------------------------------------------------------------------------+ | K-MEANS++ INITIALIZATION LOGIC | +-----------------------------------------------------------------------------------------+ | | | 1. Sample first centroid mu_1 ~ Uniform(X) | | | | 2. For k = 2 to K: | | a. For each x in X: | | Calculate D(x) = min_{j < k} ||x - mu_j|| | | | | b. Sample next centroid mu_k from distribution: | | P(x) = D(x)^2 / sum_{x'} D(x')^2 | | | | Points far from existing centroids have high D(x)^2 -> high probability of selection. | | Points close to existing centroids have low D(x)^2 -> low probability of selection. | +-----------------------------------------------------------------------------------------+
Theoretical Guarantee of K-Means++
Arthur and Vassilvitskii proved that K-Means++ initialization achieves an expected cost bound relative to the optimal clustering solution:
This competitive ratio ensures that K-Means++ is mathematically bounded from converging to catastrophically poor local minima, while simultaneously speeding up convergence by reducing the required number of coordinate descent iterations.
4. Determining the Optimal Number of Clusters ()
Because K-Means requires the practitioner to specify a priori, heuristic diagnostic metrics are necessary to evaluate partitions across candidate values .
4.1 The Inertia Dilemma & The Elbow Method
As increases, the Within-Cluster Sum of Squares (Inertia) decreases monotonically:
- When , Inertia equals the total sum of squares around the global mean.
- When , every data point is its own centroid, and Inertia reaches exactly zero ().
Therefore, minimizing Inertia directly cannot identify optimal , as it trivially favors .
The Elbow Heuristic
The Elbow Method plots Inertia against candidate values of :
- For , adding a centroid captures major underlying cluster structure, producing a steep drop in Inertia ().
- For , adding further centroids merely fragments existing clusters, producing diminishing marginal decreases in Inertia.
- The point of maximum curvature—resembling an "elbow"—indicates the parsimonious balance between model complexity and residual error.
CODEInertia J(K) ^ | \ | \ | \ Underfitting Zone (Steep drop) | \ | * <-- Optimal "Elbow" Point (K = 3) | \ | \__________ Overfitting Zone (Diminishing returns) | \________ +---------------------------------> K (Number of clusters) 1 2 3 4 5 6 7
Mathematical Determination of the Elbow Knee
In complex datasets, the visual elbow may be subtle or ambiguous. Automated knee-detection algorithms (e.g., Satopaa et al.'s Kneedle algorithm) identify the point that maximizes the orthogonal distance between the discrete curve points and the secant line connecting to .
4.2 Silhouette Analysis & Silhouette Coefficient
Silhouette Analysis provides an intrinsic validation metric that evaluates both cluster cohesion (tightness) and cluster separation (isolation) on an individual instance basis without requiring external ground truth.
Mathematical Formulation
For each observation assigned to cluster :
- Mean Intra-Cluster Distance ():
quantifies how well instance is matched to its assigned cluster (lower indicates tighter cohesion). - Mean Nearest-Cluster Distance ():
measures the distance between instance and its closest neighboring cluster (higher indicates greater separation). - Silhouette Coefficient ():
Equivalently expressed as:
CODESILHOUETTE GEOMETRY Assigned Cluster C_A Neighboring Cluster C_B +-----------------------+ +-------------------------+ | | | | | x^(j) | | x^(k) | | \ | | / | | a(i) | | / | | \ | | / | | x^(i)-------|------------|---->x b(i) | | / | | | | x^(l) | | | +-----------------------+ +-------------------------+ Intra-Cluster Nearest-Cluster Distance Distance
Silhouette Metric Range and Interpretation
The silhouette coefficient is bounded in the interval :
- : The sample is far from neighboring clusters () and tightly bound within its own cluster (excellent assignment).
- : The sample lies directly along the decision boundary between two clusters ().
- : The sample is closer to points in a neighboring cluster than to points in its assigned cluster (), signaling an erroneous assignment.
The Global Silhouette Score is the mean silhouette coefficient across all dataset instances:
The optimal cluster count is identified by maximizing the global silhouette score: .
Silhouette Diagram Interpretation
A silhouette plot visualizes sorted silhouette coefficients for each cluster:
- Cluster Balance: The relative vertical thickness of each cluster silhouette reflects the number of samples in that cluster.
- Cluster Quality: If a cluster's average silhouette score falls below the global average vertical dashed line, or contains substantial negative tails, that cluster is poorly separated or artificial.
5. Geometric Assumptions, Failure Modes, and Limitations
While computationally fast and intuitive, K-Means imposes strong structural assumptions on data distribution that can result in poor clustering when violated.
CODE+-----------------------------------------------------------------------------------------+ | K-MEANS FAILURE MODES | +-----------------------------------------------------------------------------------------+ | | | 1. Non-Convex / Ring Manifolds 2. Unequal Cluster Sizes / Densities | | * * * * * * * * * * * * * * * * | | * +-------+ * * Dense * * Sparse * | | * | Centroid| * * (X) Cluster * * (X) * | | * | falls | * * * * * * * * * * * * * * * | | * | in gap! | * Large dense cluster Centroid pulled | | * * * * * * * split arbitrarily! toward dense! | | | | 3. Elongated / Anisotropic Clusters 4. Extreme Outlier Sensitivity | | * * * * * * * * * * * * * * * * * | | (X) * mu_1 * * [ Outlier ] | | * * * * * * * * * * * * * * * * * | | | Cut across natural axis Centroid dragged toward outlier ------> | +-----------------------------------------------------------------------------------------+
5.1 Assumption of Spherical, Isotropic Clusters
K-Means implicitly assumes that:
- Clusters are spherical (isotropic): Feature variance is identical in all coordinate directions.
- Clusters have equal variance: The spatial spread is uniform across all clusters .
- Clusters have balanced sample sizes: All clusters contain roughly comparable observation counts.
This behavior stems directly from using the squared Euclidean distance metric . In probabilistic terms, K-Means is mathematically equivalent to a Gaussian Mixture Model (GMM) where all components share an identical covariance matrix constrained to the spherical form .
5.2 Failure on Non-Convex and Arbitrary Geometries
Because K-Means partitions feature space via linear Hyperplane Voronoi boundaries, it cannot capture clusters with non-convex topologies, such as:
- Concentric circles or nested rings.
- Interlocking crescents (two-moons dataset).
- Elongated, serpentine, or sinusoidal manifolds.
For non-convex geometries, density-based algorithms (DBSCAN) or spectral clustering are required.
5.3 Sensitivity to Feature Scaling
Because Euclidean distance computes squared coordinate differences , features with larger numerical magnitudes dominate the distance calculations:
- If feature spans (e.g., Annual Income) and feature spans (e.g., Credit Rating), distance calculations are dominated by , rendering statistically irrelevant.
- Mandatory Preprocessing: Features must be standardized using
StandardScaler() or scaled usingRobustScalerprior to fitting K-Means.
5.4 Sensitivity to Extreme Outliers
Because K-Means squares Euclidean distances, anomalous observations located far from the main data manifold exert large leverage on centroid calculations during the M-step. A single distant outlier can pull a centroid away from the true cluster center, sometimes isolating the outlier in its own degenerate cluster.
5.5 Handling Empty Clusters During Execution
During Lloyd's iterations, an initialization configuration may result in zero samples being assigned to a centroid (). Dividing by during the centroid update produces an arithmetic exception. Standard scikit-learn implementations handle this by re-seeding the empty centroid at the observation currently exhibiting the largest squared distance from its assigned centroid.
6. Scalability, Variations, and Alternative Formulations
| Characteristic | Standard K-Means (Lloyd) | Mini-Batch K-Means | K-Medoids (PAM) |
|---|---|---|---|
| Centroid Prototype | Arithmetic mean | Arithmetic mean | Exemplar data point |
| Distance Metric | Squared Euclidean () | Squared Euclidean () | Arbitrary (, , Cosine, Gower) |
| Computational Complexity | () | ||
| Memory Footprint | Full dataset in memory () | Small batch buffer () | Distance matrix () |
| Outlier Robustness | Low (squared error penalty) | Low (squared error penalty) | High (uses medoid medians) |
| Convergence Speed | Moderate | Fast | Slow |
6.1 Mini-Batch K-Means
To cluster web-scale datasets that exceed available RAM, D. Sculley (2010) proposed Mini-Batch K-Means. Rather than computing cluster assignments and updating centroids across the entire dataset in each iteration, Mini-Batch K-Means uses small, randomly sampled subsets (mini-batches) of size (typically ).
Online Centroid Update Mechanism
For each mini-batch of size :
- Assign each instance to its nearest existing centroid: .
- For each assigned instance , update the associated centroid using a running stochastic gradient step:
where is a per-centroid counter tracking the cumulative number of samples assigned to centroid across all prior batches.
- Advantages: Drastically reduces disk I/O and RAM overhead, achieving an order-of-magnitude reduction in computation time with minimal degradation in clustering quality (typically within 1–3% of standard K-Means inertia).
6.2 K-Medoids (Partitioning Around Medoids - PAM)
In standard K-Means, the centroid is a virtual point calculated as the arithmetic mean, which may not correspond to any actual observation and is sensitive to outliers.
- K-Medoids restricts each cluster center to be an actual observation from the dataset (termed a medoid):
- Objective Function: Minimizes the sum of dissimilarities using arbitrary distance metrics (e.g., Manhattan , Cosine, or Jaccard distances):
- Robustness: Because it uses medoids and -style dissimilarities rather than squared Euclidean distances, K-Medoids is less sensitive to extreme outliers.
6.3 K-Modes and K-Prototypes for Categorical & Mixed Data
- K-Modes (Huang, 1998): Replaces the Euclidean distance metric with a simple matching dissimilarity measure:
Centroids are represented by cluster modes (the most frequent categorical attribute values) rather than means. - K-Prototypes: Combines K-Means and K-Modes using a weighted objective function:
where is a balance hyperparameter penalizing categorical mismatches.
7. Scikit-Learn Implementation Architecture
7.1 Production Clustering Pipeline
The following script demonstrates standard preprocessing, K-Means++ clustering, silhouette diagnostics, and elbow evaluation using Scikit-Learn:
pythonimport numpy as np
import pandas as pd
from sklearn.cluster import KMeans, MiniBatchKMeans
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import silhouette_score, silhouette_samples
from sklearn.datasets import make_blobs
# 1. Generate Synthetic Data
X, y_true = make_blobs(
n_samples=2000,
n_features=6,
centers=4,
cluster_std=1.2,
random_state=42
)
# 2. Mandatory Feature Scaling
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# 3. Model Instantiation & Fitting
kmeans = KMeans(
n_clusters=4,
init='k-means++', # K-Means++ seeding protocol
n_init=10, # 10 independent restarts with distinct seeds
max_iter=300, # Maximum coordinate descent iterations per run
tol=1e-4, # Convergence threshold for centroid shift
algorithm='lloyd', # Standard Lloyd coordinate descent
random_state=42
)
labels = kmeans.fit_predict(X_scaled)
centroids = kmeans.cluster_centers_
inertia = kmeans.inertia_
print(f"Final WCSS (Inertia): {inertia:.2f}")
# 4. Silhouette Validation Metric
sil_score = silhouette_score(X_scaled, labels)
print(f"Mean Silhouette Coefficient: {sil_score:.4f}")
# 5. Mini-Batch K-Means for Streaming / Scalability
minibatch_kmeans = MiniBatchKMeans(
n_clusters=4,
init='k-means++',
batch_size=256,
max_iter=100,
random_state=42
)
mb_labels = minibatch_kmeans.fit_predict(X_scaled)
print(f"Mini-Batch WCSS (Inertia): {minibatch_kmeans.inertia_:.2f}")
7.2 Parameter Reference Guide
n_clusters(default=8): The number of clusters and centroids to generate.init('k-means++','random', or array): Seeding method.'k-means++'is default and recommended.n_init(default=10): Number of times the algorithm runs with distinct centroid seeds. The run with the lowest WCSS/Inertia is chosen.max_iter(default=300): Maximum iterations of the Lloyd coordinate descent per run.tol(default=1e-4): Relative tolerance with respect to Frobenius norm of difference in centroid positions to declare convergence.algorithm('lloyd','elkan'):'lloyd'uses standard coordinate descent;'elkan'uses triangular inequality bounds to accelerate convergence on dense datasets.