1
---
2
name: Clustering Analysis
3
description: Identify groups and patterns in data using k-means, hierarchical clustering, and DBSCAN for cluster discovery, customer segmentation, and unsupervised learning
4
---
5
6
# Clustering Analysis
7
8
## Overview
9
10
Clustering partitions data into groups of similar observations without pre-defined labels, enabling discovery of natural patterns and structures in data.
11
12
## When to Use
13
14
- Segmenting customers based on purchasing behavior or demographics
15
- Discovering natural groupings in data without prior knowledge of categories
16
- Identifying market segments for targeted marketing campaigns
17
- Organizing large datasets into meaningful categories for further analysis
18
- Finding patterns in gene expression data or medical imaging
19
- Grouping documents, products, or users by similarity for recommendation systems
20
21
## Clustering Algorithms
22
23
- **K-Means**: Partitioning into k clusters
24
- **Hierarchical**: Dendrograms showing nested clusters
25
- **DBSCAN**: Density-based arbitrary-shaped clusters
26
- **Gaussian Mixture**: Probabilistic clustering
27
- **Agglomerative**: Bottom-up hierarchical approach
28
29
## Key Concepts
30
31
- **Cluster Validation**: Metrics to evaluate cluster quality
32
- **Optimal Clusters**: Methods to determine best k
33
- **Inertia**: Within-cluster sum of squares
34
- **Silhouette Score**: Measure of cluster separation
35
- **Dendrogram**: Hierarchical clustering visualization
36
37
## Implementation with Python
38
39
```python
40
import pandas as pd
41
import numpy as np
42
import matplotlib.pyplot as plt
43
from sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering
44
from sklearn.mixture import GaussianMixture
45
from sklearn.preprocessing import StandardScaler
46
from sklearn.metrics import (
47
silhouette_score, silhouette_samples, davies_bouldin_score,
48
calinski_harabasz_score
49
)
50
from scipy.cluster.hierarchy import dendrogram, linkage
51
import seaborn as sns
52
53
# Generate sample data
54
np.random.seed(42)
55
n_samples = 300
56
centers = [[0, 0], [5, 5], [-3, 4]]
57
X = np.vstack([
58
np.random.randn(100, 2) + centers[0],
59
np.random.randn(100, 2) + centers[1],
60
np.random.randn(100, 2) + centers[2],
61
])
62
63
# Standardize
64
scaler = StandardScaler()
65
X_scaled = scaler.fit_transform(X)
66
67
# K-Means with Elbow method
68
inertias = []
69
silhouette_scores = []
70
k_range = range(2, 11)
71
72
for k in k_range:
73
kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)
74
kmeans.fit(X_scaled)
75
inertias.append(kmeans.inertia_)
76
silhouette_scores.append(silhouette_score(X_scaled, kmeans.labels_))
77
78
fig, axes = plt.subplots(1, 2, figsize=(14, 4))
79
80
axes[0].plot(k_range, inertias, 'bo-')
81
axes[0].set_xlabel('Number of Clusters (k)')
82
axes[0].set_ylabel('Inertia')
83
axes[0].set_title('Elbow Method')
84
axes[0].grid(True, alpha=0.3)
85
86
axes[1].plot(k_range, silhouette_scores, 'go-')
87
axes[1].set_xlabel('Number of Clusters (k)')
88
axes[1].set_ylabel('Silhouette Score')
89
axes[1].set_title('Silhouette Analysis')
90
axes[1].grid(True, alpha=0.3)
91
92
plt.tight_layout()
93
plt.show()
94
95
# Optimal k = 3
96
optimal_k = 3
97
kmeans = KMeans(n_clusters=optimal_k, random_state=42, n_init=10)
98
kmeans_labels = kmeans.fit_predict(X_scaled)
99
100
# K-Means visualization
101
fig, axes = plt.subplots(1, 3, figsize=(15, 4))
102
103
# K-Means clusters
104
axes[0].scatter(X[:, 0], X[:, 1], c=kmeans_labels, cmap='viridis', alpha=0.6)
105
axes[0].scatter(
106
kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1],
107
c='red', marker='X', s=200, edgecolors='black', linewidths=2
108
)
109
axes[0].set_title(f'K-Means (k={optimal_k})')
110
axes[0].set_xlabel('Feature 1')
111
axes[0].set_ylabel('Feature 2')
112
113
# Silhouette plot
114
ax = axes[1]
115
y_lower = 10
116
silhouette_vals = silhouette_samples(X_scaled, kmeans_labels)
117
118
for i in range(optimal_k):
119
cluster_silhouette_vals = silhouette_vals[kmeans_labels == i]
120
cluster_silhouette_vals.sort()
121
122
size_cluster_i = cluster_silhouette_vals.shape[0]
123
y_upper = y_lower + size_cluster_i
124
125
ax.fill_betweenx(np.arange(y_lower, y_upper),
126
0, cluster_silhouette_vals,
127
alpha=0.7, label=f'Cluster {i}')
128
y_lower = y_upper + 10
129
130
ax.axvline(x=silhouette_score(X_scaled, kmeans_labels), color="red", linestyle="--")
131
ax.set_xlabel('Silhouette Coefficient')
132
ax.set_ylabel('Cluster Label')
133
ax.set_title('Silhouette Plot')
134
135
# Hierarchical clustering
136
linkage_matrix = linkage(X_scaled, method='ward')
137
dendrogram(linkage_matrix, ax=axes[2], truncate_mode='lastp', p=10)
138
axes[2].set_title('Dendrogram (Ward)')
139
axes[2].set_xlabel('Sample Index')
140
141
plt.tight_layout()
142
plt.show()
143
144
# Hierarchical clustering
145
hierarchical = AgglomerativeClustering(n_clusters=optimal_k, linkage='ward')
146
hier_labels = hierarchical.fit_predict(X_scaled)
147
148
# DBSCAN clustering
149
dbscan = DBSCAN(eps=0.4, min_samples=5)
150
dbscan_labels = dbscan.fit_predict(X_scaled)
151
n_clusters_dbscan = len(set(dbscan_labels)) - (1 if -1 in dbscan_labels else 0)
152
n_noise = list(dbscan_labels).count(-1)
153
154
# Gaussian Mixture Model
155
gmm = GaussianMixture(n_components=optimal_k, random_state=42)
156
gmm_labels = gmm.fit_predict(X_scaled)
157
gmm_proba = gmm.predict_proba(X_scaled)
158
159
# Clustering algorithm comparison
160
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
161
162
algorithms = [
163
(kmeans_labels, 'K-Means'),
164
(hier_labels, 'Hierarchical'),
165
(dbscan_labels, 'DBSCAN'),
166
(gmm_labels, 'Gaussian Mixture'),
167
]
168
169
for idx, (labels, title) in enumerate(algorithms):
170
ax = axes[idx // 2, idx % 2]
171
172
# Skip noise points for DBSCAN
173
mask = labels != -1
174
scatter = ax.scatter(
175
X[mask, 0], X[mask, 1], c=labels[mask], cmap='viridis', alpha=0.6
176
)
177
178
if title == 'DBSCAN' and n_noise > 0:
179
noise_mask = labels == -1
180
ax.scatter(X[noise_mask, 0], X[noise_mask, 1], c='red', marker='x', s=100, label='Noise')
181
ax.legend()
182
183
ax.set_title(f'{title} (n_clusters={len(set(labels[mask]))})')
184
ax.set_xlabel('Feature 1')
185
ax.set_ylabel('Feature 2')
186
187
plt.tight_layout()
188
plt.show()
189
190
# Cluster validation metrics
191
validation_metrics = {
192
'Algorithm': ['K-Means', 'Hierarchical', 'DBSCAN', 'GMM'],
193
'Silhouette Score': [
194
silhouette_score(X_scaled, kmeans_labels),
195
silhouette_score(X_scaled, hier_labels),
196
silhouette_score(X_scaled[dbscan_labels != -1], dbscan_labels[dbscan_labels != -1]) if n_noise < len(X_scaled) else np.nan,
197
silhouette_score(X_scaled, gmm_labels),
198
],
199
'Davies-Bouldin Index': [
200
davies_bouldin_score(X_scaled, kmeans_labels),
201
davies_bouldin_score(X_scaled, hier_labels),
202
davies_bouldin_score(X_scaled[dbscan_labels != -1], dbscan_labels[dbscan_labels != -1]) if n_noise < len(X_scaled) else np.nan,
203
davies_bouldin_score(X_scaled, gmm_labels),
204
],
205
'Calinski-Harabasz Index': [
206
calinski_harabasz_score(X_scaled, kmeans_labels),
207
calinski_harabasz_score(X_scaled, hier_labels),
208
calinski_harabasz_score(X_scaled[dbscan_labels != -1], dbscan_labels[dbscan_labels != -1]) if n_noise < len(X_scaled) else np.nan,
209
calinski_harabasz_score(X_scaled, gmm_labels),
210
],
211
}
212
213
metrics_df = pd.DataFrame(validation_metrics)
214
print("Clustering Validation Metrics:")
215
print(metrics_df)
216
217
# Cluster size analysis
218
sizes_df = pd.DataFrame({
219
'K-Means': pd.Series(kmeans_labels).value_counts().sort_index(),
220
'Hierarchical': pd.Series(hier_labels).value_counts().sort_index(),
221
'GMM': pd.Series(gmm_labels).value_counts().sort_index(),
222
})
223
224
print("\nCluster Sizes:")
225
print(sizes_df)
226
227
# Membership probability (GMM)
228
fig, ax = plt.subplots(figsize=(10, 6))
229
membership = gmm_proba.max(axis=1)
230
scatter = ax.scatter(X[:, 0], X[:, 1], c=membership, cmap='RdYlGn', alpha=0.6, s=50)
231
ax.set_title('Cluster Membership Confidence (GMM)')
232
ax.set_xlabel('Feature 1')
233
ax.set_ylabel('Feature 2')
234
plt.colorbar(scatter, ax=ax, label='Membership Probability')
235
plt.show()
236
237
# Cluster characteristics
238
kmeans_centers_original = scaler.inverse_transform(kmeans.cluster_centers_)
239
cluster_df = pd.DataFrame(X, columns=['Feature 1', 'Feature 2'])
240
cluster_df['Cluster'] = kmeans_labels
241
242
for cluster_id in range(optimal_k):
243
cluster_data = cluster_df[cluster_df['Cluster'] == cluster_id]
244
print(f"\nCluster {cluster_id} Characteristics:")
245
print(cluster_data[['Feature 1', 'Feature 2']].describe())
246
```
247
248
## Cluster Quality Metrics
249
250
- **Silhouette Score**: -1 to 1 (higher is better)
251
- **Davies-Bouldin Index**: Lower is better
252
- **Calinski-Harabasz Index**: Higher is better
253
- **Inertia**: Lower is better (KMeans only)
254
255
## Algorithm Selection
256
257
- **K-Means**: Fast, spherical clusters, k needs specification
258
- **Hierarchical**: Produces dendrogram, interpretable
259
- **DBSCAN**: Arbitrary shapes, handles noise
260
- **GMM**: Probabilistic, soft assignments
261
262
## Deliverables
263
264
- Optimal cluster count analysis
265
- Cluster visualizations
266
- Validation metrics comparison
267
- Cluster characteristics summary
268
- Silhouette plots
269
- Dendrogram for hierarchical clustering
270
- Membership assignments
271