K-Means groups similar data points into K clusters without any labels. Businesses use it for customer segmentation, for example finding “high income, low spending” customers to target with offers.
What You Will Learn
- How the K-Means algorithm works
- Choosing K with the elbow method and silhouette score
- Interpreting clusters
- Limitations of K-Means
Prerequisites
NumPy and scatter plots.
The Algorithm
1. Choose K and place K centroids (cluster centres), using the smart k-means++ start by default.
2. Assign each point to its nearest centroid.
3. Move each centroid to the mean of its assigned points.
4. Repeat steps 2–3 until the assignments stop changing.
It minimises inertia: the sum of squared distances from points to their centroid.
Step 1: Customer Data
import numpy as np
import pandas as pd
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=200,
centers=[[25, 80], [55, 50], [40, 20], [70, 85], [80, 20]],
cluster_std=6, random_state=42)
df = pd.DataFrame(X.round(1), columns=['income_k', 'spending_score'])
print(df.head())
Explanation: We simulate 200 mall customers with annual income (thousand ₹) and a spending score (1–100). In a real project you would load a file such as Mall_Customers.csv. There are no labels: the algorithm must find the groups itself. That is unsupervised learning.
income_k spending_score 0 63.4 41.6 1 53.8 51.8 2 33.8 78.6 3 81.9 15.0 4 41.3 12.5
Step 2: Choose K
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
for k in range(1, 9):
km = KMeans(n_clusters=k, n_init=10, random_state=42).fit(X)
s = round(silhouette_score(X, km.labels_), 3) if k > 1 else '-'
print(k, round(km.inertia_, 0), s)
Explanation: Elbow method: inertia always falls as K grows, but here it drops sharply up to K=5 and then flattens, forming an “elbow” at 5. Silhouette score (from -1 to 1, higher is better) measures how well each point fits its own cluster compared with the nearest other cluster, and it also peaks at K=5 (0.713). Both point to 5 clusters.
1 245480.0 - 2 112581.0 0.486 3 68147.0 0.572 4 33251.0 0.626 5 12673.0 0.713 6 11593.0 0.631 7 10629.0 0.549 8 9684.0 0.47
Step 3: Fit and Describe the Clusters
km = KMeans(n_clusters=5, n_init=10, random_state=42).fit(X)
df['cluster'] = km.labels_
print(df.groupby('cluster')[['income_k', 'spending_score']].mean().round(1)
.assign(size=df['cluster'].value_counts().sort_index()))
Explanation: The cluster numbers are arbitrary; the profiles are what matter.
| Cluster | Profile | Possible action |
|---|---|---|
| 0 | Middle income, low spending | Discount offers |
| 1 | Low income, high spending | Budget deals, watch credit risk |
| 2 | High income, high spending | Premium / loyalty programme |
| 3 | High income, low spending | Targeted campaigns, best growth potential |
| 4 | Average on both | Standard marketing |
income_k spending_score size cluster 0 40.0 20.9 39 1 24.0 79.6 40 2 71.4 84.3 40 3 80.3 20.5 40 4 54.2 50.2 41
Step 4: Assign New Customers
print(km.predict([[30, 75], [78, 22]]))
[1 3]
Step 5: Plot
import matplotlib.pyplot as plt
plt.scatter(df['income_k'], df['spending_score'], c=df['cluster'], cmap='tab10')
plt.scatter(km.cluster_centers_[:, 0], km.cluster_centers_[:, 1], c='black', marker='X', s=200)
plt.xlabel('Income (k)'); plt.ylabel('Spending score'); plt.show()
Limitations
| Issue | Notes |
|---|---|
| K must be chosen | Use elbow + silhouette + business sense |
| Assumes round, similar-size clusters | Use DBSCAN or Gaussian Mixture for other shapes |
| Sensitive to scale | Scale features when units differ (StandardScaler) |
| Sensitive to outliers | Outliers pull centroids |
Common Errors
| Problem | Cause and fix |
|---|---|
| Different results each run | Set random_state; keep n_init=10 or more. |
| One feature dominates | Scale features first. |
Practice Exercises
- Add an age feature, scale all three, and re-cluster.
- Try DBSCAN on the same data.
Interview Questions
Q: What does K-Means minimise?
Within-cluster sum of squared distances (inertia).
Q: How do you choose K?
Elbow method, silhouette score, and domain knowledge.
Q: Supervised or unsupervised?
Unsupervised.
Summary
K-Means assigns points to the nearest of K centroids and updates them until stable. Choose K with elbow and silhouette, scale features, and interpret clusters by their averages.
Next: Hierarchical Clustering · PCA
Machine Learning Tutorials, Courses and Certifications