Treating all customers identically is a recipe for wasted marketing spend. In this class, we master Unsupervised Customer Segmentation by combining classical RFM Analysis with K-Means Clustering.
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
# Sample customer transaction dataset
np.random.seed(42)
n_cust = 500
df_rfm = pd.DataFrame({
'recency_days': np.random.exponential(scale=45, size=n_cust).astype(int),
'frequency_orders': np.random.poisson(lam=6, size=n_cust) + 1,
'monetary_value': np.random.exponential(scale=350, size=n_cust) + 25
})
# Step 1: Preprocessing & Scaling (Mandatory for distance-based clustering!)
scaler = StandardScaler()
rfm_scaled = scaler.fit_transform(df_rfm)
# Step 2: Determine optimal k using Silhouette Analysis
for k in range(2, 6):
km = KMeans(n_clusters=k, init='k-means++', random_state=42)
labels = km.fit_predict(rfm_scaled)
sil_score = silhouette_score(rfm_scaled, labels)
print(f"k = {k} → Silhouette Score: {sil_score:.4f}")
# Step 3: Fit final 3-cluster segmentation model
final_kmeans = KMeans(n_clusters=3, init='k-means++', random_state=42)
df_rfm['cluster_id'] = final_kmeans.fit_predict(rfm_scaled)
# Step 4: Cluster Profiling
profile = df_rfm.groupby('cluster_id').agg({
'recency_days': 'mean',
'frequency_orders': 'mean',
'monetary_value': 'mean',
'cluster_id': 'count'
}).rename(columns={'cluster_id': 'customer_count'})
print("\n--- Segment Business Profiles ---\n", profile.round(2))
Cluster 0 (Low Recency, High Frequency, High Monetary) represents your VIP Champions — enroll them in loyalty clubs. Cluster 1 (High Recency, Low Frequency) represents Lapsed / Churned Customers — target them with aggressive win-back email discounts.
Broaden your statistical analysis, Python data wrangling, and production engineering expertise:
Identify which customer segments exhibit the highest retention risk.
Reduce feature dimensions to visualize multi-dimensional clusters.
Display interactive customer segment profiles to marketing executives.
Execute an end-to-end customer analytics and segmentation project.