BettyChen commited on
Commit
d14e7e7
·
verified ·
1 Parent(s): 4a87e84

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +287 -132
app.py CHANGED
@@ -5,7 +5,7 @@ st.set_page_config(page_title="國泰人壽 - 用戶行為預測工具", layout=
5
 
6
  import pandas as pd
7
  import numpy as np
8
- from datetime import datetime
9
  import plotly.express as px
10
 
11
  # 嘗試載入 TensorFlow 和相關套件
@@ -135,15 +135,213 @@ def safe_scale(scaler, value, default=0.0):
135
  except:
136
  return default
137
 
138
- def recommend_strategy(action_group):
139
- if "試算" in action_group:
140
- return "推播優惠券"
141
- elif "商品資訊頁" in action_group or "訂製保險組合" in action_group:
142
- return "建議展示內容"
143
- elif "預約" in action_group:
144
- return "提供預約"
145
- else:
146
- return "等待更多資料"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
  def safe_label_transform(encoder, value, default=0): # 改為 default=0
149
  """
@@ -285,13 +483,15 @@ def validate_and_fix_sequence(seq, seq_name):
285
 
286
  return seq
287
 
 
288
  def predict_from_uploaded_csv(df):
289
  if model is None or encoders is None or scalers is None:
290
  st.error("模型未正確載入,無法進行預測")
291
  return pd.DataFrame()
292
 
293
  # 檢查必要欄位
294
- required_columns = ['user_pseudo_id', 'event_time'] + cat_features + num_features
 
295
  missing_columns = [col for col in required_columns if col not in df.columns]
296
  if missing_columns:
297
  st.error(f"缺少必要欄位: {missing_columns}")
@@ -299,150 +499,105 @@ def predict_from_uploaded_csv(df):
299
 
300
  # 資料預處理
301
  df = df.copy()
 
302
  df = df.sort_values(by=["user_pseudo_id", "event_time"])
303
 
304
- # 列印編碼器信息用於除錯
305
- print("\n=== 編碼器信息 ===")
306
- for col, encoder in encoders.items():
307
- print(f"{col}: {len(encoder.classes_)} 個類別, 範圍 [0, {len(encoder.classes_)-1}]")
308
- print(f" 前5個類別: {list(encoder.classes_[:5])}")
309
-
310
  results = []
311
 
312
  for user_id, group in df.groupby("user_pseudo_id"):
313
  try:
314
- print(f"\n處理用戶: {user_id}")
315
  last_steps = group.tail(SEQ_LEN)
316
  pad_len = SEQ_LEN - len(last_steps)
317
- print(f" 序列長度: {len(last_steps)}, 需要填充: {pad_len}")
318
-
319
- # 處理類別特徵 (4個輸入)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320
  cat_inputs = []
321
- for i, col in enumerate(cat_features):
322
- print(f" 處理類別特徵: {col}")
323
-
324
- # 檢查原始數據
325
- raw_values = last_steps[col].tolist()
326
- print(f" 原始值: {raw_values}")
327
-
328
- # 進行編碼
329
- seq = []
330
- for v in raw_values:
331
- encoded_value = safe_label_transform(encoders[col], v, default=0)
332
- seq.append(encoded_value)
333
-
334
- print(f" 編碼後: {seq}")
335
-
336
- # 填充序列
337
- padded_seq = [0] * pad_len + seq
338
- print(f" 填充後: {padded_seq}")
339
-
340
- # 驗證並修復序列
341
- final_seq = validate_and_fix_sequence(padded_seq, f"{col}_sequence")
342
-
343
- # 確保數據類型和形狀
344
- final_seq = np.array(final_seq, dtype=np.int32).reshape(1, SEQ_LEN)
345
-
346
- # 最終檢查
347
- if final_seq.min() < 0:
348
- st.error(f"最終序列仍包含負值: {final_seq}")
349
- return pd.DataFrame()
350
-
351
- if final_seq.max() >= len(encoders[col].classes_):
352
- st.error(f"序列值超出範圍: max={final_seq.max()}, 允許範圍=[0, {len(encoders[col].classes_)-1}]")
353
- return pd.DataFrame()
354
-
355
- cat_inputs.append(final_seq)
356
- print(f" 最終形狀: {final_seq.shape}, 範圍: [{final_seq.min()}, {final_seq.max()}]")
357
-
358
- # 處理數值特徵 (3個輸入)
359
  num_inputs = []
360
  for col in num_features:
361
- print(f" 處理數值特徵: {col}")
362
-
363
- # 檢查原始數據
364
- raw_values = last_steps[col].tolist()
365
- print(f" 原始值: {raw_values}")
366
-
367
- # 進行標準化
368
- seq = []
369
- for v in raw_values:
370
- scaled_value = safe_scale(scalers[col], v, default=0.0)
371
- seq.append(scaled_value)
372
-
373
- print(f" 標準化後: {seq}")
374
-
375
- # 填充序列
376
- padded_seq = [0.0] * pad_len + seq
377
-
378
- # 驗證並修復序列
379
- final_seq = validate_and_fix_sequence(padded_seq, f"{col}_sequence")
380
-
381
- # 確保數據類型和形狀
382
- final_seq = np.array(final_seq, dtype=np.float32).reshape(1, SEQ_LEN)
383
- num_inputs.append(final_seq)
384
- print(f" 最終形狀: {final_seq.shape}")
385
-
386
- # 組合所有輸入
387
  all_inputs = cat_inputs + num_inputs
388
 
389
- print(f" 總輸入數量: {len(all_inputs)} (期望: 7)")
 
 
390
 
391
- # 最終驗證
392
- for i, inp in enumerate(all_inputs):
393
- input_name = cat_features[i] if i < len(cat_features) else num_features[i - len(cat_features)]
394
- print(f" 輸入 {i+1} ({input_name}): 形狀={inp.shape}, 類型={inp.dtype}")
395
-
396
- if i < len(cat_features): # 類別特徵
397
- if inp.min() < 0:
398
- st.error(f"類別輸入 {input_name} 包含負值: {inp.min()}")
399
- return pd.DataFrame()
400
-
401
- max_allowed = len(encoders[cat_features[i]].classes_) - 1
402
- if inp.max() > max_allowed:
403
- st.error(f"類別輸入 {input_name} 值超出範圍: {inp.max()} > {max_allowed}")
404
- return pd.DataFrame()
405
-
406
- # 進行預測
407
- print(" 開始預測...")
408
- predictions = model.predict(all_inputs, verbose=0)
409
- y_pred_action_group, y_pred_online, y_pred_o2o = predictions
410
- print(" 預測完成")
411
-
412
- # 處理預測結果
413
- top5_indices = y_pred_action_group[0].argsort()[-5:][::-1]
414
- top5_confidences = y_pred_action_group[0][top5_indices]
415
-
416
- inv_action = {i: v for i, v in enumerate(encoders['action_group'].classes_)}
417
- top5_actions = [inv_action.get(idx, "未知類別") for idx in top5_indices]
418
-
419
- strategy = recommend_strategy(top5_actions[0])
420
-
421
  result = {
422
- "user_pseudo_id": user_id,
423
- "Top1_next_action_group": top5_actions[0],
424
- "Top1_confidence": round(float(top5_confidences[0]), 4),
425
- "Online_conversion_prob": round(float(y_pred_online[0][0]), 4),
426
- "O2O_reservation_prob": round(float(y_pred_o2o[0][0]), 4),
427
- "Marketing_Strategy": strategy
 
 
 
428
  }
429
 
430
- # 添加 Top 5 結果
431
  for i in range(5):
432
  result[f"Top{i+1}_next_action_group"] = top5_actions[i]
433
- result[f"Top{i+1}_confidence"] = round(float(top5_confidences[i]), 4)
434
-
435
- results.append(result)
436
- print(f" 用戶 {user_id} 處理完成")
437
 
 
 
438
  except Exception as e:
439
  st.error(f"處理用戶 {user_id} 時發生錯誤: {e}")
440
- print(f"錯誤詳情: {e}")
441
- import traceback
442
- traceback.print_exc()
443
  continue
444
-
445
- print(f"\n總共處理了 {len(results)} 個用戶")
446
  return pd.DataFrame(results)
447
 
448
  # UI 介面
 
5
 
6
  import pandas as pd
7
  import numpy as np
8
+ from datetime import datetime, timedelta
9
  import plotly.express as px
10
 
11
  # 嘗試載入 TensorFlow 和相關套件
 
135
  except:
136
  return default
137
 
138
+
139
+ # 1. 定義等級映射函式
140
+ def get_level(action_group: str) -> float:
141
+ # 等級 0
142
+ if action_group in {"其他", "保險視圖、保單明細、資產總覽、保險明細"}:
143
+ return 0
144
+ # 等級 1
145
+ if action_group == "找服務(尋求服務與客服)":
146
+ return 1
147
+ # 等級 2
148
+ if action_group.startswith("商品資訊頁") or action_group == "好康優惠":
149
+ return 2
150
+ # 等級 3
151
+ combo3 = {
152
+ "自由配-投資規劃", "自由配", "訂製保險組合", "自由配-套餐"
153
+ }
154
+ if action_group in combo3 or action_group.startswith("試算"):
155
+ return 3
156
+ # 等級 4
157
+ result4 = {
158
+ "自由配-保障規劃試算結果",
159
+ "訂製保險組合-人身規劃試算結果",
160
+ "我的保險試算結果",
161
+ "訂製保險組合-投資規劃試算結果",
162
+ "自由配-配置我的基金試算結果"
163
+ }
164
+ if action_group in result4:
165
+ return 4
166
+ # 等級 5
167
+ if action_group in {
168
+ "保存與分享試算結果",
169
+ "保存與分享自由配、訂製組合結果",
170
+ "Line分享轉傳"
171
+ }:
172
+ return 5
173
+ # 等級 6
174
+ if action_group in {
175
+ "挑選預約顧問",
176
+ "預約顧問與商品諮詢",
177
+ "立即投保"
178
+ }:
179
+ return 6
180
+ # 等級 7.x
181
+ if action_group in {"方案確認", "填寫預約資料"}:
182
+ return 7.1
183
+ if action_group in {"資料填寫與確認", "投保資格確認", "手機驗證碼"}:
184
+ return 7.2
185
+ if action_group == "線上繳費":
186
+ return 7.3
187
+ # 等級 8
188
+ if action_group in {"完成網路投保", "完成O2O"}:
189
+ return 8
190
+ # 未知
191
+ return -1
192
+
193
+ # 2. 推薦策略函式(使用 next_action_group 參數)
194
+ def recommend_strategy(
195
+ next_action_group: str,
196
+ history: list[str],
197
+ last_event_time: datetime
198
+ ) -> str | None:
199
+ now = datetime.now()
200
+
201
+ # 等級 0
202
+ if next_action_group in {"其他", "保險視圖、保單明細、資產總覽、保險明細"}:
203
+ return None
204
+
205
+ # 等級 1:找服務
206
+ if next_action_group == "找服務(尋求服務與客服)":
207
+ s = "箭頭提醒「找服務」介面在畫面上方選單"
208
+ if history[-10:].count("找服務(尋求服務與客服)") > 3:
209
+ s += ";讓右下角的阿發的「Hi 需要幫忙嗎」秀出來"
210
+ return s
211
+
212
+ # 等級 2:商品資訊頁
213
+ if next_action_group.startswith("商品資訊頁"):
214
+ cnt = sum(1 for ag in history[-10:] if ag.startswith("商品資訊頁"))
215
+ if cnt >= 3:
216
+ return "顯示入口推動試算"
217
+ return None
218
+
219
+ # 等級 2:好康優惠
220
+ if next_action_group == "好康優惠":
221
+ if now - last_event_time > timedelta(minutes=3):
222
+ return "彈窗顯示好康優惠相關資訊"
223
+ return None
224
+
225
+ # 等級 3:挑選組合
226
+ combo3 = {"自由配-投資規劃", "自由配", "訂製保險組合", "自由配-套餐"}
227
+ if next_action_group in combo3:
228
+ prompt = (
229
+ "不知道如何開始嗎?簡單三個問題,讓系統提供最適合你的商品!"
230
+ if next_action_group == "訂製保險組合"
231
+ else "一鍵搭配個人化的商品組合,只要 2 分鐘!"
232
+ )
233
+ return f"彈窗:「{prompt}」"
234
+
235
+ # 等級 3:試算
236
+ if next_action_group.startswith("試算"):
237
+ return "彈窗:「一鍵帶你完成試算,只要 2 步驟,取得商品費用估算」"
238
+
239
+ # 等級 4:試算結果
240
+ result4 = {
241
+ "自由配-保障規劃試算結果",
242
+ "訂製保險組合-人身規劃試算結果",
243
+ "我的保險試算結果",
244
+ "訂製保險組合-投資規劃試算結果",
245
+ "自由配-配置我的基金試算結果"
246
+ }
247
+ if next_action_group in result4:
248
+ return "提供進度提醒:就快完成了!試算結果即將產生"
249
+
250
+ # 等級 5:保存/分享結果
251
+ if next_action_group in {
252
+ "保存與分享試算結果",
253
+ "保存與分享自由配、訂製組合結果"
254
+ }:
255
+ return "諮詢按鈕提示:「對試算結果有疑問嗎?預約免費專人解讀!」"
256
+ if next_action_group == "Line分享轉傳":
257
+ return "彈窗鼓勵推薦、推播推薦獎勵機制或分享回饋活動"
258
+
259
+ # 等級 6:挑顧問 / 諮詢需求
260
+ if next_action_group in {"挑選預約顧問", "預約顧問與商品諮詢"}:
261
+ return "彈窗推薦顧問:「這位專家最擅長XX險,3 分鐘內確認預約」"
262
+ if next_action_group == "立即投保":
263
+ return "立即投保按鈕或橫幅CTA:「立即投保享優惠!」"
264
+
265
+ # 等級 7.1:方案確認 / 填寫預約資料
266
+ if next_action_group in {"方案確認", "填寫預約資料"}:
267
+ if now - last_event_time <= timedelta(minutes=5):
268
+ return (
269
+ "進度提醒:「再三步即可完成投保」"
270
+ if next_action_group == "方案確認"
271
+ else "進度提醒:「再兩步即可完成預約」"
272
+ )
273
+
274
+ # 等級 7.2:資料填寫與確認 / 投保資格確認 / 手機驗證碼
275
+ if next_action_group in {"資料填寫與確認", "投保資格確認", "手機驗證碼"}:
276
+ if now - last_event_time > timedelta(minutes=30):
277
+ return "機器人引導:「上次還沒填完?點此一鍵回到流程」"
278
+ if now - last_event_time <= timedelta(minutes=5):
279
+ return (
280
+ "進度提醒:「還差最後一步就OK,即將完成預約」"
281
+ if next_action_group == "手機驗證碼"
282
+ else "進度提醒:「還差最後兩步就OK,即將完成投保」"
283
+ )
284
+
285
+ # 等級 7.3:線上繳費
286
+ if next_action_group == "線上繳費":
287
+ if now - last_event_time > timedelta(minutes=30):
288
+ return "機器人引導:「上次還沒填完?點此一鍵回到流程」"
289
+ if now - last_event_time <= timedelta(minutes=5):
290
+ return "進度提醒:「還差最後一步就OK,即將完成投保」"
291
+
292
+ # 等級 8:完成網投 / 完成O2O
293
+ if next_action_group == "完成網路投保":
294
+ if now - last_event_time > timedelta(minutes=30):
295
+ return (
296
+ "寄發EDM提醒即將完成投保,並附上連結「還差最後一步就OK,"
297
+ "點我回到流程」"
298
+ )
299
+ return "感謝頁推薦:「感謝您!邀請好友完成網投送雙方 NT$300元」"
300
+ if next_action_group == "完成O2O":
301
+ if now - last_event_time > timedelta(minutes=30):
302
+ return (
303
+ "寄發EDM提醒即將完成預約,並附上連結「還差最後一步就OK,"
304
+ "點我回到流程」"
305
+ )
306
+
307
+ return None
308
+
309
+ # 轉成 datetime
310
+ df['last_event_time'] = pd.to_datetime(df['last_event_time'])
311
+
312
+ # 4. 先根據 Top1~Top5 選出 next_action_group
313
+ def pick_next_action_group(row) -> str:
314
+ candidates = []
315
+ for i in range(1, 6):
316
+ ag = row[f'Top{i}_next_action_group']
317
+ conf = row[f'Top{i}_confidence']
318
+ lvl = get_level(ag)
319
+ candidates.append((ag, conf, lvl))
320
+ # 先比等級,再比機率
321
+ best = max(candidates, key=lambda x: (x[2], x[1]))
322
+ return best[0]
323
+
324
+ df['next_action_group'] = df.apply(pick_next_action_group, axis=1)
325
+
326
+ # 5. 定義歷史紀錄欄位(最新→最舊)
327
+ history_cols = [
328
+ 'next_action_group',
329
+ '-2_action_group','-3_action_group','-4_action_group',
330
+ '-5_action_group','-6_action_group','-7_action_group',
331
+ '-8_action_group','-9_action_group'
332
+ ]
333
+
334
+ # 6. 最後套用 recommend_strategy
335
+ df['strategy'] = df.apply(
336
+ lambda row: recommend_strategy(
337
+ row['next_action_group'],
338
+ [row[c] for c in history_cols],
339
+ row['last_event_time']
340
+ ),
341
+ axis=1
342
+ )
343
+
344
+
345
 
346
  def safe_label_transform(encoder, value, default=0): # 改為 default=0
347
  """
 
483
 
484
  return seq
485
 
486
+
487
  def predict_from_uploaded_csv(df):
488
  if model is None or encoders is None or scalers is None:
489
  st.error("模型未正確載入,無法進行預測")
490
  return pd.DataFrame()
491
 
492
  # 檢查必要欄位
493
+ required_columns = ['user_pseudo_id', 'event_time', 'platform', 'action', 'action_group'] \
494
+ + cat_features + num_features
495
  missing_columns = [col for col in required_columns if col not in df.columns]
496
  if missing_columns:
497
  st.error(f"缺少必要欄位: {missing_columns}")
 
499
 
500
  # 資料預處理
501
  df = df.copy()
502
+ df['event_time'] = pd.to_datetime(df['event_time'])
503
  df = df.sort_values(by=["user_pseudo_id", "event_time"])
504
 
 
 
 
 
 
 
505
  results = []
506
 
507
  for user_id, group in df.groupby("user_pseudo_id"):
508
  try:
509
+ # 取最後 SEQ_LEN 步
510
  last_steps = group.tail(SEQ_LEN)
511
  pad_len = SEQ_LEN - len(last_steps)
512
+
513
+ # --- 擷取 raw features ---
514
+ last = last_steps.iloc[-1]
515
+ raw_last_event_time = last['event_time']
516
+ raw_last_platform = last['platform']
517
+ raw_last_action = last['action']
518
+ raw_last_action_group = last['action_group']
519
+
520
+ # 取前 2~9 步的 raw action & action_group
521
+ prev_records = {}
522
+ for i in range(2, 10):
523
+ if len(last_steps) >= i:
524
+ rec = last_steps.iloc[-i]
525
+ prev_records[f"-{i}_action"] = rec['action']
526
+ prev_records[f"-{i}_action_group"] = rec['action_group']
527
+ else:
528
+ prev_records[f"-{i}_action"] = None
529
+ prev_records[f"-{i}_action_group"] = None
530
+
531
+ # --- 類別特徵編碼 & 填充 ---
532
  cat_inputs = []
533
+ for col in cat_features:
534
+ raw_vals = last_steps[col].tolist()
535
+ encoded = [ safe_label_transform(encoders[col], v, default=0)
536
+ for v in raw_vals ]
537
+ padded = [0]*pad_len + encoded
538
+ seq = validate_and_fix_sequence(padded, f"{col}_sequence")
539
+ cat_inputs.append(np.array(seq, dtype=np.int32).reshape(1, SEQ_LEN))
540
+
541
+ # --- 數值特徵標準化 & 填充 ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
542
  num_inputs = []
543
  for col in num_features:
544
+ raw_vals = last_steps[col].tolist()
545
+ scaled = [ safe_scale(scalers[col], v, default=0.0)
546
+ for v in raw_vals ]
547
+ padded = [0.0]*pad_len + scaled
548
+ seq = validate_and_fix_sequence(padded, f"{col}_sequence")
549
+ num_inputs.append(np.array(seq, dtype=np.float32).reshape(1, SEQ_LEN))
550
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
551
  all_inputs = cat_inputs + num_inputs
552
 
553
+ # --- 預測 ---
554
+ y_pred_action_group, y_pred_online, y_pred_o2o = \
555
+ model.predict(all_inputs, verbose=0)
556
 
557
+ # 取得 Top5
558
+ top5_idx = y_pred_action_group[0].argsort()[-5:][::-1]
559
+ top5_confs = y_pred_action_group[0][top5_idx]
560
+ inv_ag = {i: v for i, v in enumerate(encoders['action_group'].classes_)}
561
+ top5_actions = [inv_ag.get(idx, "未知") for idx in top5_idx]
562
+
563
+ # 選擇 next_action_group(最高等級→機率)
564
+ next_ag = pick_next_action_group({
565
+ f"Top{i+1}_next_action_group": top5_actions[i],
566
+ f"Top{i+1}_confidence": top5_confs[i]
567
+ for i in range(5)
568
+ })
569
+
570
+ # 計算行銷策略
571
+ strategy = recommend_strategy(
572
+ next_ag,
573
+ [ prev_records.get(f"-{i}_action_group") for i in range(1, 10) ],
574
+ raw_last_event_time
575
+ )
576
+
577
+ # --- 組裝結果 ---
 
 
 
 
 
 
 
 
 
578
  result = {
579
+ "user_pseudo_id": user_id,
580
+ "last_event_time": raw_last_event_time,
581
+ "last_platform": raw_last_platform,
582
+ "last_action": raw_last_action,
583
+ "last_action_group": raw_last_action_group,
584
+ **prev_records,
585
+ "Online_conversion_prob": round(float(y_pred_online[0][0]), 4),
586
+ "O2O_reservation_prob": round(float(y_pred_o2o[0][0]), 4),
587
+ "Marketing_Strategy": strategy
588
  }
589
 
590
+ # 添加 Top1~Top5
591
  for i in range(5):
592
  result[f"Top{i+1}_next_action_group"] = top5_actions[i]
593
+ result[f"Top{i+1}_confidence"] = round(float(top5_confs[i]), 4)
 
 
 
594
 
595
+ results.append(result)
596
+
597
  except Exception as e:
598
  st.error(f"處理用戶 {user_id} 時發生錯誤: {e}")
 
 
 
599
  continue
600
+
 
601
  return pd.DataFrame(results)
602
 
603
  # UI 介面