How Could One Implement the K-Means Algorithm?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
A solid K-means implementation has two jobs: choose initial centroids and then alternate between assignment and update steps until the centroids stop moving. The algorithm is simple enough to write from scratch, but it is also easy to implement badly if you ignore empty clusters, initialization quality, or convergence checks.
Core Idea of K-Means
Given k clusters and a set of numeric points, K-means repeatedly:
- assigns each point to its nearest centroid
- recomputes each centroid as the mean of the points assigned to it
- stops when the centroids barely change or after a maximum number of iterations
Vanilla random initialization works, but k-means++ usually converges to a better solution because it spreads the initial centroids more intelligently.
A Runnable NumPy Implementation
The example below uses k-means++ style initialization and then runs the normal K-means loop.
This is enough to experiment with the algorithm and inspect how the centroids move.
Why Initialization Matters
K-means optimizes a non-convex objective, so different starting centroids can lead to different final clusters. Random starts may work on easy datasets, but they often converge to poor local optima.
k-means++ improves this by preferring new centroids that are far from existing ones. That does not guarantee the global optimum, but it usually reduces bad initializations and stabilizes results.
In practice, many production implementations still run multiple initializations and keep the best solution by inertia.
Handling Empty Clusters
One practical issue is empty clusters. During an iteration, a centroid may end up with no assigned points. If you blindly compute its mean, the centroid becomes invalid.
Common fixes are:
- keep the previous centroid unchanged
- reinitialize it to a random point
- reinitialize it to the point with the largest current error
The example above keeps the old centroid when a cluster becomes empty. That is simple and stable enough for a teaching implementation.
Choosing k
K-means requires you to choose the number of clusters in advance. The algorithm will always return exactly k clusters even if the data does not naturally support that choice.
Typical heuristics include:
- elbow plots of inertia
- silhouette scores
- domain-specific expectations about the data
Those methods guide the choice, but they do not remove the need for judgment.
Common Pitfalls
A common mistake is using K-means on features with very different scales. Since the algorithm relies on Euclidean distance, large-scale features dominate unless you standardize first.
Another issue is expecting K-means to find non-spherical or strongly unbalanced clusters. The algorithm works best when clusters are roughly compact and mean-based.
A third problem is relying on one random initialization and assuming the result is stable.
Summary
- K-means alternates between assigning points and recomputing centroids.
- '
k-means++ gives a stronger initialization than plain random seeding.' - A good implementation needs convergence checks and empty-cluster handling.
- Standardize features when scale differences matter.
- Validate both the chosen
kand the stability of the final clustering.
Related reading
- How decision tree calculate the splitting attribute?
- How do 20 questions AI algorithms work?
- How do backpropagation works in tensorflow
- How do display different runs in TensorBoard?
- How do I access the ith column of a NumPy multidimensional array?
- How do I add an arbitrary value to a TensorFlow summary?
- How do ASCII art image conversion algorithms work?
- How do document diff algorithms work?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.