聊天視窗

資料科學實戰:從數據到洞察 - 第 6 章

6. 高階模型與深度學習

發布於 2026-02-27 05:45

# 6. 高階模型與深度學習 本章聚焦於資料科學中最具實戰價值的高階模型與深度學習技術。從樹模型、梯度提升機(XGBoost)到全連接神經網路、卷積網路(CNN)與循環網路(RNN),我們將依序闡述其原理、實作流程、金融/行銷案例以及模型部署與可解釋性。整個章節以 **Python** 為實作語言,涵蓋 `scikit-learn`、`xgboost`、`tensorflow/keras` 與 `pytorch` 等熱門框架。 --- ## 6.1 樹模型 ### 6.1.1 直覺與基本概念 - **決策樹(Decision Tree)**:將特徵空間遞迴切分,形成「若-則」規則。易於解釋,適合非線性關係。 - **隨機森林(Random Forest)**:多棵決策樹的集成,通過 bagging 與特徵隨機化降低過擬合。 - **梯度提升樹(Gradient Boosting Tree)**:順序訓練,每棵樹修正前一棵的殘差;目前最常見的實作是 XGBoost、LightGBM、CatBoost。 ### 6.1.2 範例:信用風險預測 python import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import roc_auc_score # 1. 資料載入 X = pd.read_csv('credit_features.csv') y = pd.read_csv('credit_labels.csv')['label'] # 2. 分割 X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y) # 3. 模型 rf = RandomForestClassifier(n_estimators=200, max_depth=10, random_state=42, n_jobs=-1) rf.fit(X_train, y_train) # 4. 評估 pred = rf.predict_proba(X_val)[:, 1] print('ROC‑AUC:', roc_auc_score(y_val, pred)) > **實務提醒**:隨機森林在處理高維度特徵(如交易日誌)時表現良好,但若特徵量級差異大,需先進行標準化或使用 `Categorical` 直接編碼。 ### 6.1.3 重要參數 | 參數 | 說明 | 建議範圍 | |------|------|-----------| | n_estimators | 棵樹數量 | 100–1000(取決於資料量) | | max_depth | 最大樹深 | 5–30,過深會過擬合 | | min_samples_split | 分裂最小樣本數 | 2–10 | | min_samples_leaf | 葉節點最小樣本數 | 1–5 | | max_features | 每次分裂考慮的特徵數 | "sqrt" / "log2" / 整數 | --- ## 6.2 XGBoost(梯度提升樹) ### 6.2.1 為何選擇 XGBoost? - **速度快**:採用二階梯度下降與列裁剪,適合大規模資料。 - **表現優秀**:在 Kaggle 與業界多場比賽中名列前茅。 - **可解釋性**:提供特徵重要度、局部解釋(SHAP)等工具。 ### 6.2.2 基本實作 python import xgboost as xgb from sklearn.metrics import roc_auc_score # 1. DMatrix 轉換 train = xgb.DMatrix(X_train, label=y_train) val = xgb.DMatrix(X_val, label=y_val) # 2. 參數設定 params = { 'objective': 'binary:logistic', 'eval_metric': 'auc', 'eta': 0.05, # 學習速率 'max_depth': 6, 'subsample': 0.8, 'colsample_bytree': 0.8, 'seed': 42 } # 3. 交叉驗證 & 訓練 watchlist = [(train, 'train'), (val, 'eval')] model = xgb.train(params, train, num_boost_round=1000, evals=watchlist, early_stopping_rounds=50, verbose_eval=50) # 4. 預測 & 評估 pred = model.predict(val) print('ROC‑AUC:', roc_auc_score(y_val, pred)) > **技巧**:若資料中存在大量類別特徵,可先使用 `xgb.DMatrix` 的 `enable_categorical` 參數;若對 GPU 加速有需求,可改用 `xgboost` 的 GPU 支援 (`tree_method='gpu_hist'`). ### 6.2.3 SHAP 解釋 python import shap explainer = shap.TreeExplainer(model) shap_values = explainer.shap_values(X_val) shap.summary_plot(shap_values, X_val) > SHAP(SHapley Additive exPlanations)可量化每個特徵對單一樣本預測的貢獻,對金融合規與風險控管極具價值。 --- ## 6.3 神經網路(Fully‑Connected / MLP) ### 6.3.1 基本架構 - **輸入層**:特徵向量。 - **隱藏層**:多層全連接,每層使用非線性激活(ReLU、LeakyReLU)。 - **輸出層**:根據任務(分類、回歸)選擇激活函數(Sigmoid、Softmax、線性)。 ### 6.3.2 範例:客戶流失預測(Keras) python import tensorflow as tf from tensorflow.keras import layers, models, callbacks # 1. 模型建構 model = models.Sequential([ layers.Dense(128, activation='relu', input_shape=(X_train.shape[1],)), layers.Dropout(0.2), layers.Dense(64, activation='relu'), layers.Dropout(0.1), layers.Dense(1, activation='sigmoid') ]) # 2. 編譯 model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['AUC']) # 3. 訓練 history = model.fit(X_train, y_train, epochs=50, batch_size=256, validation_data=(X_val, y_val), callbacks=[callbacks.EarlyStopping(patience=5, restore_best_weights=True)]) # 4. 評估 print('Best AUC:', max(history.history['val_auc'])) > **正則化**:Dropout、L2 正則化 (`kernel_regularizer`) 以及 Batch Normalization 能有效抑制過擬合。 ### 6.3.3 參數選擇 | 參數 | 範例 | 目的 | |------|------|------| | hidden units | 64–512 | 取決於特徵量級與複雜度 | | activation | ReLU / LeakyReLU | 近似線性但保留稀疏性 | | optimizer | Adam / RMSProp | 針對稀疏特徵的學習速率調整 | | dropout rate | 0.1–0.5 | 避免過擬合 | --- ## 6.4 卷積網路(CNN)與循環網路(RNN) ### 6.4.1 卷積網路(CNN) - **適用場景**:時序圖像、序列化交易波動(如股價走勢)。 - **核心概念**:卷積核掃描局部區域,提取局部特徵;池化降低維度並增加不變性。 #### 範例:股票技術指標分類(Keras) python import numpy as np # 1. 轉換成圖像格式: (samples, 7, 7, 1) X_train_img = X_train.values.reshape(-1, 7, 7, 1) X_val_img = X_val.values.reshape(-1, 7, 7, 1) model = models.Sequential([ layers.Conv2D(32, (3, 3), activation='relu', input_shape=(7, 7, 1)), layers.MaxPooling2D((2, 2)), layers.Conv2D(64, (3, 3), activation='relu'), layers.Flatten(), layers.Dense(64, activation='relu'), layers.Dense(1, activation='sigmoid') ]) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['AUC']) model.fit(X_train_img, y_train, epochs=30, batch_size=128, validation_data=(X_val_img, y_val), callbacks=[callbacks.EarlyStopping(patience=3, restore_best_weights=True)]) ### 6.4.2 循環網路(RNN) - **RNN 標準結構**:利用隱藏狀態傳遞時間依賴。 - **長短時記憶網路(LSTM)**:解決梯度消失,擷取長期依賴。 - **門控循環單元(GRU)**:LSTM 的簡化版,計算量更少。 #### 範例:交易日誌情緒分析(PyTorch) python import torch import torch.nn as nn import torch.optim as optim class SentimentLSTM(nn.Module): def __init__(self, vocab_size, embed_dim, hidden_dim, output_dim, n_layers=2, dropout=0.3): super().__init__() self.embedding = nn.Embedding(vocab_size, embed_dim) self.lstm = nn.LSTM(embed_dim, hidden_dim, num_layers=n_layers, batch_first=True, dropout=dropout) self.fc = nn.Linear(hidden_dim, output_dim) self.sigmoid = nn.Sigmoid() def forward(self, x): x = self.embedding(x) out, _ = self.lstm(x) out = out[:, -1, :] # 取最後時間步 out = self.fc(out) return self.sigmoid(out) # 初始化 model = SentimentLSTM(vocab_size=5000, embed_dim=128, hidden_dim=256, output_dim=1) criterion = nn.BCELoss() optimizer = optim.Adam(model.parameters(), lr=1e-3) # 訓練迴圈略(與 TensorFlow 相似,採用 EarlyStopping 等) > **金融場景**:LSTM 可用於交易量時間序列預測、新聞情緒連續影響力評估。 --- ## 6.4 模型部署與可視化 | 步驟 | 工具 | 重點 | |------|------|------| | 1. 模型轉換 | `ONNX` | 轉換後可在多種環境執行 (Python, C++, Java) | | 2. 儲存模型 | `joblib` / `tf.saved_model` / `torch.jit` | 版本控制、冷啟動快速 | | 3. API 化 | `FastAPI` / `Flask` | RESTful 接口、批量推論 | | 4. 監控 | `MLflow` / `Weights & Biases` | 記錄參數、指標、模型版本 | | 5. 可解釋性 | `SHAP` / `lime` | 生成局部/全局解釋報告 | --- ## 6.5 實務案例:電商客戶分群 + 產品推薦 | 步驟 | 描述 | 重點 | |------|------|------| | 1. 數據 | 交易歷史、瀏覽行為、客戶屬性 | 需先進行特徵工程(one‑hot、分桶、嵌入)。 | | 2. 分群 | `AutoEncoder` + K‑Means | 建立客戶相似度矩陣,輸出嵌入向量。 | 3. 產品預測 | `XGBoost` + SHAP | 根據分群特徵預測客戶對某類產品的興趣。 | 4. 推薦 | `Seq2Seq` (Transformer) | 針對瀏覽序列生成個性化商品清單。 | 5. 部署 | `FastAPI` + `uvicorn` + Docker | 可在雲端快速擴縮,並使用 `ONNX` 進行跨語言推論。 > **學習點**:深度模型往往需要大量資料與計算資源,但其 **可擴張性** 與 **自學習** 能在金融風險評估、行銷策略優化上帶來顯著提升。 --- ## 6.6 小結 | 技術 | 優勢 | 風險 | 建議場景 | |------|------|------|-----------| | 樹模型 | 可解釋性強,適合結構化資料 | 過擬合、參數調優困難 | 風險評估、分類任務 | | XGBoost | 速度快、表現佳、SHAP | 需要精細調參、GPU 資源 | 大規模金融交易、Kaggle 競賽 | | MLP | 彈性高、易整合其他特徵 | 過擬合、訓練時間長 | 需要捕捉複雜非線性關係的任務 | | CNN / RNN | 專長時序/圖像特徵 | 需要大量資料、可解釋性較弱 | 股價走勢、語義情緒分析 | > **未來發展**:隨著 **Auto‑ML** 與 **Neural Architecture Search (NAS)** 的成熟,模型選擇與優化將更自動化;然而,金融合規與風險監管仍要求高度可解釋性與透明度。 --- ## 參考文獻 1. Chen, T., & Guestrin, C. (2016). XGBoost: A Scalable Tree Boosting System. 2. Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep Learning. 3. Lundberg, S. M., & Lee, S.-I. (2017). A Unified Approach to Interpreting Model Predictions. 4. Zhang, Y., & Wallace, B. (2017). A Sensitivity Analysis of (and Practitioners Guide to) Recurrent Neural Networks for Sentence Classification. --- > **提示**:在實際專案中,請務必將 **模型訓練**、**評估**、**可解釋性**、**部署** 等步驟打包成 **CI/CD** 流程,確保模型在生產環境中的可靠性與可追蹤性。