K-means Clustering › Example
Machine Learning from ScratchAll chapters K-means Clustering › ExampleOne section · Sections in this chapter5 / 15 ↓
Let's work through a concrete example of K-means clustering using a simple 2D dataset with 8 data points. This step-by-step calculation will help us understand exactly how the algorithm works.
Given Data Points: We have 8 points in 2D space:
- , , ,
- , , ,
We want to find clusters. Step 1: Initialization Let's randomly initialize two centroids:
- Centroid 1:
- Centroid 2:
Step 2: Assignment Step (First Iteration) For each point, we calculate the distance to both centroids and assign it to the nearest one.
For point :
- Distance to :
- Distance to :
- is assigned to Cluster 1 (closer to )
For point :
- Distance to :
- Distance to :
- is assigned to Cluster 2 (closer to )
Continuing this process for all points:
- Cluster 1: , , ,
- Cluster 2: , , ,
Step 3: Update Step (First Iteration)
Now we recalculate the centroids as the mean of points in each cluster.
For Cluster 1:
For Cluster 2:
Step 4: Convergence Check
The centroids haven't changed, so the algorithm has converged!
Final Result:
- Cluster 1: with centroid
- Cluster 2: with centroid
Verification:
Let's verify that no point would change clusters if we reassigned them:
- All points in Cluster 1 are closer to than to
- All points in Cluster 2 are closer to than to
The algorithm has successfully identified two distinct clusters in our data.
Let's visualize this step-by-step example to see how the algorithm works:



Here you can see the complete K-means process on our simple 8-point example, showing how the algorithm successfully identifies the two natural clusters in the data.
In this example we've chosen random initial centroids that conveniently were located in the middle of the two clusters to make the example simple. In practice, we should use the k-means++ initialization method to choose the initial centroids.