-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustomer_segmentation.py
More file actions
160 lines (131 loc) · 6.46 KB
/
Copy pathcustomer_segmentation.py
File metadata and controls
160 lines (131 loc) · 6.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import silhouette_score
from sklearn.decomposition import PCA
# ── 1. Load / Generate Dataset ────────────────────────────
# To use your own data: df = pd.read_csv("your_customer_data.csv")
np.random.seed(42)
n = 10000
df = pd.DataFrame({
'customer_id': range(1, n + 1),
'age': np.random.normal(40, 12, n).clip(18, 75).astype(int),
'annual_income': np.random.normal(55000, 20000, n).clip(15000, 120000).round(0),
'spending_score': np.random.randint(1, 101, n).astype(float),
'purchase_freq': np.random.poisson(8, n).clip(1, 30),
'avg_order_value': np.random.normal(200, 80, n).clip(20, 500).round(2),
'tenure_months': np.random.randint(1, 60, n),
'returns_count': np.random.poisson(1, n).clip(0, 10),
})
# Introduce missing values for cleaning demo
df.loc[np.random.choice(df.index, 150), 'annual_income'] = np.nan
df.loc[np.random.choice(df.index, 100), 'spending_score'] = np.nan
# ── 2. EDA ────────────────────────────────────────────────
print("=" * 50)
print("EXPLORATORY DATA ANALYSIS")
print("=" * 50)
print(df.describe().round(2))
print(f"\nMissing values:\n{df.isnull().sum()}")
# ── 3. Preprocessing ──────────────────────────────────────
df['annual_income'] = df['annual_income'].fillna(df['annual_income'].median())
df['spending_score'] = df['spending_score'].fillna(df['spending_score'].median())
# Customer Lifetime Value
df['clv'] = (df['avg_order_value'] * df['purchase_freq'] * (df['tenure_months'] / 12)).round(2)
features = ['age', 'annual_income', 'spending_score',
'purchase_freq', 'avg_order_value', 'tenure_months', 'clv']
X = df[features].copy()
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# ── 4. Find Optimal k ─────────────────────────────────────
print("\n" + "=" * 50)
print("FINDING OPTIMAL NUMBER OF CLUSTERS")
print("=" * 50)
inertias, silhouettes = [], []
K_range = range(2, 11)
for k in K_range:
km = KMeans(n_clusters=k, random_state=42, n_init=10)
labels = km.fit_predict(X_scaled)
inertias.append(km.inertia_)
score = silhouette_score(X_scaled, labels, sample_size=2000, random_state=42)
silhouettes.append(score)
print(f"k={k} | Inertia: {km.inertia_:,.0f} | Silhouette: {score:.4f}")
best_k = list(K_range)[silhouettes.index(max(silhouettes))]
print(f"\nBest k by silhouette score: {best_k}")
# ── 5. Final KMeans Model (k=4) ───────────────────────────
print("\n" + "=" * 50)
print("FINAL MODEL: KMeans (k=4)")
print("=" * 50)
kmeans = KMeans(n_clusters=4, random_state=42, n_init=10)
df['cluster'] = kmeans.fit_predict(X_scaled)
final_sil = silhouette_score(X_scaled, df['cluster'], sample_size=2000, random_state=42)
print(f"Silhouette Score: {final_sil:.4f}")
# ── 6. Cluster Profiling ──────────────────────────────────
profile = df.groupby('cluster')[features].mean().round(2)
print("\nCluster Profiles:")
print(profile)
segment_names = {
0: 'Budget Shoppers',
1: 'High Value',
2: 'At-Risk',
3: 'Loyal Mid-Tier'
}
df['segment'] = df['cluster'].map(segment_names)
summary = df.groupby('segment').agg(
count = ('customer_id', 'count'),
avg_clv = ('clv', 'mean'),
avg_income = ('annual_income', 'mean'),
avg_spend = ('spending_score', 'mean'),
avg_tenure = ('tenure_months', 'mean')
).round(2)
print("\nSegment Summary:")
print(summary)
# ── 7. Marketing Recommendations ─────────────────────────
print("\n" + "=" * 50)
print("ACTIONABLE MARKETING RECOMMENDATIONS")
print("=" * 50)
print("High Value → Loyalty rewards, premium memberships, early access")
print("Loyal Mid-Tier → Upsell with bundle deals, referral programs")
print("Budget Shoppers → Discount coupons, flash sales, free shipping offers")
print("At-Risk → Re-engagement emails, win-back campaigns, surveys")
# ── 8. Visualizations ─────────────────────────────────────
colors = ['#7F77DD', '#1D9E75', '#D85A30', '#BA7517']
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
fig.suptitle('Customer Segmentation Analysis', fontsize=16, fontweight='bold')
# Elbow Curve
axes[0, 0].plot(list(K_range), inertias, 'o-', color='#7F77DD', linewidth=2)
axes[0, 0].set_title('Elbow Method — Optimal k')
axes[0, 0].set_xlabel('Number of Clusters (k)')
axes[0, 0].set_ylabel('Inertia')
# Silhouette Scores
axes[0, 1].bar(list(K_range), silhouettes, color='#9FE1CB', edgecolor='white')
axes[0, 1].set_title('Silhouette Score by k')
axes[0, 1].set_xlabel('k')
axes[0, 1].set_ylabel('Silhouette Score')
# PCA Scatter Plot
pca = PCA(n_components=2, random_state=42)
X_pca = pca.fit_transform(X_scaled)
for i, name in segment_names.items():
mask = df['cluster'] == i
axes[1, 0].scatter(X_pca[mask, 0], X_pca[mask, 1],
c=colors[i], label=name, alpha=0.4, s=5)
axes[1, 0].set_title('Customer Clusters (PCA 2D)')
axes[1, 0].set_xlabel('Principal Component 1')
axes[1, 0].set_ylabel('Principal Component 2')
axes[1, 0].legend(markerscale=4, fontsize=9)
# CLV by Segment
clv_by_seg = df.groupby('segment')['clv'].mean().sort_values(ascending=False)
axes[1, 1].bar(range(len(clv_by_seg)), clv_by_seg.values,
color=colors[:len(clv_by_seg)], edgecolor='white')
axes[1, 1].set_xticks(range(len(clv_by_seg)))
axes[1, 1].set_xticklabels(clv_by_seg.index, rotation=15, ha='right', fontsize=9)
axes[1, 1].set_title('Avg Customer Lifetime Value by Segment (₹)')
axes[1, 1].set_ylabel('CLV (₹)')
plt.tight_layout()
plt.savefig('customer_segmentation.png', dpi=150, bbox_inches='tight')
plt.show()
print("\n✅ Plot saved as customer_segmentation.png")
# ── 9. Export Results ─────────────────────────────────────
df.to_csv('customer_segments_output.csv', index=False)
print("✅ Segmentation results saved to customer_segments_output.csv")