Machine Learning from Scratch – Day 13: Understanding K-Means Clustering
Understanding K-Means Clustering
Series: Machine Learning From Scratch (18 articles)
- …
- 13Machine Learning from Scratch – Day 13: Understanding K-Means Clustering This article
Machine Learning from Scratch – Day 13: Understanding K-Means Clustering
Introduction
In our previous articles, we explored supervised learning algorithms such as Logistic Regression, Decision Trees, Random Forest, KNN, Naive Bayes, and Support Vector Machines.
Most of these algorithms learn from labeled data, where the correct output is already provided.
But what happens when we have a dataset without labels?
Imagine an online shopping platform with thousands of customers. The platform has information about their purchasing habits, spending patterns, and product preferences.
However, nobody has labeled these customers as budget shoppers, frequent buyers, or premium customers.
Can a machine learning algorithm discover these groups automatically?
Yes! This is where K-Means Clustering becomes useful.
Today, we will explore one of the most popular unsupervised learning algorithms and understand how it groups similar data points.
1. What is K-Means Clustering?
K-Means is an unsupervised machine learning algorithm used to divide a dataset into K different clusters.
A cluster is simply a group of data points that are similar to one another.
The main objective of K-Means is to group data points so that:
- Points within the same cluster are relatively close to one another.
- Different clusters are separated as much as possible.
Unlike supervised learning, K-Means does not require predefined class labels.
Instead, it discovers patterns and structures directly from the data.
For example, a shopping platform might use K-Means to group customers based on their annual spending and purchase frequency.
2. Understanding Clusters and Centroids
Before understanding the algorithm, let's learn two important terms.
What is a Cluster?
A cluster is a collection of similar data points.
For example, suppose we have information about customers based on their spending habits.
K-Means might identify groups such as:
- Cluster 1: Customers with low spending.
- Cluster 2: Customers with moderate spending.
- Cluster 3: Customers with high spending.
These labels are interpretations we assign after examining the clusters. K-Means itself only produces cluster assignments.
What is a Centroid?
A centroid is the center point of a cluster.
It represents the average position of all data points assigned to that cluster.
For example, if a cluster contains three points:
(2, 4), (4, 6), (6, 8)
The centroid is calculated by taking the mean of each coordinate:
X coordinate:
(2 + 4 + 6) / 3 = 4
Y coordinate:
(4 + 6 + 8) / 3 = 6
Therefore, the centroid is:
(4, 6)
K-Means repeatedly updates these centroids until the cluster assignments stabilize or another stopping condition is reached.
3. How Does K-Means Work?
K-Means follows an iterative process.
Let's understand it step by step.
Step 1: Choose the Number of Clusters (K)
First, decide how many clusters you want the algorithm to create.
For example, if K = 3, the algorithm will create three clusters.
Step 2: Initialize Centroids
The algorithm selects three initial centroids.
These centroids act as starting points for the clustering process.
The initialization method can affect the final result. Scikit-learn commonly uses K-Means++ initialization.
Step 3: Assign Data Points
Calculate the distance between every data point and each centroid.
Assign each point to the cluster with the nearest centroid.
Step 4: Update Centroids
After assigning the points, calculate the mean position of the data points in each cluster.
These new mean positions become the updated centroids.
Step 5: Repeat the Process
Repeat the assignment and centroid-update steps until the assignments stop changing or the algorithm reaches its stopping criteria.
<image-placeholder />
The overall process can be summarized as:
Initialize → Assign → Update → Repeat → Final Clusters
4. Understanding the K-Means Objective Function
K-Means attempts to minimize the sum of squared distances between each data point and its assigned cluster centroid.
This is commonly called Within-Cluster Sum of Squares (WCSS) or inertia.
The objective function is:
J = Σᵢ₌₁ᴷ Σₓ∈Cᵢ ||x - μᵢ||²
Where:
- K represents the number of clusters.
- Cᵢ represents the points assigned to cluster i.
- x represents an individual data point.
- μᵢ represents the centroid of cluster i.
- ||x - μᵢ||² represents the squared Euclidean distance.
In simple terms, K-Means tries to keep data points as close as possible to their respective centroids.
A lower WCSS generally means points are more compact within their clusters.
However, WCSS usually decreases as K increases, so a lower value alone does not prove that a particular K is the best choice.
5. How Do We Choose the Correct Value of K?
One of the biggest challenges in K-Means is deciding how many clusters to create.
If we choose K = 2, the algorithm creates two clusters.
If we choose K = 5, it creates five clusters.
But how do we know which value is appropriate?
A popular technique is the Elbow Method.
Understanding the Elbow Method
The Elbow Method works by:
- Running K-Means with different values of K.
- Calculating the WCSS for each value.
- Plotting K against WCSS.
- Looking for a point where the decrease in WCSS begins to slow down significantly.
This point is called the elbow.
It provides a useful estimate of the number of clusters.
However, the elbow is not always clearly visible, so other methods such as silhouette analysis can also help.
6. What Is the Silhouette Score?
The Silhouette Score measures how well a data point fits within its assigned cluster compared with other clusters.
Its value ranges from -1 to +1.
- Close to +1: The point is well matched to its cluster.
- Around 0: The point may lie near a cluster boundary.
- Below 0: The point may be closer to another cluster.
A higher average silhouette score generally indicates better-separated and more cohesive clusters.
It is useful when comparing different values of K.
7. Why Is Feature Scaling Important in K-Means?
K-Means relies on distance calculations.
Consider a dataset containing:
- Age: 18–60
- Annual income: ₹2,00,000–₹20,00,000
Income has a much larger numerical range than age.
Without feature scaling, income could dominate the distance calculation and influence the clusters disproportionately.
To address this problem, we can use StandardScaler or MinMaxScaler.
Feature scaling is particularly important when features have different units or numerical ranges.
8. Implementing K-Means Using Python
Now let's implement K-Means using Scikit-learn.
We will use a customer segmentation dataset generated using Scikit-learn.
Our goal is to group customers based on two features: annual income and spending score.
Step 1: Import libraries
import matplotlib.pyplot as pltfrom sklearn.datasets import make_blobsfrom sklearn.cluster import KMeansfrom sklearn.preprocessing import StandardScalerStep 2: Generate a sample dataset
X, _ = make_blobs( n_samples=300, centers=3, cluster_std=1.0, random_state=42)We generate 300 data points with three underlying groups.
The underscore means we are intentionally ignoring the generated labels because we want to perform unsupervised clustering.
Step 3: Apply feature scaling
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)Scaling helps ensure that features contribute more comparably to distance calculations.
Step 4: Create and train the model
model = KMeans( n_clusters=3, random_state=42, n_init=10)
model.fit(X_scaled)Here:
-
n_clusters=3specifies the number of clusters.
-
random_state=42makes initialization reproducible.
-
n_init=10runs the algorithm with multiple initializations and retains the best result.
Step 5: Get cluster assignments
labels = model.labels_
centroids = model.cluster_centers_
print("Cluster assignments:", labels)print("Centroids:", centroids)Each data point receives a cluster label.
Step 6: Visualize the clusters
plt.scatter( X_scaled[:, 0], X_scaled[:, 1], c=labels, cmap="viridis")
plt.scatter( centroids[:, 0], centroids[:, 1], marker="X", s=200)
plt.xlabel("Feature 1")plt.ylabel("Feature 2")plt.title("K-Means Clustering")plt.show()The scatter plot displays the clusters, while the X markers represent their centroids.
You should see three groups of data points.
9. Advantages and Disadvantages of K-Means
Advantages | Disadvantages |
|---|---|
Simple and easy to implement | Requires choosing K in advance |
Efficient for many datasets | Sensitive to initial centroid positions |
Easy to interpret | Sensitive to outliers |
Works well with compact, separated clusters | Can struggle with irregularly shaped clusters |
Scales reasonably well for many datasets | Requires numerical features and meaningful distance calculations |
10. Real-World Applications of K-Means
K-Means is used in many practical applications.
1. Customer Segmentation
Businesses group customers based on purchasing behavior, spending patterns, and preferences.
2. Image Compression
Similar colors can be grouped together to reduce the number of distinct colors used in an image.
3. Document Clustering
Documents can be grouped based on their text features or vector representations.
4. Anomaly Detection
Points that are unusually far from cluster centers may be investigated as potential anomalies. However, distance alone does not guarantee that a point is anomalous.
5. Recommendation Systems
Customer or product groups can help identify similarities and support recommendation strategies.
11. Key Takeaways
Let's summarize what we learned today:
- K-Means is an unsupervised learning algorithm.
- It groups similar data points into clusters.
- K represents the number of clusters.
- A centroid represents the center of a cluster.
- The algorithm repeatedly assigns points and updates centroids.
- WCSS measures the compactness of clusters.
- The Elbow Method and Silhouette Score help evaluate different cluster counts.
- Feature scaling is important because K-Means relies on distances.
K-Means demonstrates how machine learning can discover hidden patterns without requiring labeled training data.
Coming Next – Day 14: Understanding Hierarchical Clustering
In our next article, we will explore Hierarchical Clustering, another unsupervised learning algorithm.
We will understand how clusters are formed step by step, the difference between agglomerative and divisive clustering, and how dendrograms help us visualize relationships between data points.
Series: Machine Learning From Scratch (18 articles)
- …
- 13Machine Learning from Scratch – Day 13: Understanding K-Means Clustering This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article