聊天視窗

資料科學實務與方法:從理論到應用 - 第 2 章

第二章:模型評估與驗證—從指標到洞察

發布於 2026-03-04 02:15

# 2. 模型評估與驗證—從指標到洞察 在上一章中,我們已經完成了資料清洗、特徵工程、模型訓練與 Flask API 部署。這一切的基礎,最終還是要透過**評估**來驗證模型的價值。這章將帶你從「什麼叫做好模型」走向「如何用數據證明它好」。 ## 2.1 評估指標的選擇 | 指標 | 何時使用 | 直覺說明 | |------|-----------|-----------| | **Accuracy** | 分類平衡時 | 取得預測正確的比例 | | **Precision / Recall** | 分類不平衡時 | 對正例的誤判與漏判量化 | | **F1‑score** | 想平衡 Precision 與 Recall | 兩者的調和平均 | | **AUC‑ROC** | 判斷分數排序能力 | 越高代表分數排序越好 | | **Confusion Matrix** | 可視化錯誤類型 | 直觀顯示 TP、FP、FN、TN | | **Lift / Gain** | 業務投資回報 | 衡量推薦效果相對於隨機的提升 | > **小提示**:如果你正在開發一個「預測客戶是否會退訂」的模型,常見的做法是以 **Recall** 為主要指標——我們更關心「漏掉多少可能退訂的客戶」而非「錯誤地標記為退訂」。 ## 2.2 交叉驗證(Cross‑Validation) python from sklearn.model_selection import StratifiedKFold from sklearn.metrics import f1_score X, y = df.drop(columns=["label"]), df["label"] cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) f1_scores = [] for train_idx, val_idx in cv.split(X, y): X_train, X_val = X.iloc[train_idx], X.iloc[val_idx] y_train, y_val = y.iloc[train_idx], y.iloc[val_idx] model = RandomForestClassifier(n_estimators=200, random_state=42) model.fit(X_train, y_train) preds = model.predict(X_val) f1_scores.append(f1_score(y_val, preds)) print(f"交叉驗證 F1 分數:{np.mean(f1_scores):.4f} ± {np.std(f1_scores):.4f}") 交叉驗證可以幫助你減少模型對於單一驗證集的過擬合風險,並提供更穩健的性能估計。 ## 2.3 超參數調整 | 方法 | 優點 | 缺點 | |------|------|------| | **Grid Search** | 全面搜尋 | 計算量大 | | **Randomized Search** | 節省時間 | 可能漏掉最佳組合 | | **Bayesian Optimization** | 高效 | 需要額外套件 | python from sklearn.model_selection import RandomizedSearchCV from scipy.stats import randint param_dist = { "n_estimators": randint(100, 400), "max_depth": randint(5, 20), "min_samples_split": randint(2, 10), } rf = RandomForestClassifier(random_state=42) search = RandomizedSearchCV(rf, param_distributions=param_dist, n_iter=50, scoring="f1", cv=5, verbose=1, random_state=42) search.fit(X, y) print("最佳參數:", search.best_params_) print("最佳 F1 分數:", search.best_score_) 透過這樣的調整,我們可以在保證模型泛化的同時,提升預測效果。 ## 2.4 模型可解釋性(Interpretability) 在企業環境中,模型 **可解釋性** 是推動決策的一把鑰匙。下面以 SHAP 為例,展示特徵對預測結果的貢獻。 python import shap explainer = shap.TreeExplainer(search.best_estimator_) shap_values = explainer.shap_values(X) shap.summary_plot(shap_values[1], X) # 針對正類(label=1) > **案例對話**: > - **資料科學家**:這裡顯示 `feature_7` 的 SHAP 值為正,代表它提升了客戶購買的可能性。 > - **行銷經理**:那我們就把產品推廣聚焦在這類客戶,預期會提升 8% 的轉化率。 ## 2.5 業務績效評估 模型訓練完後,我們將 **Lift** 或 **Return on Investment (ROI)** 這類業務指標納入評估。假設推薦系統每月帶來 50,000 萬額的訂單,我們的模型在推薦前後的差異為 5,000 萬,則 Lift 為 10%。 python base_sales = 500 lifted_sales = 550 lift = (lifted_sales - base_sales) / base_sales print(f"推薦 Lift:{lift:.2%}") 如果 Lift 超過了行業平均(如 7%),便能說明模型的商業價值。 ## 2.6 綜合評估報告 | 評估項目 | 目標值 | 實際值 | 判定 | |----------|--------|--------|------| | **F1‑score** | ≥ 0.82 | 0.835 | ✅ | | **AUC** | ≥ 0.89 | 0.907 | ✅ | | **Lift** | ≥ 0.09 | 0.10 | ✅ | | **模型解釋性** | 可視化 | SHAP summary plot | ✅ | > **結語**:模型評估不是一次性的任務,而是**連續迭代**的過程。每一次部署都伴隨著性能監控,確保模型在真實數據流中的穩定表現。 --- > **思考題**:在你所在的產業中,若要評估一個「預測客戶流失」模型,你會選擇哪些評估指標?為什麼?