Sub topic 8
Running k-means with scikit-learn
This chapter assumes you know the following:
- Basic Python and NumPy.
- A feature matrix has one row per sample and one column per feature.
- Lloyd's algorithm alternates between assigning points and updating centroids.
- Inertia is the sum of squared distances from each point to its centroid.
- k-means++ seeds the centroids, and scaling matters for distance-based methods.
Here you will move from the hand-written NumPy version to sklearn.cluster.KMeans, read its results, and avoid its common mistakes.
The KMeans estimator
KMeans follows the usual scikit-learn pattern. You build the object with hyperparameters, call fit on the data, and read attributes whose names end in an underscore. Those attributes exist only after fitting.
| Parameter | Meaning | Typical choice |
|---|---|---|
| `n_clusters` | The number of clusters, k | Required, chosen by you |
| `init` | Seeding method | `"k-means++"` (default) |
| `n_init` | Number of full runs with different seeds. The best run by inertia is kept. | `10`, or `"auto"` |
| `max_iter` | Cap on Lloyd iterations per run | `300` (default) |
| `tol` | Convergence tolerance on centroid movement | `1e-4` (default) |
| `random_state` | Seed, for reproducible results | Any integer |
After fitting you can read these attributes:
cluster_centers_: an array of shape(k, n_features).labels_: the cluster index of each training row.inertia_: the final objective value of the best run.n_iter_: the number of iterations the best run used.
A scaled pipeline
k-means uses Euclidean distance, so a feature measured in thousands will dominate one measured in fractions. Put a StandardScaler in front of KMeans inside a Pipeline. The scaler is then fitted once, and the same transformation is applied automatically to any new data.
import numpy as np
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_)
print(kmeans.n_iter_)
# Convert centroids back to the original units
centers_original = model[0].inverse_transform(kmeans.cluster_centers_)
print(centers_original.round(2))
# Assign unseen points to the nearest learned centroid
new_points = np.array([[0.0, 0.0], [5.0, 5.0]])
print(model.predict(new_points))Two details in this code are worth noting:
model[-1]andmodel[0]use pipeline indexing to reach the individual steps.cluster_centers_lives in scaled space. Callinverse_transformon the scaler if you want to describe clusters in original units, such as "customers who spend about 40 per visit".
Reading the results
labels_ gives the cluster of each training row. predict gives the nearest-centroid cluster for new rows. For the training data, fit_predict(X) returns the same assignment as labels_.
The cluster numbers themselves are arbitrary. Cluster 0 in one run may be cluster 2 in another with a different seed. Compare clusterings by their contents, not by their numbers.
Inertia is only meaningful in comparisons that make sense. You can compare runs on the same data at the same k, which is what n_init does internally. You cannot compare inertia across different k, because it always falls as k grows. You also cannot compare it across different scalings, because the units differ.
Common errors
- Skipping scaling. If one feature has a much larger range, the clusters will mostly split along that feature.
- Fitting the scaler on all data, then splitting. Fit the pipeline on training data only, then call
predicton held-out data. - Passing missing values or text.
KMeansraises an error onNaNand on non-numeric columns. Impute or encode first. Be careful with one-hot columns, since they add distance in a way that may not reflect similarity. - Trusting a single start. A low
n_initcan leave you in a poor local minimum. Keepn_initat 10 or more unless the data is very large. - Treating
predictas a confidence statement. A far-away outlier is still assigned to its nearest centroid. Usekmeans.transformto get distances to every centroid if you need to flag outliers. - Forgetting
random_state. Without it, results can differ from run to run and your tutorial or report will not reproduce.
Exercise
Why is it better to put StandardScaler and KMeans in one pipeline than to scale X by hand and fit KMeans on the result?
Show answer
The pipeline stores the scaler fitted on the training data and applies exactly the same transformation inside predict. If you scale by hand, you must remember to apply the same fitted scaler to every new batch, and it is easy to skip it or refit it on the new data, which shifts the centroids' meaning. The pipeline also lets you invert the scaling on clustercenters through its first step.
Exercise
You fit KMeans with nclusters=3 and nclusters=4 on the same data and see that inertia_ drops from 410 to 350. Can you conclude that 4 clusters is the better model?
Show answer
No. Inertia never increases as k grows, so a drop is expected whatever the true structure. You need a criterion that accounts for this, such as the elbow in the inertia curve or the silhouette score, which the next chapter covers.