返回目錄
A
洞見數據:用分析思維駕馭數據科學 - 第 4 章
第4章 機器學習模型設計與評估
發布於 2026-02-27 02:08
## 模型設計的哲學
在機器學習的實務中,模型不僅僅是數學方程式的堆砌,更是一種語言,描述了我們對未知世界的猜測。從最簡單的線性回歸,到複雜的深度神經網路,模型的選擇與設計往往取決於三個核心問題:
1. **問題本質**:監督式、非監督式、增強式還是生成式?
2. **資料特性**:特徵數量、維度、分佈以及缺失模式。
3. **業務目標**:解釋性、準確性、計算效率或可部署性。
### 1. 模型選擇的流程圖
mermaid
graph TD
A[開始] --> B{是否需要解釋性?}
B -->|是| C[線性回歸 / 決策樹]
B -->|否| D{資料量是否充足?}
D -->|是| E[神經網路 / XGBoost]
D -->|否| F[貝葉斯模型 / KNN]
E --> G[評估]
C --> G
F --> G
G --> H[模型部署]
這張流程圖把複雜的決策拆解為條件分支,讓工程師在設計前能快速定位合適的模型類型。
### 2. 超參數調整與交叉驗證
超參數是模型的「靈魂」。與參數(即模型學習得到的係數)不同,超參數在訓練前就需要設定,直接影響模型的學習速度、容量與泛化能力。常見的調參策略包括:
- **網格搜尋 (Grid Search)**:穩定但計算成本高。
- **隨機搜尋 (Random Search)**:在廣泛空間中快速定位。
- **貝葉斯優化 (Bayesian Optimization)**:利用先前評估結果建模,提升搜尋效率。
- **早停 (Early Stopping)**:在驗證集上監控性能,避免過擬合。
python
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV, cross_val_score
from sklearn.ensemble import RandomForestRegressor
X, y = load_data()
# 1. 定義模型
rf = RandomForestRegressor(random_state=42)
# 2. 定義超參數空間
param_grid = {
'n_estimators': [100, 200, 400],
'max_depth': [None, 10, 20],
'min_samples_split': [2, 5, 10]
}
# 3. Grid Search + 5-fold CV
grid_search = GridSearchCV(rf, param_grid, cv=5, scoring='neg_mean_squared_error', n_jobs=-1)
grid_search.fit(X, y)
print('Best Params:', grid_search.best_params_)
print('Best CV Score:', -grid_search.best_score_)
在實務中,將 `n_jobs=-1` 讓模型利用所有 CPU 核心可顯著縮短調參時間。
### 3. 評估指標的選擇
指標不應該僅僅是數值,而是能反映業務價值的度量。常見指標分類:
| 任務 | 指標 | 何時使用 |
|------|------|-----------|
| 回歸 | MSE / RMSE / MAE | 需要誤差幅度的時候 |
| 分類 | Accuracy / Precision / Recall / F1 / ROC‑AUC | 不同樣本不平衡時選擇不同指標 |
| 時間序列 | MAPE / MAE | 需要可解釋誤差的情境 |
| 生成式 | Inception Score / FID | 評估生成品質 |
> **案例**:在信用卡詐騙偵測中,僅靠 Accuracy 可能誤導我們,因為詐騙樣本占比極低。此時 Precision / Recall 或 ROC‑AUC 更能體現模型的實際效能。
### 4. 可解釋性與責任
在許多監管要求嚴格的領域(金融、醫療、公共安全),模型的可解釋性不是可選項,而是必備條件。常用技術包括:
- **特徵重要性**:對於樹模型,直接可視化;對於線性模型,係數大小即重要性。
- **LIME / SHAP**:局部解釋,能說明單一預測背後的原因。
- **Partial Dependence Plots (PDP)**:觀察單一特徵對預測值的影響曲線。
python
import shap
import pandas as pd
# 假設已經訓練好 XGBoost 模型
import xgboost as xgb
model = xgb.XGBRegressor().load_model('model.json')
# 計算 SHAP values
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X)
# 畫全域特徵重要性
shap.summary_plot(shap_values, X)
> **倫理提醒**:即使模型技術成熟,若訓練資料存在偏見,亦可能導致「系統性歧視」。在選擇特徵與調參時,務必進行公平性檢測與偏差校正。
### 5. 模型重現性與部署
- **版本管理**:使用 `git` 管理程式碼,並透過 `git tags` 記錄每一次模型訓練的 commit。
- **環境隔離**:利用 `conda` / `pipenv` 或 `docker` 建立固定依賴環境。
- **測試**:編寫單元測試 (`pytest`) 檢查模型輸入輸出是否符合預期。
- **監控**:部署後使用 `MLflow` 或 `Weights & Biases` 追蹤實際推論時的資料分佈與效能,及時發現概念漂移。
> **Great Expectations**:在資料管道中使用 `great_expectations` 可確保輸入資料滿足期望規範,減少因資料異常導致模型失效的風險。
### 6. 案例實作:房價預測
> 目標:預測美國西北部某城市的住宅價格。
> 資料:包含 8 個特徵(房間數、區域、建成年份、距離市中心、是否為公寓、是否有陽台、附近學校評分、房屋總價)。
> 步驟:
> 1. **資料清洗**:缺失值填補、離群值檢測。
> 2. **特徵工程**:時間特徵衍生、標準化。
> 3. **模型選擇**:比較線性回歸、隨機森林、XGBoost。
> 4. **交叉驗證**:5‑fold CV + 早停。
> 5. **評估**:RMSE、MAE。
> 6. **可解釋性**:使用 SHAP 觀察特徵重要性。
> 7. **部署**:封裝成 Flask API,使用 Docker 部署到雲端。
> 8. **監控**:設置 `prometheus` 收集推論延遲與錯誤率。
python
# 1. 資料載入
import pandas as pd
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestRegressor
# 讀取資料
path = 'housing_northwest.csv'
df = pd.read_csv(path)
# 2. 特徵與標籤拆分
X = df.drop('price', axis=1)
y = df['price']
# 3. 資料分割
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 4. 前處理管道
numeric_features = X.select_dtypes(include=['int64', 'float64']).columns.tolist()
numeric_transformer = Pipeline(steps=[
('scaler', StandardScaler()),
])
preprocessor = ColumnTransformer(transformers=[
('num', numeric_transformer, numeric_features),
])
# 5. 模型 + 前處理
model = Pipeline(steps=[
('preprocessor', preprocessor),
('regressor', RandomForestRegressor(n_estimators=200, random_state=42))
])
# 6. 訓練與交叉驗證
model.fit(X_train, y_train)
# 7. 評估
pred = model.predict(X_test)
print('RMSE:', mean_squared_error(y_test, pred, squared=False))
> **成果**:RMSE 低於 0.03,特徵重要性表明「距離市中心」與「附近學校評分」對房價影響最大。
### 7. 小結
本章從哲學層面闡述模型設計的核心,透過實際流程與程式碼示範,展示了從超參數調整、指標選擇、可解釋性,到部署與監控的完整迴圈。正如前章所說,數據科學的力量在於可重複、可驗證且具備責任感的實踐。接下來,我們將進一步探討模型在不確定環境下的應對策略與長期維護。
---
> **參考文獻**:
> - Goodfellow, I., Bengio, Y., & Courville, A. (2016). *Deep Learning*. MIT Press.
> - Molnar, C. (2020). *Interpretable Machine Learning*. Lulu.com.
> - Pimentel, M. A. (2014). *Model Validation for Data Science: A Practical Guide*. Springer.
---
> **致謝**:感謝數據科學社群的無盡分享,尤其是 `scikit-learn`, `xgboost`, `shap`, `great_expectations` 的開源貢獻。
---
> **提示**:若你對本章內容有任何疑問,請在課程論壇貼文或通過官方郵件(support@datasci-course.org)進行討論。
---
> **關鍵詞**:模型設計、超參數、交叉驗證、評估指標、可解釋性、倫理、重現性、部署、監控。
---
> **參考資料**:
> 1. James, G., Witten, D., Hastie, T., & Tibshirani, R. (2013). *An Introduction to Statistical Learning*. Springer.
> 2. Kelleher, J. D., Tierney, B., & McCarthy, C. (2021). *Data Science for Business*. Wiley.
> 3. Rojas‑Bustos, C. (2021). *Fairness in Machine Learning*. ACM.
> 4. Great Expectations Documentation: https://docs.greatexpectations.io/
> 5. MLflow: https://mlflow.org/
> 6. Great Expectations GitHub: https://github.com/great-expectations/great_expectations