Sub topic 3
Running k-means with scikit-learn
Assume you know Python, NumPy arrays, feature matrices, Euclidean distance, and the difference between supervised and unsupervised learning. In scikit-learn, KMeans assigns each row to a cluster and stores the learned centroids.
Fit and inspect a model
Scale features when their units or ranges differ. The pipeline below standardizes each column before clustering. n_init=10 runs the algorithm from several starting positions and keeps the result with the lowest inertia.
from sklearn.datasets import make_blobs
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
X, _ = make_blobs(n_samples=300, centers=3, random_state=42)
model = make_pipeline(
StandardScaler(),
KMeans(n_clusters=3, n_init=10, random_state=42),
)
labels = model.fit_predict(X)
kmeans = model[-1]
print(labels.shape)
print(kmeans.cluster_centers_.shape)
print(kmeans.inertia_)labels contains one integer per sample. inertia_ is the sum of squared distances from each sample to its assigned centroid. Lower inertia means tighter clusters, but inertia always decreases as k increases.
Choosing `k`
The elbow method compares inertia for several values of k. Choose a value near the point where additional clusters stop producing large improvements. The silhouette score measures how close each sample is to its own cluster compared with other clusters. Higher values are generally better, with a maximum of 1.
| Measure | Prefer | Main use |
|---|---|---|
| Inertia | Lower, with an elbow | Find diminishing returns |
| Silhouette score | Higher | Compare separation and cohesion |
from sklearn.metrics import silhouette_score
X_scaled = StandardScaler().fit_transform(X)
for k in range(2, 8):
km = KMeans(n_clusters=k, n_init=10, random_state=42).fit(X_scaled)
print(k, round(km.inertia_, 1), round(silhouette_score(X_scaled, km.labels_), 3))Failure cases and alternatives
K-means assumes roughly round, similarly sized clusters under the chosen distance metric. It performs poorly with elongated or nested shapes, strong outliers, categorical values, or badly scaled features. Consider DBSCAN for density-based, irregular clusters; hierarchical clustering for a merge tree; or Gaussian mixture models when soft, elliptical memberships matter. Mini-batch k-means updates centroids using small batches, reducing memory and time for very large datasets at the cost of some accuracy.
Exercise
Why can inertia alone give a misleading choice of k?
Show answer
It cannot increase when k increases, so it must be compared with diminishing returns or another measure such as silhouette score.