No labels to copy
Clustering looks for groups in unlabeled data. There is no y to fit against. The algorithm proposes structure, and you decide whether that structure is useful for the problem at hand.
Python
Features without a label column
Output
Press Run to execute this cell. The first run downloads Python; later runs reuse the session.
Let K-means find centers
K-means alternates between assigning each row to the nearest centroid and moving each centroid to the mean of its assigned rows. Scaling matters because distance is measured in feature units.
Python
Fit, label, and visualize the clusters
Output
Press Run to execute this cell. The first run downloads Python; later runs reuse the session.
The centroids above are in scaled space, so their coordinates are not the original feature units. Use model.named_steps["scale"].inverse_transform(...) if you need to map them back.
Inertia rewards tight clusters
Inertia is the sum of squared distances from each row to its assigned centroid. It falls as the number of clusters grows, so it cannot choose k by itself. Look for an elbow where extra clusters stop buying much tightness.
Python
Inertia always improves as k grows
Output
Press Run to execute this cell. The first run downloads Python; later runs reuse the session.
Measure separation, not just tightness
The silhouette score compares each row's average distance to its own cluster with its average distance to the nearest other cluster. Values near 1 mean well-separated groups, near 0 mean overlapping groups, and below 0 suggest possible misassignment.
Python
Compare separation across candidate cluster counts
Output
Press Run to execute this cell. The first run downloads Python; later runs reuse the session.
Silhouette is computed on the same X and labels used to fit here, which is fine for exploration. For a performance claim, evaluate on held-out rows or use a stability check across resamples.
Cluster numbers are not class names
K-means labels are arbitrary identifiers. Cluster 0 in one run can be cluster 3 in another, even when the grouping is identical. Never compare raw cluster IDs across models or treat them as ordered categories.
Python
The group sizes can match while the IDs differ
Output
Press Run to execute this cell. The first run downloads Python; later runs reuse the session.
Practice
Make it stick
Run the tests as often as you like. Hints and the solution are available when you need them.
Exercise
Build a StandardScaler plus KMeans(n_clusters=4, n_init=10, random_state=42) pipeline. Store the cluster labels in labels, the inertia in inertia, and the silhouette score in silhouette.
Your solution
ReadyResults
Run the tests to check your solution. The first run downloads Python; later runs reuse the session.
Quiz
Check your understanding
Lesson progress