| """ |
| Customer Segmentation — K-Means RFM + DBSCAN Anomaly Detection |
| ================================================================ |
| CLO5: K-Means, K-Medoids, DBSCAN |
| |
| 1. RFM Analysis (Recency, Frequency, Monetary) |
| 2. K-Means Clustering with Elbow + Silhouette |
| 3. DBSCAN for anomaly/outlier detection |
| 4. Segment profiling & business recommendations |
| |
| Usage: |
| python analytics/customer_segmentation.py --data-dir ./data/raw |
| """ |
|
|
| import os, sys, logging, argparse |
| import pandas as pd |
| import numpy as np |
| from sklearn.cluster import KMeans, DBSCAN |
| from sklearn.preprocessing import StandardScaler |
| from sklearn.metrics import silhouette_score |
| import matplotlib |
| matplotlib.use('Agg') |
| import matplotlib.pyplot as plt |
| import warnings |
| warnings.filterwarnings('ignore') |
|
|
| logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s') |
| logger = logging.getLogger(__name__) |
|
|
|
|
| def compute_rfm(data_dir: str) -> pd.DataFrame: |
| """Tính RFM từ Olist dataset.""" |
| orders = pd.read_csv(os.path.join(data_dir, 'olist_orders_dataset.csv'), |
| parse_dates=['order_purchase_timestamp']) |
| items = pd.read_csv(os.path.join(data_dir, 'olist_order_items_dataset.csv')) |
| customers = pd.read_csv(os.path.join(data_dir, 'olist_customers_dataset.csv')) |
|
|
| |
| orders = orders[orders['order_status'] == 'delivered'].dropna(subset=['order_purchase_timestamp']) |
|
|
| |
| order_revenue = items.groupby('order_id').agg(revenue=('price', 'sum')).reset_index() |
| merged = orders.merge(order_revenue, on='order_id', how='left') |
| merged = merged.merge(customers[['customer_id', 'customer_unique_id', 'customer_state']], |
| on='customer_id', how='left') |
|
|
| |
| ref_date = merged['order_purchase_timestamp'].max() + pd.Timedelta(days=1) |
|
|
| |
| rfm = merged.groupby('customer_unique_id').agg( |
| recency=('order_purchase_timestamp', lambda x: (ref_date - x.max()).days), |
| frequency=('order_id', 'nunique'), |
| monetary=('revenue', 'sum'), |
| state=('customer_state', 'first'), |
| ).reset_index() |
|
|
| rfm['monetary'] = rfm['monetary'].round(2) |
| logger.info(f"[RFM] {len(rfm)} unique customers") |
| logger.info(f" Recency: mean={rfm['recency'].mean():.0f}, median={rfm['recency'].median():.0f}") |
| logger.info(f" Frequency: mean={rfm['frequency'].mean():.2f}, max={rfm['frequency'].max()}") |
| logger.info(f" Monetary: mean={rfm['monetary'].mean():.0f}, median={rfm['monetary'].median():.0f}") |
| return rfm |
|
|
|
|
| def kmeans_segmentation(rfm: pd.DataFrame, output_dir: str): |
| """K-Means clustering with optimal K selection.""" |
| features = ['recency', 'frequency', 'monetary'] |
| X = rfm[features].copy() |
|
|
| |
| for col in features: |
| p99 = X[col].quantile(0.99) |
| X[col] = X[col].clip(upper=p99) |
|
|
| scaler = StandardScaler() |
| X_scaled = scaler.fit_transform(X) |
|
|
| |
| K_range = range(2, 9) |
| inertias, silhouettes = [], [] |
| for k in K_range: |
| km = KMeans(n_clusters=k, random_state=42, n_init=10, max_iter=300) |
| labels = km.fit_predict(X_scaled) |
| inertias.append(km.inertia_) |
| sil = silhouette_score(X_scaled, labels) |
| silhouettes.append(sil) |
| logger.info(f" K={k}: Inertia={km.inertia_:.0f}, Silhouette={sil:.4f}") |
|
|
| best_k = list(K_range)[np.argmax(silhouettes)] |
| logger.info(f" Best K by Silhouette: {best_k}") |
|
|
| |
| km_final = KMeans(n_clusters=best_k, random_state=42, n_init=10) |
| rfm['cluster'] = km_final.fit_predict(X_scaled) |
|
|
| |
| rfm['r_score'] = pd.qcut(rfm['recency'], q=5, labels=[5, 4, 3, 2, 1], duplicates='drop').astype(int) |
| rfm['f_score'] = pd.qcut(rfm['frequency'].rank(method='first'), q=5, labels=[1, 2, 3, 4, 5], |
| duplicates='drop').astype(int) |
| rfm['m_score'] = pd.qcut(rfm['monetary'].rank(method='first'), q=5, labels=[1, 2, 3, 4, 5], |
| duplicates='drop').astype(int) |
|
|
| |
| profiles = rfm.groupby('cluster').agg( |
| count=('customer_unique_id', 'count'), |
| avg_recency=('recency', 'mean'), |
| avg_frequency=('frequency', 'mean'), |
| avg_monetary=('monetary', 'mean'), |
| ).round(1) |
|
|
| segment_names = {} |
| for idx, row in profiles.iterrows(): |
| if row['avg_recency'] < profiles['avg_recency'].median() and row['avg_frequency'] > profiles['avg_frequency'].median(): |
| if row['avg_monetary'] > profiles['avg_monetary'].median(): |
| segment_names[idx] = 'Champions' |
| else: |
| segment_names[idx] = 'Loyal' |
| elif row['avg_recency'] < profiles['avg_recency'].median(): |
| segment_names[idx] = 'New/Promising' |
| elif row['avg_frequency'] > profiles['avg_frequency'].median(): |
| segment_names[idx] = 'At Risk' |
| else: |
| segment_names[idx] = 'Lost/Hibernating' |
|
|
| rfm['segment'] = rfm['cluster'].map(segment_names) |
| profiles['segment'] = profiles.index.map(segment_names) |
|
|
| print(f"\n CUSTOMER SEGMENTS (K={best_k}):") |
| print(profiles.to_string()) |
|
|
| |
| fig, axes = plt.subplots(2, 2, figsize=(14, 10)) |
|
|
| |
| axes[0, 0].plot(list(K_range), inertias, 'bo-') |
| axes[0, 0].set_xlabel('K') |
| axes[0, 0].set_ylabel('Inertia') |
| axes[0, 0].set_title('Elbow Method') |
|
|
| |
| axes[0, 1].plot(list(K_range), silhouettes, 'ro-') |
| axes[0, 1].set_xlabel('K') |
| axes[0, 1].set_ylabel('Silhouette Score') |
| axes[0, 1].set_title('Silhouette Method') |
| axes[0, 1].axvline(x=best_k, color='green', linestyle='--', label=f'Best K={best_k}') |
| axes[0, 1].legend() |
|
|
| |
| colors = ['#e74c3c', '#3498db', '#2ecc71', '#f39c12', '#9b59b6', '#1abc9c', '#e67e22'] |
| for cluster in range(best_k): |
| mask = rfm['cluster'] == cluster |
| name = segment_names.get(cluster, f'C{cluster}') |
| axes[1, 0].scatter(rfm.loc[mask, 'recency'], rfm.loc[mask, 'monetary'], |
| c=colors[cluster % len(colors)], label=name, alpha=0.4, s=15) |
| axes[1, 0].set_xlabel('Recency (days)') |
| axes[1, 0].set_ylabel('Monetary (BRL)') |
| axes[1, 0].set_title('Customer Segments') |
| axes[1, 0].legend(fontsize=8) |
|
|
| |
| seg_counts = rfm['segment'].value_counts() |
| seg_counts.plot(kind='bar', ax=axes[1, 1], color=[colors[i % len(colors)] for i in range(len(seg_counts))], |
| alpha=0.8) |
| axes[1, 1].set_title('Segment Size') |
| axes[1, 1].set_ylabel('Customers') |
| axes[1, 1].tick_params(axis='x', rotation=30) |
|
|
| plt.suptitle('K-Means Customer Segmentation (RFM)', fontsize=14, fontweight='bold') |
| plt.tight_layout() |
| path = os.path.join(output_dir, 'customer_segmentation.png') |
| plt.savefig(path, dpi=150, bbox_inches='tight') |
| plt.close() |
| logger.info(f"[VIZ] Saved: {path}") |
|
|
| return rfm |
|
|
|
|
| def dbscan_anomaly(rfm: pd.DataFrame, output_dir: str): |
| """DBSCAN để phát hiện anomaly customers.""" |
| features = ['recency', 'frequency', 'monetary'] |
| X = rfm[features].copy() |
| for c in features: |
| X[c] = X[c].clip(upper=X[c].quantile(0.99)) |
|
|
| scaler = StandardScaler() |
| X_scaled = scaler.fit_transform(X) |
|
|
| |
| db = DBSCAN(eps=0.8, min_samples=10) |
| labels = db.fit_predict(X_scaled) |
|
|
| n_clusters = len(set(labels)) - (1 if -1 in labels else 0) |
| n_noise = (labels == -1).sum() |
|
|
| rfm['dbscan_label'] = labels |
| rfm['is_anomaly'] = (labels == -1).astype(int) |
|
|
| logger.info(f"[DBSCAN] Clusters: {n_clusters}, Noise/Anomalies: {n_noise} ({n_noise/len(rfm)*100:.1f}%)") |
|
|
| |
| anomalies = rfm[rfm['is_anomaly'] == 1] |
| normal = rfm[rfm['is_anomaly'] == 0] |
|
|
| print(f"\n DBSCAN ANOMALY DETECTION:") |
| print(f" Normal customers: {len(normal):,}") |
| print(f" Anomaly customers: {len(anomalies):,} ({len(anomalies)/len(rfm)*100:.1f}%)") |
| print(f"\n Anomaly profile vs Normal:") |
| for feat in features: |
| print(f" {feat}: Anomaly avg={anomalies[feat].mean():.1f} vs Normal avg={normal[feat].mean():.1f}") |
|
|
| |
| fig, ax = plt.subplots(figsize=(10, 6)) |
| ax.scatter(normal['recency'], normal['monetary'], c='#3498db', alpha=0.3, s=10, label='Normal') |
| ax.scatter(anomalies['recency'], anomalies['monetary'], c='#e74c3c', alpha=0.8, s=40, |
| marker='x', label=f'Anomaly ({len(anomalies)})') |
| ax.set_xlabel('Recency (days)') |
| ax.set_ylabel('Monetary (BRL)') |
| ax.set_title('DBSCAN Anomaly Detection on Customer RFM') |
| ax.legend() |
| path = os.path.join(output_dir, 'dbscan_anomaly_customers.png') |
| plt.savefig(path, dpi=150, bbox_inches='tight') |
| plt.close() |
| logger.info(f"[VIZ] Saved: {path}") |
|
|
| return rfm |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description='Customer Segmentation') |
| parser.add_argument('--data-dir', type=str, default='./data/raw') |
| parser.add_argument('--output-dir', type=str, default='./data/analytics') |
| args = parser.parse_args() |
| os.makedirs(args.output_dir, exist_ok=True) |
|
|
| rfm = compute_rfm(args.data_dir) |
| rfm = kmeans_segmentation(rfm, args.output_dir) |
| rfm = dbscan_anomaly(rfm, args.output_dir) |
|
|
| rfm.to_csv(os.path.join(args.output_dir, 'customer_segments.csv'), index=False) |
|
|
| |
| print(f"\n{'='*70}") |
| print(f" BUSINESS RECOMMENDATIONS") |
| print(f"{'='*70}") |
| for seg in rfm['segment'].unique(): |
| n = (rfm['segment'] == seg).sum() |
| avg_m = rfm.loc[rfm['segment'] == seg, 'monetary'].mean() |
| recs = { |
| 'Champions': 'Reward program, early access to new products', |
| 'Loyal': 'Upsell premium products, referral program', |
| 'New/Promising': 'Onboarding emails, first purchase discount', |
| 'At Risk': 'Win-back campaign, special offers', |
| 'Lost/Hibernating': 'Re-engagement email, survey for feedback', |
| } |
| print(f" {seg}: {n:,} customers, avg spend BRL {avg_m:,.0f}") |
| print(f" → {recs.get(seg, 'Standard marketing')}") |
| print(f"{'='*70}") |
|
|
|
|
| if __name__ == '__main__': |
| main() |
|
|