K-means Clustering › Visualizing K-means Clustering
Machine Learning from ScratchAll chapters K-means Clustering › Visualizing K-means ClusteringOne section · Sections in this chapter3 / 15 ↓
Let's visualize how K-means clustering works step by step. We'll generate synthetic data with three distinct clusters and show the iterative process of centroid updates and cluster assignments.




Here you can see the iterative nature of K-means clustering in action. Watch how the algorithm starts with random centroids and progressively improves the cluster assignments and centroid positions until convergence. The final plot includes cluster boundaries to show how the algorithm partitions the feature space.
Now let's create a second visualization that shows the impact of different initialization strategies and the importance of choosing the right number of clusters:






This second visualization shows how different values of k affect the clustering results. Notice that k=4 (the true number of clusters) achieves the highest silhouette score.