Stephanwu commited on
Commit
7ca76eb
·
verified ·
1 Parent(s): 30a0cf6

Add main app.py with insurance behavior analysis

Browse files
Files changed (1) hide show
  1. app.py +243 -0
app.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """保险APP 用户行为分析 - Gradio Space"""
2
+ import os, json, math, warnings, datetime, random
3
+ from collections import Counter
4
+ from dataclasses import dataclass, field
5
+ from typing import List, Dict, Optional
6
+
7
+ warnings.filterwarnings('ignore')
8
+ import numpy as np
9
+ import pandas as pd
10
+ from sklearn.model_selection import train_test_split
11
+ from sklearn.preprocessing import StandardScaler
12
+ from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
13
+ from sklearn.metrics import (
14
+ roc_auc_score, f1_score, confusion_matrix,
15
+ average_precision_score, precision_recall_curve, classification_report
16
+ )
17
+ import matplotlib
18
+ matplotlib.use('Agg')
19
+ import matplotlib.pyplot as plt
20
+ import seaborn as sns
21
+
22
+ import gradio as gr
23
+
24
+ INSURANCE_EVENT_TYPES = {
25
+ "page_view", "product_view", "product_compare", "premium_calculator",
26
+ "faq_view", "article_read", "quote_request", "quote_result_view",
27
+ "document_upload", "form_submit", "chat_init", "call_init", "video_consult",
28
+ "policy_select", "payment_init", "payment_success", "policy_issued",
29
+ "claim_init", "claim_doc_upload", "claim_review", "claim_approved",
30
+ "claim_rejected", "renewal_reminder", "renewal_click", "renewal_complete",
31
+ "policy_cancel", "app_uninstall", "login", "logout",
32
+ }
33
+
34
+ @dataclass
35
+ class InsuranceAppEvent:
36
+ event_id: str; user_id: str; session_id: str; timestamp: int
37
+ event_type: str; page_id: str
38
+ product_id: Optional[str] = None; amount: Optional[float] = None
39
+ channel: str = "app"; device_type: str = "mobile"
40
+
41
+ @dataclass
42
+ class UserSession:
43
+ session_id: str; user_id: str
44
+ events: List[InsuranceAppEvent] = field(default_factory=list)
45
+
46
+ @dataclass
47
+ class UserBehaviorProfile:
48
+ user_id: str; sessions: List[UserSession] = field(default_factory=list)
49
+
50
+
51
+ class InsuranceFeatureEngineer:
52
+ def extract_user_features(self, profile):
53
+ sessions = profile.sessions
54
+ if not sessions: return None
55
+ all_events = []
56
+ for s in sessions: all_events.extend(s.events)
57
+ all_events.sort(key=lambda e: e.timestamp)
58
+ all_type_counts = Counter(e.event_type for e in all_events)
59
+ total = len(all_events)
60
+ if total == 0: return None
61
+ product_counter = Counter(e.product_id for e in all_events if e.product_id)
62
+ top_product = product_counter.most_common(1)[0][0] if product_counter else None
63
+ first_ts = all_events[0].timestamp; last_ts = all_events[-1].timestamp
64
+ days_active = (last_ts - first_ts) / (24 * 3600 * 1000)
65
+ has_purchased = any(e.event_type == "policy_issued" for e in all_events)
66
+ has_renewed = any(e.event_type == "renewal_complete" for e in all_events)
67
+ has_claimed = any(e.event_type in ("claim_init", "claim_approved") for e in all_events)
68
+ support = all_type_counts.get("chat_init", 0) + all_type_counts.get("call_init", 0)
69
+ return {
70
+ "total_sessions": len(sessions), "total_events": total,
71
+ "days_active": days_active, "avg_events_per_session": total / len(sessions),
72
+ "product_view_ratio": all_type_counts.get("product_view", 0) / total,
73
+ "quote_request_ratio": all_type_counts.get("quote_request", 0) / total,
74
+ "article_read_ratio": all_type_counts.get("article_read", 0) / total,
75
+ "payment_success_ratio": all_type_counts.get("payment_success", 0) / total,
76
+ "policy_issued_ratio": all_type_counts.get("policy_issued", 0) / total,
77
+ "unique_products_viewed": len(product_counter),
78
+ "has_purchased": int(has_purchased), "has_renewed": int(has_renewed),
79
+ "has_claimed": int(has_claimed), "support_dependency": support / total,
80
+ "renewal_click_count": all_type_counts.get("renewal_click", 0),
81
+ "policy_cancel_count": all_type_counts.get("policy_cancel", 0),
82
+ "claim_init_count": all_type_counts.get("claim_init", 0),
83
+ "days_since_last_event": (datetime.datetime.now().timestamp()*1000 - last_ts)/(24*3600*1000),
84
+ "weekend_activity_ratio": sum(1 for e in all_events if datetime.datetime.fromtimestamp(e.timestamp/1000).weekday()>=5)/total,
85
+ "peak_active_hour": Counter(datetime.datetime.fromtimestamp(e.timestamp/1000).hour for e in all_events).most_common(1)[0][0],
86
+ "recent_7day_events": sum(1 for e in all_events if (last_ts-e.timestamp)<7*24*3600*1000),
87
+ "recent_30day_events": sum(1 for e in all_events if (last_ts-e.timestamp)<30*24*3600*1000),
88
+ }
89
+
90
+
91
+ def generate_synthetic_data(n_users=2000, n_events_per_user=50):
92
+ event_types = list(INSURANCE_EVENT_TYPES)
93
+ products = ["health_basic","health_premium","critical_illness","term_life",
94
+ "auto_compulsory","auto_commercial","home","travel_domestic"]
95
+ data = []
96
+ for u in range(n_users):
97
+ user_id = f"user_{u:04d}"; churn_risk = random.random()
98
+ sessions = []; base_ts = int(datetime.datetime(2024,1,1).timestamp()*1000)
99
+ for s in range(random.randint(1,5)):
100
+ session_id = f"sess_{u}_{s}"
101
+ n_events = random.randint(5, n_events_per_user // max(1, random.randint(1,5)))
102
+ events = []
103
+ for e in range(n_events):
104
+ if churn_risk > 0.7:
105
+ event_type = random.choices(["page_view","product_view","article_read","app_uninstall"],weights=[0.4,0.3,0.2,0.1])[0]
106
+ else:
107
+ stages = n_events
108
+ if e < stages*0.3: event_type = random.choice(["page_view","product_view","article_read"])
109
+ elif e < stages*0.6: event_type = random.choice(["product_view","quote_request","premium_calculator","faq_view"])
110
+ elif e < stages*0.8: event_type = random.choice(["quote_result_view","form_submit","document_upload","payment_init"])
111
+ else: event_type = random.choice(["payment_success","policy_issued","renewal_click","renewal_complete"])
112
+ timestamp = base_ts + e * random.randint(5000,30000)
113
+ events.append(InsuranceAppEvent(f"evt_{u}_{s}_{e}", user_id, session_id, timestamp, event_type, f"page_{event_type}",
114
+ random.choice(products) if event_type in ["product_view","quote_request"] else None,
115
+ random.uniform(1000,100000) if event_type in ["quote_request","payment_success"] else None))
116
+ sessions.append(UserSession(session_id, user_id, events))
117
+ base_ts += 24 * 3600 * 1000
118
+ data.append((UserBehaviorProfile(user_id, sessions), int(churn_risk > 0.7)))
119
+ return data
120
+
121
+
122
+ def train_model(n_users, n_events, test_size, random_state):
123
+ data = generate_synthetic_data(n_users=n_users, n_events_per_user=n_events)
124
+ engineer = InsuranceFeatureEngineer()
125
+ features_list, labels = [], []
126
+ for profile, label in data:
127
+ f = engineer.extract_user_features(profile)
128
+ if f: features_list.append(f); labels.append(label)
129
+ df = pd.DataFrame(features_list)
130
+ df_full = df.copy()
131
+ for c in df.columns:
132
+ if df[c].dtype == 'object':
133
+ df[c] = pd.to_numeric(df[c], errors='coerce').fillna(0)
134
+ df = df.fillna(0).replace([np.inf, -np.inf], 0)
135
+ X = df.values; y = np.array(labels)
136
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=random_state, stratify=y)
137
+ scaler = StandardScaler()
138
+ X_train_s = scaler.fit_transform(X_train); X_test_s = scaler.transform(X_test)
139
+
140
+ gbdt = GradientBoostingClassifier(n_estimators=200, max_depth=5, learning_rate=0.1, subsample=0.8, random_state=random_state)
141
+ gbdt.fit(X_train_s, y_train)
142
+ y_pred_gbdt = gbdt.predict(X_test_s); y_prob_gbdt = gbdt.predict_proba(X_test_s)[:,1]
143
+
144
+ rf = RandomForestClassifier(n_estimators=100, max_depth=10, class_weight='balanced', random_state=random_state, n_jobs=-1)
145
+ rf.fit(X_train_s, y_train)
146
+ y_prob_rf = rf.predict_proba(X_test_s)[:,1]; y_pred_rf = rf.predict(X_test_s)
147
+
148
+ auc_gbdt = float(roc_auc_score(y_test, y_prob_gbdt))
149
+ f1_gbdt = float(f1_score(y_test, y_pred_gbdt))
150
+ ap_gbdt = float(average_precision_score(y_test, y_prob_gbdt))
151
+ auc_rf = float(roc_auc_score(y_test, y_prob_rf))
152
+ ap_rf = float(average_precision_score(y_test, y_prob_rf))
153
+
154
+ fi = pd.DataFrame({'feature': list(df.columns), 'importance': rf.feature_importances_}).sort_values('importance', ascending=False)
155
+
156
+ os.makedirs("outputs", exist_ok=True)
157
+
158
+ fig, ax = plt.subplots(figsize=(12,8))
159
+ top = fi.head(15)
160
+ ax.barh(top['feature'][::-1], top['importance'][::-1], color='steelblue')
161
+ ax.set_title('Insurance APP - Top 15 Feature Importance')
162
+ ax.set_xlabel('Importance')
163
+ plt.tight_layout()
164
+ fig_path1 = "outputs/feature_importance.png"
165
+ plt.savefig(fig_path1, dpi=150, bbox_inches='tight'); plt.close()
166
+
167
+ fig, ax = plt.subplots(figsize=(8,6))
168
+ pg, rg, _ = precision_recall_curve(y_test, y_prob_gbdt)
169
+ pr, rr, _ = precision_recall_curve(y_test, y_prob_rf)
170
+ ax.plot(rg, pg, label=f'GBDT AP={ap_gbdt:.3f}')
171
+ ax.plot(rr, pr, label=f'RF AP={ap_rf:.3f}')
172
+ ax.set_xlabel('Recall'); ax.set_ylabel('Precision')
173
+ ax.set_title('Precision-Recall Curve'); ax.legend()
174
+ plt.tight_layout()
175
+ fig_path2 = "outputs/pr_curve.png"
176
+ plt.savefig(fig_path2, dpi=150, bbox_inches='tight'); plt.close()
177
+
178
+ fig, axs = plt.subplots(1,2,figsize=(12,5))
179
+ sns.heatmap(confusion_matrix(y_test, y_pred_gbdt), annot=True, fmt='d', cmap='Blues', ax=axs[0])
180
+ axs[0].set_title(f'GBDT (AUC={auc_gbdt:.3f})')
181
+ sns.heatmap(confusion_matrix(y_test, y_pred_rf), annot=True, fmt='d', cmap='Greens', ax=axs[1])
182
+ axs[1].set_title(f'RF (AUC={auc_rf:.3f})')
183
+ plt.tight_layout()
184
+ fig_path3 = "outputs/confusion_matrix.png"
185
+ plt.savefig(fig_path3, dpi=150, bbox_inches='tight'); plt.close()
186
+
187
+ fi_str = fi.head(15).to_string(index=False)
188
+ report = classification_report(y_test, y_pred_gbdt, digits=4)
189
+
190
+ result_text = f"""=== 模型训练结果 ===
191
+ 样本数: {n_users} | 特征��: {len(df.columns)}
192
+ 训练集: {len(y_train)} | 测试集: {len(y_test)}
193
+
194
+ --- GBDT ---
195
+ AUC: {auc_gbdt:.4f}
196
+ F1: {f1_gbdt:.4f}
197
+ AP: {ap_gbdt:.4f}
198
+
199
+ --- Random Forest ---
200
+ AUC: {auc_rf:.4f}
201
+ AP: {ap_rf:.4f}
202
+
203
+ --- Top 15 特征重要性 ---
204
+ {fi_str}
205
+
206
+ --- 分类报告 (GBDT) ---
207
+ {report}"""
208
+
209
+ return result_text, fig_path1, fig_path2, fig_path3, df_full
210
+
211
+
212
+ with gr.Blocks(title="保险APP 用户行为分析模型") as demo:
213
+ gr.Markdown("""# 🏥 保险APP 用户行为分析模型训练平台
214
+ 基于合成数据演示保险APP用户流失预测模型的完整训练流程。
215
+ **核心功能:** 生成合成数据 → 自动特征工程 → 训练 GBDT + RF → 可视化结果
216
+
217
+ **参考论文:** Deep Interest Network (KDD 2018) | Transformer Churn Prediction (arXiv 2309.14390) | TabBERT (arXiv 2011.01843)""")
218
+
219
+ with gr.Row():
220
+ with gr.Column(scale=1):
221
+ n_users_slider = gr.Slider(500, 5000, value=2000, step=100, label="用户数量")
222
+ n_events_slider = gr.Slider(10, 100, value=50, step=5, label="每用户最大事件数")
223
+ test_size_slider = gr.Slider(0.1, 0.4, value=0.2, step=0.05, label="测试集比例")
224
+ random_seed = gr.Number(value=42, label="随机种子", precision=0)
225
+ train_btn = gr.Button("🚀 开始训练", variant="primary")
226
+ with gr.Column(scale=2):
227
+ result_text = gr.Textbox(label="训练结果", lines=20)
228
+
229
+ with gr.Row():
230
+ img1 = gr.Image(label="特征重要性")
231
+ img2 = gr.Image(label="PR曲线")
232
+ with gr.Row():
233
+ img3 = gr.Image(label="混淆矩阵")
234
+ data_table = gr.Dataframe(label="数据样本 (前10行)")
235
+
236
+ train_btn.click(fn=train_model, inputs=[n_users_slider, n_events_slider, test_size_slider, random_seed],
237
+ outputs=[result_text, img1, img2, img3, data_table])
238
+
239
+ gr.Markdown("""---
240
+ **事件类型:** 浏览(page_view, product_view) | 交互(quote_request, chat_init) | 转化(payment_success, policy_issued) | 理赔(claim_init) | 续保(renewal_click, policy_cancel)""")
241
+
242
+ if __name__ == "__main__":
243
+ demo.launch()