K-Means Function in Python: Step-by-Step Guide
In this article
A k-means function in Python groups data points into k clusters by repeatedly assigning each point to the nearest cluster center and then recomputing those centers as the mean of the assigned points. The shortest working version uses scikit-learn: import KMeans, create it with n_clusters=k, call fit_predict on your numeric data, and read the cluster labels and cluster_centers_. The steps below build that function from scratch, then show how to validate it and avoid the usual traps.
What You'll Need
- Python 3.9 or newer installed and working from a terminal or notebook.
- NumPy and scikit-learn installed (pip install numpy scikit-learn). Optionally pandas for loading tabular data and matplotlib for plotting clusters.
- A numeric dataset with no missing values. Categorical columns must be encoded or dropped before clustering.
- A chosen value of k. If you do not know it, plan to compare a few values using inertia or silhouette scores.
Step-by-Step
- Load and inspect the data. Read your file into a pandas DataFrame or a NumPy array and check the shape, data types and missing values. K-means works on distances, so every feature must be numeric. Drop rows with missing values or impute them; a single NaN will make the fit fail.
- Select the feature columns. Keep only the columns that describe the thing you are clustering. Identifiers, timestamps and free text should be excluded because they add noise and distort distances.
- Scale the features. Use StandardScaler from sklearn.preprocessing to center each column at zero mean and unit variance, or MinMaxScaler if you prefer a fixed range. Without scaling, a column measured in thousands will dominate one measured in fractions, and the clusters will simply reflect that one column.
- Choose k and initialize. Set n_clusters to your chosen k. Leave init='k-means++' (the default), which spreads the starting centers out and gives more stable results than random initialization. Set n_init to a value such as 10 so the algorithm runs multiple times and keeps the best result; newer scikit-learn versions default to 'auto', which already handles this.
- Fit the model and get labels. Call fit_predict on the scaled array. The returned array has one integer label per row, from 0 to k-1. Store it alongside your original data so you can inspect which rows landed in which cluster.
- Read the cluster centers. Access cluster_centers_ to see the mean position of each cluster in scaled space. If you scaled the data, use the scaler's inverse_transform on the centers to express them in the original units, which makes them interpretable.
- Check convergence and quality. Look at inertia_ (the sum of squared distances to the nearest center); lower is better for the same k, but it always falls as k rises, so it cannot choose k alone. Compute a silhouette score with sklearn.metrics.silhouette_score to judge how well separated the clusters are. A score near 1 means tight, well-separated clusters; near 0 means overlapping ones.
- Wrap it in a reusable function. Put the scaling, fitting and label assignment into a single function that accepts a DataFrame and k, and returns the labels, the fitted model and the scaler. Keep the scaler with the model so future data can be transformed the same way before prediction.
- Assign new points. Use the fitted model's predict method on new data that has been transformed with the same scaler. Do not refit the scaler on the new data, or the cluster assignments will not match the original ones.
Common Mistakes
- Forgetting to scale. This is the single most common cause of meaningless clusters. Always scale before fitting unless every feature is already on the same unit and range.
- Leaving missing values in. scikit-learn raises an error on NaN input. Clean or impute first.
- Using k-means on non-spherical clusters. K-means assumes clusters are roughly round and similar in size. Long, curved or nested shapes are better handled by DBSCAN or hierarchical clustering.
- Choosing k by inertia alone. Inertia decreases monotonically with k, so it will always favor more clusters. Combine it with silhouette scores or domain knowledge.
- Refitting the scaler on new data. Transform new data with the scaler fitted on the training data, never a fresh one.
- Treating cluster numbers as meaningful. Label 0 in one run may be label 2 in another. Always describe clusters by their centers, not their index.
Tips
- Run the fit several times with different random_state values to confirm the clusters are stable. If labels change wildly, the data may not have natural clusters at that k.
- Plot two features at a time with the labels as colors to sanity-check the result visually. For more than two features, consider reducing dimensions first.
- Use the elbow method as a rough guide: plot inertia against k and look for the point where the curve flattens. Treat it as a hint, not a verdict.
- Keep random_state set to a fixed integer so results are reproducible across runs.
- Document the scaling step alongside the model. Anyone who later applies the model must use the same transformation.
Troubleshooting
The fit raises a ValueError about NaN or infinity. Check for missing values and infinite values in the feature array, then drop or impute them before scaling.
Clusters look random or change every run. Confirm scaling was applied, set a fixed random_state, and increase n_init. If the data has no clear structure, k-means will still produce k groups but they will not be meaningful.
One cluster contains almost every point. This usually means one feature dominates the distance calculation. Rescale the features and re-run.
Silhouette score is very low or negative. The chosen k may be wrong for the data, or the clusters may overlap heavily. Try other k values and inspect a plot before trusting the labels.
Predictions on new data do not match the original clusters. You likely refitted the scaler or the model. Use the saved scaler and model objects from the original fit.
Frequently Asked Questions
Do I need scikit-learn to write a k-means function?
No. You can implement it with NumPy alone by initializing centers, assigning points by distance, and recomputing means until labels stop changing. scikit-learn is simply more reliable and faster.
How do I choose the right k?
There is no automatic answer. Compare a few values using silhouette scores and the elbow plot, and confirm the resulting clusters make sense for your problem.
Can k-means handle categorical data?
Not directly, because it relies on numeric distances. Encode categories as numbers only if they have a meaningful order; otherwise use a clustering method designed for categorical data.
Why do I get different labels on each run?
Initialization is random by default. Set random_state to a fixed value and increase n_init to make results reproducible.
What does the inertia_ value mean?
It is the sum of squared distances from each point to its assigned center. Lower values mean tighter clusters, but it always drops as k increases, so it cannot pick k by itself.
Can I use k-means for very large datasets?
Yes, but memory and time grow with the data. Use the MiniBatchKMeans variant in scikit-learn, which processes small batches and scales better while giving similar results.