Machine Learning Tutorial 0/98 lessons ~6 min read Lesson 48
K-Means Clustering
K-means partitions points into k groups by repeatedly assigning each point to the nearest centroid and recomputing centroids as cluster means.
Course progress0%
Focus
9 guided sections
Practice signal
Examples included
Career prep
Foundation builder
Introduction
K-means partitions points into k groups by repeatedly assigning each point to the nearest centroid and recomputing centroids as cluster means. It works well when clusters are compact and roughly spherical.
Understanding the topic
Pick k Use domain knowledge, silhouette scores, or the elbow plot of inertia vs k.
Scale first Distance-based clustering usually needs standardized features.
- Pick k — Use domain knowledge, silhouette scores, or the elbow plot of inertia vs k.
- Scale first — Distance-based clustering usually needs standardized features.
Step-by-step explanation
- Pick k — Use domain knowledge, silhouette scores, or the elbow plot of inertia vs k.
- Scale first — Distance-based clustering usually needs standardized features.
Informative example
Python starter:
python
from sklearn.cluster import KMeansfrom sklearn.datasets import make_blobsfrom sklearn.metrics import silhouette_scoreX, _ = make_blobs(n_samples=300, centers=3, cluster_std=0.9, random_state=42)km = KMeans(n_clusters=3, n_init="auto", random_state=42).fit(X)print(f"Inertia: {km.inertia_:.2f} | Silhouette: {silhouette_score(X, km.labels_):.4f}")
Output
Inertia: 459.42 | Silhouette: 0.8602
Execution workflow
1K-Means Clustering — workflow
1 / 2Pick k
Use domain knowledge, silhouette scores, or the elbow plot of inertia vs k.
Best practices
- Hold out a test set before hyperparameter tuning.
- Scale numeric columns for distance-based models.
- Track multiple metrics — not accuracy alone on skewed labels.
Common mistakes
- Leaking test statistics into preprocessing fit on full data.
- Training on the same rows you report as test performance.
- Chasing complex models before a simple baseline.
Hands-on exercise
Practice:
- Cluster a 2D scatter and color by label
- Try k=2 vs k=4 on the same data
Summary
K-Means Clustering — Partition points around k centroids.
Ready to mark this lesson complete?Track your journey across the entire course.