K-Means Clustering Cheat Sheet
A reference for K-Means clustering covering scikit-learn implementation, centroid initialization, the elbow method, and silhouette scoring for choosing k.
1 PageBeginnerMar 20, 2026
Clustering with scikit-learn
Fit K-Means and inspect the resulting clusters.
python
from sklearn.cluster import KMeansfrom sklearn.preprocessing import StandardScalerX_scaled = StandardScaler().fit_transform(X)kmeans = KMeans(n_clusters=4, init='k-means++', n_init=10, random_state=42)labels = kmeans.fit_predict(X_scaled)print('Inertia:', kmeans.inertia_)print('Centroids:', kmeans.cluster_centers_)
Elbow Method
Pick k by plotting inertia across candidate values.
python
import matplotlib.pyplot as pltinertias = []for k in range(1, 11): km = KMeans(n_clusters=k, n_init=10, random_state=42).fit(X_scaled) inertias.append(km.inertia_)plt.plot(range(1, 11), inertias, marker='o')plt.xlabel('k'); plt.ylabel('Inertia') # look for the 'elbow' bend
Silhouette Score
Quantify cluster separation quality for each k.
python
from sklearn.metrics import silhouette_scorefor k in range(2, 8): labels = KMeans(n_clusters=k, n_init=10, random_state=42).fit_predict(X_scaled) score = silhouette_score(X_scaled, labels) print(f'k={k}: silhouette={score:.3f}') # closer to 1 is better
Key Concepts
Core theory behind K-Means.
- Centroid- Mean position of all points assigned to a cluster; recomputed every iteration
- Inertia- Sum of squared distances from points to their nearest centroid (within-cluster variance)
- k-means++- Smart centroid initialization that spreads out starting centroids to speed up convergence
- Elbow method- Plot inertia against k and pick the point where the decrease sharply flattens
- Silhouette score- Measures how similar a point is to its own cluster vs. neighboring clusters, ranging -1 to 1
- Convergence- Assignment and update steps alternate until centroids stop moving or max_iter is reached
Pro Tip
K-means assumes roughly spherical, similarly sized clusters and is sensitive to feature scale and outliers — always standardize your features first, and consider DBSCAN or a Gaussian Mixture Model when clusters are non-convex or have very different densities.
Was this cheat sheet helpful?
Explore Topics
#KMeansClustering#KMeansClusteringCheatSheet#DataScience#Beginner#ClusteringWithScikitLearn#ElbowMethod#SilhouetteScore#KeyConcepts#Functions#MachineLearning#CheatSheet#SkillVeris