Skip to main content

Lesson 8 of 9

Mini Project: Multi-Dimensional Customer Segmentation & Behavior Profiling

Design and implement a complete customer segmentation pipeline for an e-commerce platform. The workflow preprocesses RFM (Recency, Frequency, Monetary) purchase attributes, applies PCA for dimensionality reduction, performs K-Means++ clustering with Silhouette optimization, and generates actionable marketing personas.

30 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Complete Customer Segmentation & Persona Generation Script

Complete Customer Segmentation & Persona Generation Script
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

# 1. SYNTHETIC E-COMMERCE RFM CUSTOMER DATASET
np.random.seed(42)
n_customers = 1500
df_cust = pd.DataFrame({
    'recency_days': np.random.exponential(scale=60, size=n_customers).clip(1, 365),
    'frequency_orders': np.random.poisson(lam=6, size=n_customers).clip(1, 50),
    'monetary_spend': np.random.lognormal(mean=5.5, sigma=1.0, size=n_customers),
    'avg_basket_items': np.random.normal(4, 1.5, size=n_customers).clip(1, 20),
    'discount_dependency': np.random.beta(2, 5, size=n_customers) # 0 to 1
})

# 2. STANDARDIZATION & OUTLIER MITIGATION
scaler = StandardScaler()
X_scaled = scaler.fit_transform(np.log1p(df_cust)) # Log1p mitigates positive skew

# 3. K-MEANS++ OPTIMIZATION
kmeans = KMeans(n_clusters=4, init='k-means++', n_init=10, random_state=42)
df_cust['cluster'] = kmeans.fit_predict(X_scaled)
sil = silhouette_score(X_scaled, df_cust['cluster'])

print("=== CUSTOMER SEGMENTATION CLUSTER PROFILES ===")
print(f"Overall Silhouette Clustering Score: {sil:.4f}")

# 4. COMPUTE PERSONA PROFILE TABLE (Median metrics per cluster)
persona_summary = df_cust.groupby('cluster').agg({
    'recency_days': 'median',
    'frequency_orders': 'median',
    'monetary_spend': 'median',
    'discount_dependency': 'median',
    'cluster': 'count'
}).rename(columns={'cluster': 'customer_count'})

# Assign domain marketing persona labels
persona_names = {
    0: 'Loyal VIP High-Spenders',
    1: 'Discount Bargain Hunters',
    2: 'At-Risk Churning Customers',
    3: 'New Low-Engagement Visitors'
}
persona_summary['Persona Name'] = persona_summary.index.map(persona_names)

print("\nCluster Persona Breakdown:")
print(persona_summary[['Persona Name', 'customer_count', 'recency_days', 'frequency_orders', 'monetary_spend']].to_string())

Pro Tip: Stable Cluster Profiling over Time

In production, customer behavior drifts. Re-clustering every month causes cluster IDs to scramble (Cluster 1 becomes Cluster 3). To maintain stable reporting, train K-Means once, freeze cluster centroids, and score incoming monthly cohorts using `kmeans.predict(new_data)`.

Diagram
Loading diagram…

MlCustomerSegmentationProject Visual Representation

Hands-On Challenge: Build a Radar Chart Profiler

Write a function that normalizes the median persona metrics to [0, 1] and plots a comparative radar (spider) chart displaying the distinctive strengths of each customer segment.

Quick Quiz & Key Concept Checks

Common Pitfall: Choosing Too Many Clusters

Selecting K=12 clusters might yield a marginally higher inertia score, but marketing teams cannot realistically execute 12 distinct campaigns. Aim for 3 to 5 actionable personas that map directly to business strategies.

Topics in This Module

0/9 done