Skip to main content
Albero Academy

Clustering (K-Means)

Group unlabelled data into segments.

Model Selection & Unsupervised8 min

Clustering is unsupervised: with no labels, it groups similar points together. K-means is the classic algorithm — you choose the number of clusters k, and it finds k centres that minimise within-cluster distance.

K-means

fit and assign clusters
from sklearn.cluster import KMeans
km = KMeans(n_clusters=3, random_state=42, n_init="auto")
labels = km.fit_predict(X) # each point's cluster id
km.cluster_centers_ # the centre of each cluster

Choosing k

Key takeaways

  1. 01Clustering groups unlabelled data by similarity (unsupervised).
  2. 02K-means finds k cluster centres minimising within-cluster distance; you choose k.
  3. 03Use the elbow method or silhouette score to pick k.
  4. 04Scale features first; k-means assumes spherical clusters (try DBSCAN for others).

Finished this chapter?

Mark it complete to track your progress through Scikit-learn.