Every customer looks the same on a spreadsheet. A name, an income figure, a spending number. Nothing more.
But real customers behave in very different ways. Some spend big.However, Some barely spend at all. Some earn a lot but hold back. Others earn little yet spend freely.
Customer segmentation with K-Means finds these hidden patterns. It turns a flat table of numbers into groups you can actually understand. This article walks through a full mini project, step by step, using a real dataset. You will see the code, the logic, and the business reasoning behind every decision.
This project builds directly on ideas from earlier episodes in the Intelevo ML series. However, you do not need to watch every prior video to follow along. Each concept gets a plain-language explanation here, so you can jump straight in.
By the end, you will know how to load raw customer data, cluster it, score the clustering, and translate the output into segments a marketing team could use tomorrow morning. Along the way, you will also learn where beginners typically go wrong, so you can sidestep those mistakes entirely.
What Is Customer Segmentation, Really?
Picture a mountain of unsorted mail. Every letter looks identical from a distance. Yet each one belongs to a different person, with different needs.
Customer segmentation sorts that mountain into a few labeled piles. Instead of treating every customer the same way, you group similar customers together. Then, you give each group a name and a plan.
This matters because a one-size-fits-all message rarely works well. A luxury offer means nothing to a budget-conscious shopper. A discount code feels almost insulting to a high-value loyal customer. Segmentation solves this mismatch.
Under the hood, segmentation relies on clustering algorithms. K-Means is the most common choice. It groups data points based on how close they sit to each other in numerical space. Two customers with similar income and similar spending habits end up in the same cluster.
Two additional tools complete the picture: the Silhouette Score and the Davies-Bouldin Index. Both metrics measure how well a clustering result actually works. Together, they remove the guesswork from choosing the right number of clusters.
A Quick Refresher On How K-Means Groups Customers
K-Means works through repetition. First, it places a set number of center points, called centroids, somewhere in the data. Then, it assigns every customer to the nearest centroid.
Next, it recalculates each centroid based on the average position of its assigned customers. The algorithm repeats this cycle again and again. Eventually, the centroids stop moving. At that point, the clusters have settled into their final shape.
This process sounds simple, and honestly, it is. Yet the results depend heavily on two things: how many clusters you choose, and whether every feature carries fair weight in the distance calculation. This mini project solves both issues directly.
Meet The Dataset
This project uses a classic dataset: two hundred mall customers. Only two columns matter here — annual income and a spending score from 1 to 100.
Take a look at a few sample rows.
| CustomerID | Annual Income (k$) | Spending Score (1–100) |
|---|---|---|
| 1 | 15 | 39 |
| 2 | 16 | 81 |
| 3 | 17 | 6 |
| 4 | 78 | 92 |
| 5 | 76 | 4 |
Notice something interesting. Customers 4 and 5 earn almost the same income. Yet their spending scores sit at opposite extremes. One spends heavily. The other barely spends at all.
This gap is exactly what makes segmentation useful. Income alone never tells the full story. Behavior fills in the rest.
The Four-Stage Pipeline
Every good mini project follows a clear structure. This one breaks into four stages.
First, Prepare. Load the data, then scale the features so no single column dominates the math.
Second, Cluster. Run K-Means across a range of possible group counts.
Third, Evaluate. Score every candidate using the Silhouette Score and the Davies-Bouldin Index. Keep the winner.
Fourth, Profile and Name. Translate the winning clusters into segments a real business can act on.
This same shape works for almost any segmentation project, regardless of industry. Let’s walk through each stage in code.
Step 1: Load And Explore The Data
Start simple. Load the file, then look before you leap.
import pandas as pd
df = pd.read_csv("mall_customers.csv")
print(df.shape)
print(df.isna().sum())
X = df[["Annual_Income", "Spending_Score"]]
X.describe()
The read_csv() function loads the raw table into memory. Next, df.shape and isna().sum() confirm there is nothing missing to clean up. This step feels small, but it saves headaches later.
After that, the code slices out only the two columns that matter for clustering. There is no need to carry the customer ID or gender column into the math. Keep the feature set lean and focused.
Finally, X.describe() reveals something important. Income sits in the tens of thousands. Spending score sits between 1 and 100. These two columns live on completely different scales. As a result, the next step becomes essential, not optional.
Step 2: Scale The Features
K-Means measures distance between points. Therefore, any column with larger raw numbers will quietly dominate the result. Income, left unscaled, would drown out spending score entirely.
The fix is straightforward.
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# z = (x - mean) / std
print(X_scaled[:3].round(2))
StandardScaler rewrites every column using a simple formula: subtract the mean, then divide by the standard deviation. Each column now carries the same weight in the distance calculation.
From this point forward, every clustering step uses X_scaled. The original X still comes in handy later, though, for producing readable summaries that people outside data science can understand.
Step 3: Let The Silhouette Score Pick k
Choosing the right number of clusters trips up many beginners. Some guess. Others eyeball a chart and hope for the best. Neither approach scales well.
Instead, let the data decide.
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
scores = []
for k in range(2, 9):
km = KMeans(n_clusters=k, n_init=10, random_state=42)
labels = km.fit_predict(X_scaled)
scores.append((k, silhouette_score(X_scaled, labels)))
best_k = max(scores, key=lambda p: p[1])[0]
print(f"Best k: {best_k}")
This loop tries every value of k between 2 and 8. For each one, it fits a K-Means model, then calculates the Silhouette Score. A higher score means tighter, better-separated clusters.
After the loop finishes, max() picks the k with the strongest score. For this dataset, that number comes out to 5. In other words, the data naturally splits into five distinct behavioral groups.
No elbow chart squinting required. The metric already points to the answer.
Step 4: Fit The Final Model And Confirm Quality
With the winning k in hand, fit the final model and lock in the results.
from sklearn.metrics import davies_bouldin_score
final_km = KMeans(n_clusters=5, n_init=10, random_state=42)
df["Cluster"] = final_km.fit_predict(X_scaled)
sil = silhouette_score(X_scaled, df["Cluster"])
db = davies_bouldin_score(X_scaled, df["Cluster"])
print(f"Silhouette: {sil:.2f}")
print(f"Davies-Bouldin: {db:.2f}")
Notice the change here. fit_predict() now writes the cluster label directly onto the original dataframe. This step matters because it keeps the raw, human-readable values connected to each customer’s group.
The two evaluation metrics confirm the split holds up. Silhouette lands near 0.55. Davies-Bouldin lands near 0.57. Both numbers sit comfortably in a healthy range, which means the clusters separate cleanly rather than blurring into each other.
At this point, the dataframe holds everything needed for the next stage: raw customer values, plus one clear cluster label per row.
Turning Clusters Into Segments
A cluster number alone means nothing to a marketing team. Cluster 3 tells nobody anything useful. However, one line of code changes that completely.
df.groupby("Cluster")[["Annual_Income", "Spending_Score"]].mean()
This single command groups every customer by their cluster label, then averages the two key columns. The result reads like a story.
| Cluster | Avg Income | Avg Spending | Segment Name |
|---|---|---|---|
| 0 | $25k | 20 | Careful Savers |
| 1 | $88k | 17 | At-Risk High Value |
| 2 | $26k | 78 | Budget-Conscious Spenders |
| 3 | $87k | 82 | Premium Loyalists |
| 4 | $55k | 50 | Standard Shoppers |
Look closely at cluster 0. Low income, low spending. That pattern describes someone careful with money. Meanwhile, cluster 3 shows high income and high spending together. That combination describes a loyal, high-value shopper.
Every segment name comes directly from these averages. You never invent a name. You never guess one. The algorithm only ever hands you group numbers; the naming step turns those numbers into something people recognize.
Meet Your Segments
Three segments deserve immediate attention from any marketing team.
Premium Loyalists earn well and spend well. Protect this group first. Early access programs and loyalty perks keep them engaged and prevent them from drifting toward competitors.
At-Risk High Value customers earn just as much as the Premium Loyalists. Yet they barely spend. This gap deserves investigation. Perhaps they feel unengaged. Perhaps a competitor already won their attention elsewhere.
Budget-Conscious Spenders earn less, but they spend actively despite that constraint. This group responds well to value bundles, seasonal discounts, and smart pricing tiers.
Two additional groups sit in the middle ground. Still, these three tell a marketing team exactly where to focus energy first.
Why This Matters For Real Businesses
Segmentation only earns its value once it changes what someone does next. Consider three concrete outcomes.
First, campaigns become targeted rather than generic. Premium Loyalists receive loyalty perks. Budget-Conscious Spenders receive discount codes. Nobody gets a message that misses the mark.
Second, a win-back strategy becomes possible. At-Risk High Value customers get a re-engagement nudge before they disappear for good. Catching this signal early can save a relationship that otherwise quietly fades.
Third, the entire pipeline becomes repeatable. Run this same script again next quarter. Watch which customers shift between segments over time. That movement itself becomes a valuable signal, revealing changing habits before they show up in revenue reports.
Fourth, segmentation improves communication across teams. A product manager, a marketer, and a sales lead can all discuss “Premium Loyalists” and immediately understand who that means. Nobody needs to interpret a raw cluster number or dig through a spreadsheet first.
In short, five simple numbers per customer become a genuine business strategy.
Common Pitfalls To Avoid
A few mistakes trip up beginners working with real-world segmentation data. Watch out for these three.
Skipping the scaler. Forget StandardScaler, and the column with the largest numbers silently controls every cluster. Income, left unscaled, would overpower spending score every time.
Over-segmenting. Ten clusters might look impressive in a slide deck. However, a marketing team cannot realistically act on ten different strategies at once. Four or five segments usually work far better in practice.
Naming from guesswork. Always name a segment using its actual group averages. Never rely on a glance at a scatterplot. Numbers tell the truth; visual impressions sometimes mislead.
Avoiding these three mistakes turns a technically correct clustering result into something genuinely useful.
Key Takeaways
Let’s lock in what matters most from this project.
Scale your features first. Both K-Means and Davies-Bouldin depend entirely on distance calculations, so unscaled data quietly breaks everything downstream.
Let the Silhouette Score choose your cluster count. Skip the guesswork and skip the elbow chart squinting.
Use groupby("Cluster").mean() to turn raw numbers into a story anyone can understand.
Finally, remember this rule above all else: a segment only counts if someone can act on it right away. Clustering without action stays purely academic. Clustering with action becomes strategy.
Where This Fits In The Bigger Picture
This mini project pulls together several earlier lessons from the Intelevo ML series. Clustering itself came from earlier episodes covering K-Means and hierarchical linkage. Cluster evaluation, meanwhile, came from the episode on the Silhouette Score and the Davies-Bouldin Index.
This project introduces nothing new algorithmically. Instead, it shows how those separate pieces snap together into one working pipeline. That, ultimately, is what a real data science workflow looks like in practice: familiar tools, applied in the right sequence, against a dataset you have never seen before.
Watch The Full Walkthrough
This article covers the core ideas, but the video walks through every line of code on screen, alongside visual explanations of each concept. Watch the full episode on the Intelevo YouTube channel for the complete demonstration, including live output at every stage of the pipeline.
The next episode moves into feature engineering and feature selection techniques. That topic builds the inputs that make every future model stronger, right from the very first column. Subscribe to Intelevo so you never miss an episode in this growing machine learning series.
