Loading the lesson...
In the print dialog, choose "Save as PDF" as the destination.
Machine Learning and AI - Lab 1
Unsupervised learning with scikit-learn: generate, cluster, evaluate, and optimize
sklearn.datasets.make_blobssklearn.cluster.KMeansn_clusters, init, max_iter, n_initk using the Elbow Method (WCSS)make_blobs creates isotropic Gaussian blobs for clustering experimentsn_samples, n_features, centers, cluster_std, random_statefrom sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
X, y_true = make_blobs(n_samples=300, n_features=2,
centers=4, cluster_std=0.8,
random_state=42)X colored by y_true shows the true clusteringK-Means will try to recoverinit='k-means++': smart seeding, new centroids favor points far from existing onesInitialize centroids
k-means++
Run n_init times
different seeds
Compute inertia
per run
Keep lowest inertia
kmeans = KMeans(n_clusters=4, init='k-means++',
max_iter=300, n_init=10, random_state=42)
kmeans.fit(X)
labels = kmeans.labels_
centroids = kmeans.cluster_centers_labels)X markersa = avg distance to same-cluster points, b = avg distance to nearest other cluster| Score | Meaning |
|---|---|
| +1 | Well-clustered |
| 0 | On the boundary |
| -1 | Likely misassigned |
WCSS against k from 1 to 10 to reveal a bend where improvement slowsTry k = 1 to 10
Fit K-Means
record inertia
Plot WCSS vs k
Locate the elbow
wcss, silhouette_scores = [], []
for i in range(1, 11):
km = KMeans(n_clusters=i, init='k-means++',
max_iter=300, n_init=10, random_state=42)
km.fit(X)
wcss.append(km.inertia_)K-Means output (right)labels may differ (true cluster 0 could become predicted cluster 2)K-Means recovered the underlying structure closely| Metric | Value |
|---|---|
| Samples / Features / True clusters | 300 / 2 / 4 |
| cluster_std | 0.8 |
| k used / Initialization | 4 / k-means++ |
| WCSS (inertia) | 362.472 |
| Silhouette Score | 0.834 (excellent) |
| Best k by silhouette | 4 |
K-Means works best on spherical, well-separated clustersk-means++ initialization plus multiple n_init runs avoid poor local minimakMahmoud Abas|Lab #1: K-Means Clustering with Synthetic Data