Sub topic 8
Running k-means with scikit-learn
This chapter assumes you know basic Python and NumPy, the shape of a feature matrix (rows are samples, columns are features), and the core k-means ideas from earlier chapters: inertia, Lloyd's algorithm, k-means++ seeding, and why features need scaling. Here you apply them with sklearn.cluster.KMeans. You will fit a model, read its attributes, assign new points, and avoid the common mistakes.
What KMeans does for you
In the NumPy version of Lloyd's algorithm, you wrote the assignment step, the update step, and the stopping test yourself. KMeans does the same work, with these additions:
- It seeds centroids with k-means++ by default.
- It runs the whole algorithm several times from different seeds and keeps the run with the lowest inertia.
- It uses compiled code, so it is much faster than a Python loop.
- It follows the standard scikit-learn interface:
fit,predict,transform, andfit_predict.
The estimator is unsupervised. You call fit(X) with no target, unlike a classifier, which needs fit(X, y).
The constructor parameters that matter
from sklearn.cluster import KMeans
KMeans(
n_clusters=8,
init="k-means++",
n_init="auto",
max_iter=300,
tol=1e-4,
random_state=None,
)| Parameter | Meaning | Practical advice |
|---|---|---|
| `n_clusters` | The number k. | No useful default. Choose it deliberately (see the chapter on choosing k). |
| `init` | `"k-means++"`, `"random"`, or an array of starting centroids. | Keep `"k-means++"` unless you have a reason to supply your own starting points. |
| `n_init` | Number of independent runs. | `"auto"` runs 1 time with k-means++ and 10 times with random init. Set an integer such as 10 to make the count explicit. |
| `max_iter` | Maximum Lloyd iterations per run. | 300 is rarely a limit. Raise it if you see a `ConvergenceWarning`. |
| `tol` | Convergence tolerance on how much the centroids move. | Leave the default unless you need speed or precision. |
| `random_state` | Seed for reproducibility. | Set it in tutorials, tests, and reports. |
The n_init="auto" setting depends on your scikit-learn version. Older releases defaulted to n_init=10 and warned about a future change. Passing an explicit integer behaves the same in every version.
A complete first fit
Standardize first, then cluster. A Pipeline keeps the two steps together, so the scaler learned on training data is reused on new data.
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, cluster_std=1.0, 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(kmeans.cluster_centers_.shape) # (3, 2), in scaled feature space
print(kmeans.inertia_)make_blobs returns true labels as its second value. The code discards them with _ because k-means never sees them. Real unlabeled data has no such answer key.
Fitted attributes
After fit, the estimator stores results in attributes that end with an underscore. This is the scikit-learn convention for values learned from data.
| Attribute | Content |
|---|---|
| `cluster_centers_` | Array of shape `(n_clusters, n_features)` with the final centroids. |
| `labels_` | Cluster index for each training sample, shape `(n_samples,)`. |
| `inertia_` | Sum of squared distances from each sample to its assigned centroid. |
| `n_iter_` | Lloyd iterations used by the best run. |
| `n_features_in_` | Number of features seen during `fit`. |
The centroids in the pipeline example live in scaled space. If you need them in the original units, undo the scaling:
scaler = model[0]
centers_original = scaler.inverse_transform(kmeans.cluster_centers_)
print(centers_original)This is a frequent source of confusion. A centroid of (0.8, -1.1) is meaningless to a business reader, but the inverse-transformed values are in the units of the raw columns.
How a fit flows
The restarts are the reason the best-run inertia is better than the typical single-run inertia. Each run still ends in a local minimum. You only pick the best of several local minima, and nothing guarantees it is the global one.
Assigning new points
A fitted model can place points it has not seen. predict assigns each new row to the nearest stored centroid. It does not refit or move any centroid.
import numpy as np
new_points = np.array([[0.0, 0.0], [5.0, 5.0]])
print(model.predict(new_points))Because model is a pipeline, predict scales the new points with the scaler fitted on the training data before measuring distance. If you passed raw points straight to the KMeans step, the distances would be computed in the wrong units. This is the main reason to use a pipeline.
transform is a related method. It returns the distance from each sample to every centroid, with shape (n_samples, n_clusters). You can use it as a feature set for a later model, or take a row's smallest value as a measure of how typical the point is for its cluster.
distances = model.transform(new_points)
print(distances.shape) # (2, 3)
print(distances.min(axis=1))A large minimum distance suggests a point that fits poorly in any cluster. Because predict always picks some cluster, this is the only hint that a point is an outlier.
Seeing the effect of initialization
This experiment repeats single-start runs with each initialization method. It shows why the defaults use k-means++ and restarts.
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
X, _ = make_blobs(n_samples=500, centers=5, cluster_std=1.5, random_state=0)
for init in ("random", "k-means++"):
inertias = [
KMeans(n_clusters=5, init=init, n_init=1, random_state=seed).fit(X).inertia_
for seed in range(10)
]
print(init, min(inertias), max(inertias))Look at the gap between the minimum and maximum for each method. A wide gap means some starts landed in poor local minima. With k-means++ the worst case is usually closer to the best. Setting n_init=10 inside a single KMeans call applies the same idea automatically and keeps the lowest.
The exact numbers depend on your scikit-learn version and platform, so do not copy them into documentation as constants.
Comparing several values of k
The inertia_ attribute always falls as k grows, so it cannot choose k alone. The silhouette score measures how well separated the clusters are, and it needs at least two clusters. This loop computes both for a range of k:
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
X, _ = make_blobs(n_samples=300, centers=4, random_state=7)
for k in range(2, 8):
km = KMeans(n_clusters=k, n_init=10, random_state=7).fit(X)
score = silhouette_score(X, km.labels_)
print(f"k={k} inertia={km.inertia_:.1f} silhouette={score:.3f}")Read the table in two ways. Inertia drops steeply until the true number of groups and then flattens (the elbow). Silhouette usually peaks near the best k. When the two disagree, look at the cluster sizes and at plots before deciding. The next chapter's topic on choosing k covers this in detail.
Inspecting a result
A fit that finishes without errors can still be a poor clustering. These checks take seconds.
- Cluster sizes. Count the labels with
np.bincount(labels). One cluster holding 90% of the data, or a cluster with two points, deserves a look. - Centroids in original units. Convert back with
inverse_transformand check that each profile is plausible. - Inertia across seeds. Fit with a few different
random_statevalues. Large changes in inertia or in the grouping point to an unstable solution. - Iteration count. If
n_iter_equalsmax_iter, the run stopped early and may not have converged.
import numpy as np
print(np.bincount(labels))
print(kmeans.n_iter_)Common errors
Forgetting to scale
Without scaling, a feature measured in thousands dominates one measured in single digits. The distances reflect almost only the large feature. Scale inside a pipeline so the same transformation applies at fit and predict time.
Fitting the scaler on all data, then evaluating on a split
If you hold out data for evaluation, fit the scaler on the training portion only. A pipeline does this automatically when you call fit on training data.
Treating label numbers as meaningful
Cluster 0 is not smaller, better, or earlier than cluster 2. The numbering depends on the seed. Two runs can produce the same grouping with permuted labels. If you compare clusterings, use a permutation-invariant measure such as sklearn.metrics.adjusted_rand_score, not equality of label arrays.
Using categorical columns directly
k-means needs numeric features where means and Euclidean distance make sense. Integer-coded categories (red=0, green=1, blue=2) invent an order and a distance that do not exist. One-hot encoding avoids the false order, but the resulting 0/1 columns still behave poorly with means. Consider k-modes or a Gower-distance method for mostly categorical data.
Reading `inertia_` across different datasets or scalings
Inertia depends on the units and on the number of samples. Only compare values computed on the same data with the same preprocessing.
Ignoring warnings
A ConvergenceWarning means a run hit max_iter. A message that the number of distinct points is less than n_clusters means you asked for more clusters than the data has distinct rows. Both are signals to change your setup, not noise to silence.
Expecting outlier robustness
Centroids are means, so a single extreme point can drag one. If outliers are common, remove or cap them, or use a method such as k-medoids.
Speed and memory
For moderate data, the default KMeans is fast. Two options help when it is not:
- Lower
n_initafter confirming that results are stable. - Switch to
MiniBatchKMeansfor hundreds of thousands of rows or more. It updates centroids from small random batches, trading a slightly higher inertia for much lower time. Its interface matchesKMeans.
Do not call silhouette_score on very large data without sampling. It computes pairwise distances and grows quadratically. Its sample_size argument evaluates on a random subset.
score = silhouette_score(X, km.labels_, sample_size=1000, random_state=0)Exercises
Exercise
You fit model = make_pipeline(StandardScaler(), KMeans(n_clusters=3, n_init=10, random_state=0)) on a training set. A colleague calls model[-1].predict(new_rows) with raw rows and gets odd assignments. What went wrong, and what is the fix?
Show answer
The KMeans step was trained on scaled data, so its centroids are in scaled units. Calling it directly with raw rows compares unscaled values to scaled centroids. Call model.predict(new_rows) on the whole pipeline, or apply model[0].transform(new_rows) first, so the scaler fitted on the training data is applied.
Exercise
You run k-means twice with different random_state values. The label arrays differ in many positions, but the inertia is almost identical. Does this show the algorithm is unreliable? How would you check?
Show answer
Not necessarily. Label numbers are arbitrary, so the same grouping can appear with permuted labels. Compare the two label arrays with adjusted_rand_score. A value near 1 means the groupings match despite different numbering. A low value with similar inertia points to different local minima that fit about equally well.