Customer Segmentation Project
Customer Segmentation Project
Build a real-world clustering model that groups customers based on their behavior using K-Means.
Project Overview
In this hands-on project, we'll build a Customer Segmentation Model using K-Means Clustering. The goal is to group customers based on their annual income and spending behavior, helping businesses make smart, data-driven decisions.
Project Objectives
- Understand customer data and clean it.
- Perform Exploratory Data Analysis (EDA).
- Apply scaling and preprocessing.
- Use the Elbow Method to choose optimal K.
- Apply K-Means Clustering.
- Evaluate cluster quality using Silhouette Score.
- Visualize and interpret customer segments.
Prerequisites
- Python 3.x
- Jupyter Notebook / Google Colab
- Libraries: pandas, numpy, matplotlib, seaborn, scikit-learn
pip install pandas numpy matplotlib seaborn scikit-learn
Project Workflow
Step-by-Step Plan
- Import libraries
- Load dataset
- Perform EDA
- Feature selection
- Scale features
- Use Elbow Method
- Apply K-Means
- Visualize clusters
- Interpret segments
- Suggest business insights
Step 1: Import Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import silhouette_score
Step 2: Create / Load Dataset
For demonstration, we'll create a sample dataset of mall customers.
data = {
"CustomerID": list(range(1, 21)),
"Age": [19, 21, 20, 23, 31, 22, 35, 45, 60, 55,
30, 40, 28, 33, 50, 27, 42, 38, 47, 25],
"Annual_Income": [15, 16, 17, 18, 20, 25, 35, 40, 50, 55,
45, 60, 70, 75, 80, 90, 95, 100, 110, 120], # in $1000
"Spending_Score": [39, 81, 6, 77, 40, 76, 6, 94, 3, 72,
55, 65, 50, 60, 20, 90, 30, 85, 25, 95] # 1-100
}
df = pd.DataFrame(data)
print(df.head())
Step 3: Data Exploration
print(df.shape)
print(df.info())
print(df.describe())
print(df.isnull().sum())
Visualize the distribution of each feature:
sns.pairplot(df[["Age", "Annual_Income", "Spending_Score"]])
plt.show()
Step 4: Feature Selection
For segmentation, we'll use two key features:
X = df[["Annual_Income", "Spending_Score"]]
print(X.head())
Step 5: Feature Scaling
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
Step 6: Find Optimal K Using Elbow Method
wcss = []
for k in range(1, 11):
km = KMeans(n_clusters=k, init="k-means++", random_state=42, n_init=10)
km.fit(X_scaled)
wcss.append(km.inertia_)
plt.plot(range(1, 11), wcss, marker="o", color="red")
plt.title("Elbow Method")
plt.xlabel("Number of Clusters (K)")
plt.ylabel("WCSS")
plt.grid(True)
plt.show()
Step 7: Apply K-Means with Optimal K
kmeans = KMeans(n_clusters=5, init="k-means++", random_state=42, n_init=10)
y_kmeans = kmeans.fit_predict(X_scaled)
df["Cluster"] = y_kmeans
print(df.head())
Step 8: Evaluate Cluster Quality
score = silhouette_score(X_scaled, y_kmeans)
print(f"Silhouette Score: {score:.3f}")
Step 9: Visualize Clusters
plt.figure(figsize=(8, 6))
sns.scatterplot(
x=X["Annual_Income"], y=X["Spending_Score"],
hue=y_kmeans, palette="viridis", s=100
)
plt.scatter(
scaler.inverse_transform(kmeans.cluster_centers_)[:, 0],
scaler.inverse_transform(kmeans.cluster_centers_)[:, 1],
s=200, c="red", marker="X", label="Centroids"
)
plt.title("Customer Segments")
plt.xlabel("Annual Income (k$)")
plt.ylabel("Spending Score")
plt.legend()
plt.show()
Step 10: Interpret Customer Segments
Based on income and spending behavior, here are typical clusters:
| Cluster | Income | Spending | Customer Type |
|---|---|---|---|
| 0 | Low | Low | Budget Customers |
| 1 | Low | High | Careless Spenders |
| 2 | High | Low | Cautious Wealthy |
| 3 | High | High | Premium Customers |
| 4 | Medium | Medium | Average Buyers |
Business Insights & Strategies
Budget Customers
- Offer discounts
- Promote affordable products
Careless Spenders
- Loyalty programs
- Targeted upsells
Cautious Wealthy
- Highlight premium quality
- Use trust-based marketing
Premium Customers
- Exclusive offers
- VIP membership programs
Average Buyers
- General promotions
- Cross-selling strategies
Bonus: Save the Model
import joblib
joblib.dump(kmeans, "customer_segmentation_model.pkl")
joblib.dump(scaler, "scaler.pkl")
# Load and Predict
loaded_model = joblib.load("customer_segmentation_model.pkl")
loaded_scaler = joblib.load("scaler.pkl")
new_customer = [[70, 80]] # Annual Income, Spending Score
prediction = loaded_model.predict(loaded_scaler.transform(new_customer))
print("Predicted Cluster:", prediction[0])
Suggested Project Folder Structure
customer_segmentation_project/
│
├── data/
│ └── customers.csv
├── notebooks/
│ └── customer_segmentation.ipynb
├── models/
│ └── customer_segmentation_model.pkl
├── visualizations/
│ ├── elbow_plot.png
│ └── cluster_plot.png
├── requirements.txt
└── README.md
Real-Life Analogy
Customer Segmentation = Store Layout
Just like supermarkets group similar products together (dairy, snacks, beverages), businesses group similar customers to better serve them. Clustering automates this process using data.
Real-World Applications
E-Commerce
- Personalized recommendations
- Targeted marketing campaigns
Banking
- Customer profiling
- Loan and credit segmentation
Telecom
- Plan recommendation
- Churn prediction
Retail & FMCG
- Sales optimization
- Inventory planning
Healthcare
- Patient segmentation
- Personalized care plans
OTT / Streaming
- Group users by interests
- Recommendation engines
Common Mistakes to Avoid
Best Practices
Quick Tips
- Use clean and recent customer data.
- Combine Elbow + Silhouette to choose K.
- Standardize features before clustering.
- Use PCA for high-dimensional data.
- Always interpret clusters in business context.
- Save models for reuse.
What You Learned
Data Handling
- Cleaning & visualization
- Feature selection
Clustering Skills
- Apply K-Means
- Evaluate using Silhouette
Visualization
- Cluster visualization
- Elbow & Silhouette plots
Business Insight
- Interpret clusters
- Suggest marketing actions
Golden Rule
Key Takeaway
This Customer Segmentation Project demonstrates how clustering algorithms like K-Means can transform raw customer data into actionable business insights. By identifying meaningful segments, businesses can deliver personalized experiences, boost sales, and improve customer satisfaction.