Clustering and Unsupervised Machine Learning
Introduction to Clustering
Clustering is an unsupervised learning technique that partitions data instances into meaningful groups called clusters.
A cluster contains data instances that are more similar to each other than they are to data instances in other clusters.
Clustering differs from classification in several ways:
The goal of classification is to learn a model or function that can assign the correct class label to an unseen data instance. In classification, historical instances with known target values are used to learn patterns that separate classes.
In clustering, prior knowledge of class membership is not known but is rather discovered.
Like classification, clustering assigns discrete values to data instances.
Clustering can be used as a stand-alone tool for data exploration or as a pre-processing step for other algorithms.
Common applications of clustering include:
Customer segmentation: Identifying different customer groups for product targeting.
Text collection organization: Grouping documents into previously unknown topics.
Data aggregation: Representing multiple data instances with a single representative example.
Imputation: Replacing missing values by using representative instances.
A practical example involves Diagnostic-Related Groupings (DRGs). Medical insurance companies use DRGs to determine standard treatment costs. Hospitals may assign incorrect DRGs to obtain higher reimbursements. Fraud detection is difficult because fraud cases are not clear outliers, some hospitals have naturally higher claims, and fraud behavior changes over time. Clustering groups similar hospitals so that outliers within those groups can be investigated.
Methodology: CRISP-DM for Clustering
The CRoss Industry Standard Process for Data Mining (CRISP-DM) is applied to clustering through six phases:
Data Understanding and Data Preparation: An analytical base table is created. This table does not require a target feature. Clustering is sensitive to data quality, so issues must be fixed here.
Modelling: Identifying and applying the appropriate clustering algorithm.
Evaluation: Found clusters are evaluated and interpreted.
Deployment: The algorithm is deployed as a stand-alone or integrated process.
Modeling Phase: Clustering Approaches
Different algorithms define and form clusters differently:
Centroid-based: Iterative algorithms where similarity is derived from closeness to a cluster centroid.
Connection-based: Based on the notion that points closer in data space exhibit more similarity than those further away.
Density-based: Assigns areas separated by non-dense areas to different clusters.
Probability-based: Based on the probability that data instances belong to the same distribution.
Algorithm selection considers:
Size of data set: Computationally expensive algorithms only suit small data sets.
Data type and quality: Most algorithms require continuous features and are sensitive to noise.
Clustering output: Not all algorithms can identify clusters of any shape.
Similarity Measures
A similarity measure compares two instances and quantifies how similar or different they are.
Functions typically use low values to indicate dissimilarity and large values to indicate similarity. However, when using distance as a metric, lower values indicate similarity.
Numerical Data Measures
Euclidean distance: The distance between instance and in an -dimensional feature space.
Manhattan distance (L1 norm):
Minkowski distance: A family of distance metrics including Euclidean () and Manhattan ().
Larger values place more emphasis on large differences between feature values.
Data Specific Measures
Binary data: Calculated as the proportion of features that are not equal.
is where is 0 and is 1.
is where is 1 and is 0.
is where both are 0, and is where both are 1.
Ordinal data: Assign a numerical value (0 to 1) to categories/ranks. Distance is the absolute difference.
Categorical data: Calculated as the portion of non-matching features.
, where is the number of features and is the number of matches.
Mixed data types: Weighted combinations of distance measures are used. Gower’s distance is standard when features have equal importance:
If categorical: 0 if , else 1.
If interval scale: , where is the feature range.
If ordinal: .
Text documents: Cosine similarity considers the angle between vectors rather than magnitude, which helps when comparing documents of different lengths.
Correlation: Used in genetics, treating instances as similar if their feature values are highly correlated regardless of numerical magnitude.
Dynamic Time Warping (DTW): Used for audio or time series to find the optimal alignment by warping the time domain.
Partition-Based Clustering: K-Means
K-means divides instances into disjoint clusters.
Goal: Minimize the sum of squared error.
K-Means Algorithm
Select random cluster centroids, to .
Repeat:
Calculate the distance of each instance to each centroid.
Assign each instance to the nearest centroid cluster .
Update each centroid to the average feature values of its assigned instances.
Until no instances change clusters (convergence).
K-Means++ Initialization
Random initialization can lead to local minima (or stationary points).
K-means++ algorithm:
Select the first centroid uniform randomly from data instances.
For remaining centroids to :
Calculate selection weights for each instance: .
Choose the next centroid randomly based on this weight distribution (higher probability for points further away).
Selecting K
Elbow Method: Run k-means multiple times with different . Plot SSE versus . The "elbow" of the graph indicates a good value where SSE decrease rate slows.
X-Means Algorithm:
Start with a value for .
Apply k-means locally.
Split cluster centroids into two along a random vector.
Accept the new pair if splitting improved the Bayesian Information Criterion (BIC).
K-Means Limitations
Incorrect clustering occurs with:
Different cluster sizes.
Different densities (dense areas may be split inappropriately to reduce SSE).
Non-spherical shapes.
Features on different scales. Descriptive features with larger values (e.g., height in cm vs. feet) will be emphasized and can dominate distance equations.
Pre-processing involves scaling/normalizing features, encoding categorical data, and eliminating outliers.
Post-processing includes splitting clusters with high SSE, merging close clusters, or deleting small outlier clusters.
K-Medoid Clustering (PAM)
Partitioning Around Medoids (PAM) addresses k-means sensitivity to outliers and its inability to use arbitrary distances.
A medoid is the actual data instance within a partition that has the minimum distance to all other instances in that partition.
Algorithm:
Specify and select instances as medoids.
Assign instances to the nearest medoid.
For each cluster, determine a new medoid (the instance with the lowest cost).
Repeat until medoids stabilize.
Hierarchical Clustering
Learns a hierarchy of clusters rather than a "flat" structure.
Agglomerative (Bottom-up): Starts with every instance in its own cluster and merges them sequentially.
Divisive (Top-down): Starts with all instances in one cluster and splits recursively (more computationally expensive).
Dendrograms
Dendrograms visualize hierarchical clustering results.
X-axis shows instances; Y-axis shows a similarity/merging measure.
Horizontal lines represent merges. The height of the merge is proportional to how similar/dissimilar clusters are.
Cutting the dendrogram horizontally at a specific height yields a discrete number of clusters.
Linkage Methods (Group-based Proximity)
Single Link: Distance between clusters is the distance between the closest pair of instances.
Suffers from "chaining," where elongated, undesirable clusters form because merges are strictly local.
Complete Link: Distance is the distance between the furthest pair of instances.
Tends to produce compact spherical clusters but struggles with varying densities.
Average Link: Distance is the average of differences between all instance pairs across the two clusters.
DIANA (Divisive ANAlysis) Algorithm
Create one cluster containing all data instances.
Identify the instance with the greatest average distance from all other instances in the cluster.
Splinter this instance into a new cluster.
Move instances from the original cluster to the new cluster if they are on average closer to the new cluster than the old one.
Repeat until every instance is isolated.
Cluster Evaluation and Tendency
Cluster Tendency Analysis: Determining if data contains patterns or is random before clustering.
Hopkins Statistic: Compares sample distances () and random uniform distribution distances ().
Statistic indicates clusters; indicates random data.
Visual Inspection: Uses an Ordered Dissimilarity Matrix (ODM). Heatmaps of the ODM show structured blocks if data is not random.
Internal Cluster Metrics
Internal metrics evaluate clustering without ground truth labels, focusing on compactness, separation, and connectivity.
Dunn Index: Dividies minimum cluster separation by maximum cluster diameter.
Silhouette Score (): Measures how well instance belongs to its own cluster.
: Average distance from to other members of its cluster.
: Lowest average distance from to any other cluster.
Overall score . Small scores indicate points between clusters.
Cluster Validation and Interpretation
Bootstrap Evaluation/Cluster Stability: Checks if results are consistent across data subsamples.
Draw a subsample with replacement (bootstrapping).
Apply clustering.
Calculate Jaccard similarity coefficient between original and new clusters.
Mean Jaccard coefficient suggests an unstable cluster.
Jaccard Similarity Index: .
Summary Statistics: Generating means or counts per cluster to see characterizing features (e.g., "Cluster 1 has low petal length").
Parallel Coordinate Plots: Each vertical line represents a feature; horizontal lines connect feature values for individual data instances to visualize cluster trends.