Lecture 06: Cluster Analysis (Unsupervised Learning)
Source Material:
materials/DA08 - Clustering.pdf/materials/DA08 - Clustering.md
Course: Introduction to Data Analytics (CE KMITL)
Topics: Unsupervised Clustering, Distance Metrics, K-Means Algorithm, Sum of Squared Errors (SSE), DBSCAN, Cluster Validation, Dimensionality Reduction (PCA/SVD)
1. Overview of Cluster Analysis
1.1 What is Clustering?
Cluster Analysis (Clustering) is an unsupervised learning technique that partitions an unlabelled dataset into natural subgroups (clusters). Unlike supervised learning (regression and classification), clustering algorithms do not receive target output labels (). Instead, the objective is discovered purely from patterns, relationships, and geometric structures in the feature space.
- Intra-cluster similarity: Data objects assigned to the same cluster should be as close or similar to one another as possible (minimized intra-cluster distance).
- Inter-cluster dissimilarity: Data objects belonging to different clusters should be as distinct and separated as possible (maximized inter-cluster distance).
1.2 Ambiguity in Cluster Boundaries
The true number of clusters in a dataset is often inherently ambiguous. For example, depending on the scale of observation or business context:
- Viewing data globally may suggest 2 clusters.
- Viewing intermediate sub-structures may suggest 4 clusters.
- Viewing fine-grained local density peaks may suggest 6 clusters.
This ambiguity necessitates formal mathematical distance metrics and objective validation criteria.
1.3 Taxonomy of Clustering Approaches
Clusterings and clustering algorithms can be categorized across several key dimensions:
| Dimension | Category | Core Characteristics |
|---|---|---|
| Hierarchical vs. Partitional | Partitional Clustering | Divides data into non-overlapping subsets such that each data point belongs to exactly one cluster (e.g., K-Means). |
| Hierarchical Clustering | Constructs a nested tree of clusters (dendrogram) from single points up to a single root cluster (Agglomerative or Divisive). | |
| Cluster Shape / Model | Center-Based | An object belongs to the cluster whose center (centroid or medoid) is closest (e.g., K-Means, K-Medoids / PAM). |
| Density-Based | A cluster is a dense region of points separated from other clusters by regions of low density (e.g., DBSCAN). | |
| Exclusivity | Exclusive (Hard) | Each point belongs strictly to one cluster. |
| Non-Exclusive (Overlapping) | Points can belong simultaneously to multiple clusters (e.g., border points or multi-topic documents). | |
| Fuzziness | Non-Fuzzy (Crisp) | Binary membership: point is either in cluster () or not (). |
| Fuzzy (Soft) | Probabilistic membership: weights sum to 1 (), as in Fuzzy C-Means. | |
| Completeness | Complete | Every data point in the dataset is assigned to a cluster. |
| Partial | Some points may be left unassigned as background noise or outliers (e.g., DBSCAN). |
2. Distance and Proximity Metrics
Clustering algorithms rely on proximity measures to quantify similarity or dissimilarity between data points and in a -dimensional feature space.
2.1 Euclidean Distance ( Norm)
The standard straight-line geometric distance between two points:
2.2 Manhattan Distance ( Norm / City Block)
The grid-based rectilinear distance:
2.3 General Minkowski Distance ( Norm)
A generalized metric family parameterized by :
When , it becomes Manhattan distance; when , it becomes Euclidean distance; when , it becomes Chebyshev distance ().
Pre-processing Prerequisite: Because distance formulas sum squared or absolute feature differences, variables with larger raw magnitudes dominate the distance calculations. Continuous features must be normalized (via Min-Max scaling or Z-score standardization) prior to clustering.
3. K-Means Clustering Algorithm
3.1 Algorithm Overview
K-Means (commonly implemented via Lloyd’s Algorithm) is an iterative, partitional, center-based clustering algorithm. Given an unlabelled dataset and a pre-specified number of clusters , the algorithm partitions into disjoint clusters .
3.2 Objective Cost Function: Sum of Squared Errors (SSE)
The mathematical objective of K-Means is to find cluster assignments and centroids that minimize the Sum of Squared Errors (SSE):
where:
- is the number of clusters.
- is the set of data points belonging to cluster .
- is the centroid (mean vector) of cluster :
The recomputation of as the arithmetic mean mathematically guarantees the minimization of SSE for Euclidean distance.
3.3 Step-by-Step 1D Worked Example
Consider a 1-dimensional dataset containing 5 points:
We want to partition into clusters: Cluster and Cluster .
Initial Setup (Round 0)
- Random initial centroid locations: , .
Consolidated Iteration Walkthrough Table
The table below deduplicates and synthesizes the progressive iteration sequence into a single unified step-by-step record:
| Round | Centroid | Centroid | Distance to and for each point | Point Assignments | New Centroid Calculation | Convergence Check |
|---|---|---|---|---|---|---|
| 0 | (init) | (init) | • : vs • : vs • : vs • : vs • : vs |
• • |
Initial state | |
| 1 | • : vs • : vs • : vs • : vs • : vs |
• • |
Point flipped from to ! Continues. | |||
| 2 | • : vs • : vs • : vs • : vs • : vs |
• • |
Centroid locations did not change! | |||
| 3 | Identical distances and assignments as Round 2. | , | CONVERGED (Algorithm terminates). |
SSE Evaluation of the Final Clustering:
For Cluster with centroid :
For Cluster with centroid :
Total Final SSE:
3.4 Limitations of K-Means
While computationally fast ( where is iterations), K-Means has several well-documented drawbacks:
- Vulnerability to Initial Seeds: Bad initial centroids can trap the algorithm in poor local minima or create empty clusters. (Remedy: K-Means++ initialization).
- Differing Cluster Sizes & Densities: K-Means assumes clusters have roughly equal variance and density. When a dense cluster sits next to a sparse cluster, K-Means splits the sparse cluster or merges parts of both.
- Non-Globular (Non-Convex) Shapes: K-Means uses Euclidean distance, which inherently forms convex Voronoi cells. It fails on concentric circles, interlocking spirals, or crescent shapes.
- Sensitivity to Outliers: Extreme points dramatically distort the arithmetic mean calculation of centroids.
3.5 Selecting the Optimal Number of Clusters ()
1. The Elbow Method
Plot the objective cost () as a function of :
- As increases from to , SSE monotonically decreases (reaching when ).
- We look for an elbow point: the value of where the rate of decrease drops sharply, indicating diminishing returns for adding further clusters.
2. The Silhouette Coefficient
The Silhouette Coefficient measures how well each point is matched to its own cluster compared to neighboring clusters without requiring ground truth labels.
For each data point :
- : The average distance from point to all other points in the same cluster (intra-cluster distance).
- : The minimum average distance from point to all points in any other single cluster (nearest-cluster distance).
The silhouette score for point is:
Interpretation of :
- : The point is well inside its own cluster and far from neighbors ().
- : The point lies on or very near the decision boundary between two clusters ().
- : The point has likely been assigned to the wrong cluster ().
The global Mean Silhouette Score across all points provides an effective metric to select the optimal .
4. DBSCAN (Density-Based Spatial Clustering of Applications with Noise)
4.1 Foundational Concept
DBSCAN identifies clusters as contiguous regions of high point density separated by regions of low density. Unlike K-Means, DBSCAN:
- Does not require specifying the number of clusters in advance.
- Can discover clusters of arbitrary, non-globular shapes.
- Explicitly detects and isolates noise points and outliers.
4.2 Key Hyperparameters
DBSCAN requires two essential parameters:
- (Eps / Radius): The maximum neighborhood distance to scan around any given point.
- (Minimum Points): The minimum number of points required within the -neighborhood of a point (including the point itself) to form a dense region.
The -neighborhood of point is defined as:
4.3 Point Classifications
DBSCAN categorizes every data point into one of three distinct types:
-
Core Point: A point is a Core Point if its -neighborhood contains at least points:
Core points reside in the interior of a cluster.
-
Border Point: A point is a Border Point if it has fewer than neighbors (), but falls within the -neighborhood of at least one Core Point . Border points form the outer boundaries of clusters.
-
Noise Point (Outlier): A point that is neither a Core Point nor a Border Point. It belongs to no cluster.
4.4 Density Reachability and Connectivity
To formally group points into clusters, DBSCAN establishes connectivity relations:
-
Directly Density-Reachable: Point is directly density-reachable from point with respect to and if:
- is a Core Point.
- (i.e., ).
-
Density-Reachable: Point is density-reachable from point if there exists an ordered chain of points where and such that each is directly density-reachable from . (This relation is asymmetric when ending on a border point).
-
Density-Connected: Point is density-connected to point if there exists a common core point such that both and are density-reachable from . (This relation is symmetric).
A DBSCAN Cluster is defined as a maximal set of density-connected points.
4.5 Algorithmic Steps of DBSCAN
- Label all points as Core, Border, or Noise based on their -neighborhood point count.
- Eliminate all Noise points from initial cluster consideration.
- For each unvisited Core point :
- Spawn a new cluster .
- Find all points that are density-connected to (using Breadth-First or Depth-First neighborhood expansion) and add them to .
- Assign each Border point to the cluster of its closest Core point.
- Remaining unassigned points are designated as Noise.
4.6 Comparative Summary: K-Means vs. DBSCAN
| Property | K-Means | DBSCAN |
|---|---|---|
| Number of Clusters () | Must be explicitly specified in advance | Determined automatically by the algorithm |
| Cluster Geometry | Spherical, convex, globular clusters | Arbitrary shapes (crescents, rings, spirals) |
| Noise & Outlier Handling | Highly sensitive; all points forced into clusters | Robust; isolates noise points automatically |
| Handling Varied Density | Struggles with varying densities | Fails when clusters have significantly different densities |
| Key Parameters | (number of clusters) | (neighborhood radius) and |
| Computational Complexity | (Very fast) | with spatial indexing (e.g. k-d tree), worst case |
5. Cluster Validation Concepts
Cluster validation evaluates the objective quality, validity, and statistical reliability of clustering results.
5.1 The Three Validation Indices
-
External Index: Measures the agreement between the discovered cluster labels and an externally provided set of true class labels (ground truth).
- Examples: Entropy, Purity, Rand Index, Adjusted Mutual Information (AMI).
- Useful when evaluating clustering algorithms on labeled benchmark datasets.
-
Internal Index: Evaluates the goodness of a clustering structure using only the data itself, without reference to any external labels.
- Examples: Sum of Squared Errors (SSE), Silhouette Coefficient, Davies-Bouldin Index, Calinski-Harabasz Index.
-
Relative Index: Used to compare two different clusterings generated by varying parameter values (e.g., comparing vs , or comparing K-Means vs DBSCAN). Often implemented using an internal or external index as the criterion.
5.2 Measuring Cluster Validity via Matrix Correlation
A classic internal validation approach correlates the Proximity Matrix with an Ideal Similarity Matrix:
- Proximity Matrix (): An matrix where entry records the pairwise distance between points.
- Ideal Similarity Matrix (): An matrix defined by cluster assignments:
- Correlation Calculation:
Compute Pearson’s correlation coefficient between the upper triangular entries ( pairs) of and :
- A strong correlation indicates that points belonging to the same cluster are geometrically close, while points in different clusters are distant.
- Ordering the similarity matrix rows and columns according to cluster labels produces a clear block-diagonal pattern for well-separated clusters.
6. Dimensionality Reduction: PCA and SVD
6.1 The Curse of Dimensionality
Real-world datasets often possess hundreds or thousands of features (e.g., text document term vectors, genetic markers, image pixel matrices). High dimensionality causes severe problems:
- Data Sparsity: The volume of the feature space grows exponentially, causing all points to become equidistant from each other (rendering distance-based metrics meaningless).
- Computational Bottlenecks: Time complexity scales with feature count .
- Redundancy and Noise: Many features are correlated or irrelevant, obscuring genuine cluster boundaries.
6.2 Latent Factor Models and SVD
Dimensionality reduction assumes that the observed high-dimensional data actually resides near a lower-dimensional latent subspace.
Singular Value Decomposition (SVD) factorizes an centered data matrix into three matrices:
where:
- is an orthogonal matrix (left singular vectors representing data points in latent space).
- is an diagonal matrix containing singular values (measuring the variance explained by each factor).
- is a orthogonal matrix (right singular vectors representing feature loadings).
6.3 Principal Component Analysis (PCA)
Principal Component Analysis (PCA) is an unsupervised linear technique that projects data onto orthogonal axes (Principal Components) that successively maximize the variance of the data:
- The 1st Principal Component () aligns with the direction of maximal variance.
- The 2nd Principal Component () is orthogonal to and maximizes remaining variance.
# Practical Dimensionality Reduction Pipeline with Scikit-Learn
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
# 1. Standardize features (essential prior to PCA)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# 2. Reduce dimensionality to 2 Principal Components for 2D visualization
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X_scaled)
# 3. Cluster in the reduced latent space
kmeans = KMeans(n_clusters=3, random_state=42)
labels = kmeans.fit_predict(X_pca)
By reducing high-dimensional data (such as the 4D Iris dataset or 1000D customer embeddings) to 2D or 3D, PCA enables direct human visualization of discovered clusters while eliminating noise.
7. Review and Key Takeaways
- Clustering groups unlabelled data such that intra-cluster similarity is maximized and inter-cluster similarity is minimized.
- K-Means iteratively assigns points to the nearest centroid and recomputes centroids as the mean of assigned points, minimizing the Sum of Squared Errors (SSE).
- The Elbow Method and Silhouette Coefficient provide objective criteria to determine the optimal cluster count .
- DBSCAN discovers clusters of arbitrary shapes and isolates outliers based on density parameters ( and ), categorizing points as Core, Border, or Noise.
- Cluster validity is measured via External Indices (against true labels), Internal Indices (SSE, Silhouette, Proximity-Similarity Correlation), and Relative Indices.
- PCA mitigates the curse of dimensionality by projecting data onto orthogonal directions of maximum variance prior to clustering and visualization.