Module 21

Clustering Analysis

Finding natural groups in data

Unsupervised Learning

  • 01

    Distance Metrics

    Measuring similarity between observations

  • 02

    K-Means

    Partitioning into k clusters

  • 03

    Hierarchical

    Building cluster trees

  • 04

    Validation

    Evaluating cluster quality

01

What is Clustering?

Grouping Without Labels

Before Clustering
→
After Clustering

Clustering is unsupervised learning - we don't have predefined labels. The goal is to discover natural groupings where observations within a cluster are similar to each other and different from observations in other clusters. It's about finding structure in unlabeled data.

Real-World Uses

Customer Segmentation
Group customers by behavior for targeted marketing
Image Compression
Reduce colors by clustering similar pixels
Document Organization
Group similar documents by topic
Anomaly Detection
Find points that don't fit any cluster
Gene Expression
Group genes with similar expression patterns
Market Research
Identify consumer segments

Clustering applies wherever you want to discover groups: customer segments for marketing, patient subgroups for medicine, document topics for search, fraud patterns for detection. It's exploratory - revealing structure you didn't know existed.

Supervised vs Unsupervised

Classification (Supervised)
Labels are known in advance
Goal: predict labels for new data
Example: spam/not-spam
Clustering (Unsupervised)
No predefined labels
Goal: discover natural groups
Example: customer segments

Classification learns from labeled examples to predict categories. Clustering discovers categories without labels. Classification asks 'which known group?'; clustering asks 'what groups exist?'. Different goals, different methods, complementary uses.

02

Distance Metrics

Straight-Line Distance

A
B
d = √[(x₂-x₁)² + (y₂-y₁)²]
Pythagorean theorem in n dimensions

Euclidean distance is the straight-line distance between two points. It's the most common metric, intuitive and works well when features are continuous and on similar scales. Sensitive to scale differences - standardize features first.

City-Block Distance

d = |x₂-x₁| + |y₂-y₁|
Sum of absolute differences (L1 norm)

Manhattan distance measures the path along grid lines, like walking city blocks. It's the sum of absolute differences. More robust to outliers than Euclidean. Good when features represent different things (can't be combined via Pythagorean theorem).

Angular Similarity

θ
cos(θ) = (A·B) / (|A||B|)
Measures angle, ignores magnitude

Cosine similarity measures the angle between vectors, ignoring their length. Two documents with the same word proportions but different lengths are similar by cosine. Ideal for text analysis, recommendations, and high-dimensional sparse data.

Which Distance to Use?

Use CaseBest Metric
Continuous features, similar scalesEuclidean
Features on different scalesManhattan
Text / document similarityCosine
Binary featuresJaccard
Mixed typesGower
Rule: Always standardize for Euclidean!

Distance choice matters. Euclidean for continuous, standardized features. Manhattan for mixed scales or outlier robustness. Cosine for text and sparse data. Jaccard for binary (presence/absence). Gower for mixed data types. The wrong metric gives meaningless clusters.

03

K-Means Clustering

How K-Means Works

1
Choose k (number of clusters)
2
Initialize k centroids randomly
3
Assign each point to nearest centroid
4
Update centroids to cluster means
5
Repeat 3-4 until convergence

K-means iteratively assigns points to clusters and updates cluster centers. It minimizes within-cluster variance (sum of squared distances to centroid). Simple, fast, scales well to large datasets. But requires choosing k and sensitive to initialization.

K-Means in Action

Iteration 1
Iteration 2
Converged
Squares = centroids; Circles = data points

Watch centroids move: start random, points get assigned to nearest centroid, centroids move to cluster centers, repeat. Centroids converge when assignments stop changing. Different initializations can give different results - run multiple times.

The Elbow Method

1
2
3
4
5
6
Elbow: Plot within-cluster SS vs k. Look for the 'elbow' where adding clusters stops helping much.

The elbow method plots within-cluster sum of squares against number of clusters. More clusters always reduce error, but at diminishing returns. The 'elbow' where the curve bends suggests a good k - beyond that, you're just splitting natural groups.

When K-Means Fails

✗ Non-spherical
✗ Different sizes
✗ Different densities
✗ Outliers
K-means assumes spherical, equal-sized clusters. Use DBSCAN or GMM for complex shapes.

K-means assumes clusters are spherical and similar in size. It struggles with elongated clusters, clusters of different densities, and is very sensitive to outliers (which pull centroids). For complex cluster shapes, consider DBSCAN or Gaussian Mixture Models.

04

Hierarchical Clustering

Building a Cluster Tree

A
B
C
D
E
Dendrogram: height = distance at merge

Hierarchical clustering builds a tree (dendrogram) of nested clusters. Start with each point as its own cluster, then repeatedly merge the closest clusters until one remains. Cut the tree at any height to get different numbers of clusters. No need to prespecify k.

How to Measure Cluster Distance

Single Linkage
Minimum distance between any two points
→ Can create long chains
Complete Linkage
Maximum distance between any two points
→ Compact, spherical clusters
Average Linkage
Average of all pairwise distances
→ Compromise approach
Ward's Method
Minimize within-cluster variance
→ Often best choice

Linkage determines how cluster distance is measured. Single linkage uses minimum distance (can create chains). Complete uses maximum (compact clusters). Average is a compromise. Ward's minimizes variance increase when merging - often produces the most interpretable clusters.

Choosing Number of Clusters

Cut here → 3 clusters
Cut the dendrogram horizontally at desired height. Higher cut = fewer clusters. Look for large vertical gaps (natural cluster boundaries).

Cut the dendrogram at any height to get clusters. Large vertical gaps indicate natural cluster boundaries - cut there. Unlike k-means, you can explore multiple cluster solutions from one dendrogram. Height of merge indicates dissimilarity.

Comparing Methods

FeatureK-MeansHierarchical
Specify k?Yes, upfrontNo, decide later
ScalabilityVery large nModerate n
Cluster shapesSphericalAny (varies)
VisualizationScatter plotDendrogram
Deterministic?No (random init)Yes

K-means is fast and scales well but needs k upfront. Hierarchical is slower (O(n²) space) but gives rich structure via dendrogram and doesn't need k. Use k-means for large datasets, hierarchical for interpretability and exploring cluster structure.

05

Cluster Validation

Silhouette Score

s(i) = (b - a) / max(a, b)
a = avg distance to same cluster; b = avg distance to nearest other cluster
s ≈ 1: well-clustered | s ≈ 0: boundary | s < 0: wrong cluster

Silhouette score measures how similar a point is to its own cluster versus other clusters. Ranges from -1 to 1. High values mean points are well-matched to their cluster. Average silhouette across all points measures overall clustering quality.

Internal Validation Metrics

Within-Cluster SS (WSS)
Total squared distance to centroids
Lower = tighter clusters
Between-Cluster SS (BSS)
Spread between cluster centers
Higher = more separated
Calinski-Harabasz Index
BSS/WSS ratio (adjusted for k)
Higher = better defined clusters

Internal metrics evaluate clustering without external labels. WSS measures compactness (want low). BSS measures separation (want high). Calinski-Harabasz balances both. Davies-Bouldin index measures cluster similarity (want low). Use multiple metrics.

External Validation

When you have true labels: Compare clusters to known categories
Adjusted Rand Index
Agreement between clusterings
1 = perfect, 0 = random
Normalized Mutual Info
Shared information
1 = perfect, 0 = independent

External validation compares clusters to known labels (if available). Adjusted Rand Index measures agreement corrected for chance. Normalized Mutual Information measures shared information. Use these to evaluate if clustering recovers known structure.

Cluster Stability Analysis

Bootstrap Stability Check:
1. Resample data with replacement
2. Cluster resampled data
3. Compare to original clusters
4. Repeat many times
Stable clusters: Consistently recovered across resamples
Unstable: Vary significantly → may not be real

Stability analysis tests if clusters are robust or artifacts of particular data. Resample and recluster many times. Stable clusters appear consistently. If membership changes drastically, clusters may not reflect real structure - try different k or methods.

★

Real-World Examples

Apply your knowledge to practical scenarios

01

Retail Customer Segmentation

A retailer has data on 10,000 customers: total purchases ($), visit frequency, recency (days since last purchase). They want to segment customers for targeted marketing. K-means with k=4 yields clusters.

Sample Data
{
  "cluster1": {
    "name": "High-Value Loyalists",
    "avg_spend": "$2,500",
    "frequency": "15/month",
    "recency": "3 days"
  },
  "cluster2": {
    "name": "At-Risk VIPs",
    "avg_spend": "$2,000",
    "frequency": "8/month",
    "recency": "45 days"
  },
  "cluster3": {
    "name": "Occasional Shoppers",
    "avg_spend": "$200",
    "frequency": "2/month",
    "recency": "20 days"
  },
  "cluster4": {
    "name": "Churned",
    "avg_spend": "$500",
    "frequency": "1/month",
    "r
Q How should the retailer use Cluster 1 (High-Value Loyalists)? +
A Reward and retain! They're the best customers. Offer VIP perks, exclusive previews, thank you gifts. Don't annoy with excessive marketing—they're already engaged.
Q Cluster 2 shows high spend but declining recency. What action? +
A Urgent win-back campaign! These 'At-Risk VIPs' used to be valuable but are slipping away. Send personalized offers, ask for feedback, investigate why they're disengaging.
Q Should equal marketing budget go to all clusters? +
A No! Allocate by potential ROI. Cluster 2 (At-Risk VIPs) may have highest ROI—they're proven high-spenders who need re-engagement. Cluster 4 (Churned) may not be worth the investment.
Q How do you know k=4 is the right number of clusters? +
A Use elbow method (plot within-cluster variance vs k), silhouette analysis, or domain knowledge. There's no 'correct' k—it depends on business utility. 3-6 segments are often manageable for marketing.
Key Insights
  • Clustering reveals actionable customer segments
  • Different clusters need different marketing strategies
  • Business utility matters more than perfect cluster separation
02

Image Color Compression

A photograph has millions of pixels, each with RGB values (0-255 for Red, Green, Blue). To compress the image, k-means clusters the colors into k=16 representative colors. Each pixel is then replaced with its nearest cluster center.

Q Why does clustering work for image compression? +
A Natural images have many similar colors. Instead of storing millions of unique RGB values, store just 16 cluster centers. Each pixel needs only 4 bits (to identify which of 16 colors) instead of 24 bits (full RGB).
Q What are the 'observations' and 'features' in this clustering? +
A Observations: individual pixels (millions of them). Features: R, G, B values (3 dimensions). Each pixel is a point in 3D color space. Clusters are groups of similar colors.
Q What happens if k is too small (e.g., k=4)? +
A Severe quality loss. With only 4 colors, subtle color gradients become banded, skin tones look flat, and details vanish. The compression ratio is great but the image looks posterized.
Q What's the trade-off in choosing k? +
A Larger k = better quality but less compression. Smaller k = more compression but visible artifacts. k=16 to 64 often balances quality and compression for natural images.
Key Insights
  • K-means clustering can compress continuous data
  • Compression = representing data with fewer representative values
  • k controls the quality-compression trade-off
03

Fraud Detection via Clustering

A bank clusters credit card transactions by amount, time of day, location, and merchant type. Most transactions fall into clear clusters (normal patterns). Some transactions don't fit any cluster well.

Q How does clustering help detect fraud? +
A Normal transactions form clusters (regular patterns for each customer). Fraudulent transactions are often anomalies—they don't match any cluster. Points far from all cluster centers are suspicious.
Q A transaction is flagged because it's far from all clusters. Does this mean it's fraud? +
A Not necessarily! It's an anomaly—unusual compared to normal patterns. Could be fraud, or could be legitimate but unusual (vacation spending, large purchase). It warrants investigation, not automatic blocking.
Q Why might hierarchical clustering be useful here? +
A Hierarchical clustering reveals nested structure. Large clusters might be 'normal transaction types,' with sub-clusters for specific patterns. Anomalies sit outside the entire hierarchy.
Q What's the limitation of clustering for fraud detection? +
A Novel fraud patterns look like anomalies, but so do legitimate unusual transactions. As fraudsters adapt, their transactions may start forming their own clusters. Clustering is one tool, not the complete solution.
Key Insights
  • Points that don't fit any cluster may be anomalies
  • Anomaly ≠ fraud; it means 'unusual, investigate further'
  • Clustering provides interpretable rules for detection
?

Clustering Quiz

Test your understanding • Passing score: 70%

0 of 10 answered
Q1 multiple-choice

Clustering is an example of:

Explanation: Clustering is unsupervised—we don't have labels telling us what groups exist. The algorithm discovers groups from data structure alone.
Q2 multiple-choice

In k-means, what do the 'means' refer to?

Explanation: K-means finds k cluster centers (means/centroids). Each point is assigned to the nearest center. The 'means' are updated iteratively as the average of assigned points.
Q3 multiple-choice

Which method produces a dendrogram?

Explanation: Hierarchical clustering builds a tree of clusters, visualized as a dendrogram. You can cut the tree at any height to get different numbers of clusters.
Q4 multiple-choice

The elbow method helps determine:

Explanation: The elbow method plots within-cluster variance against k. Look for an 'elbow' where adding more clusters gives diminishing returns. This suggests a good k.
Q5 multiple-choice

K-means clustering is sensitive to:

Explanation: K-means results depend on random initial centroids. Different starting positions can give different final clusters. Run multiple times and pick the best (lowest within-cluster variance).
Q6 multiple-choice

A silhouette score of 0.8 indicates:

Explanation: Silhouette ranges from -1 to 1. Scores near 1 mean points are well-matched to their own cluster and poorly matched to others. 0.8 indicates good cluster structure.
Q7 multiple-choice

Why standardize variables before clustering?

Explanation: Without standardization, variables measured in large units (e.g., income in dollars) dominate those in small units (e.g., age in years). Standardizing puts all variables on equal footing.
Q8 multiple-choice

K-means assumes clusters are:

Explanation: K-means works best for globular (spherical) clusters of similar size. It struggles with elongated, varying-size, or irregular-shaped clusters. Consider DBSCAN or GMM for those.
Q9 multiple-choice

In agglomerative hierarchical clustering, we:

Explanation: Agglomerative (bottom-up) starts with n clusters (one per point) and iteratively merges the closest pair. Divisive (top-down) does the opposite. Agglomerative is more common.
Q10 multiple-choice

DBSCAN differs from k-means because it:

Explanation: DBSCAN doesn't require specifying k, can find clusters of any shape, and explicitly identifies outliers (points in sparse regions). It uses density rather than distance to centroids.

Quiz Results

0 %

← Time Series Next: PCA →