機器學習與深度學習・單元 4 / 10
機器學習與深度學習|單元 4:集成學習進階——梯度提升、XGBoost 與 LightGBM
單元 1你在這裡:單元 4單元 10
分享AI學習的熊 授課教師:蘇志雄
適用對象:大學部(資訊、資管、統計、商管與理工相關科系) 實作工具:Python(scikit-learn、XGBoost、LightGBM、SHAP),建議使用 Google Colab
預估學習時間:講義閱讀 80 分鐘+實作 90 分鐘 | 全部程式在 2 顆 CPU 上約 1 分鐘跑完
← 上一單元:單元 3:模型評估、調參與 Pipeline
本單元學習目標
完成本單元後,你將能夠:
- 區分 bagging(大數據商用分析單元 8 的隨機森林)與 boosting,並手寫最簡單的梯度提升迴歸。
- 使用 XGBoost 與 LightGBM,理解學習率、樹的複雜度、子抽樣與提早停止等關鍵參數。
- 用 SHAP 解釋梯度提升模型的整體與個別預測,並和傳統的特徵重要性比較。
- 比較 stacking 與單一模型,討論表格資料上「梯度提升為什麼常常勝出」。
一、bagging 與 boosting
| Bagging(例如隨機森林) | Boosting(例如梯度提升) | |
|---|---|---|
| 樹怎麼來 | 每棵樹用不同的自助樣本獨立訓練(可平行) | 一棵接一棵,每棵修正前面的錯誤(循序) |
| 每棵樹 | 深、複雜(低偏差、高變異) | 淺、簡單(高偏差、低變異) |
| 主要降低 | 變異(平均很多不穩定的樹) | 偏差(一步一步逼近) |
| 太多棵樹會怎樣 | 不會過度配適,只是變慢 | 會過度配適,要用提早停止 |
梯度提升的想法
梯度提升(gradient boosting,Friedman, 2001)的步驟:
- 先用一個常數(例如平均數)當預測 F₀。
- 計算每一筆的負梯度;用平方誤差時,負梯度就是殘差 y − F。
- 用一棵小樹去擬合殘差。
- 更新 F ← F + 學習率 × 這棵樹的預測,回到步驟 2。
「梯度」這個名字的由來:每一步都往損失函數下降最快的方向走一小步,和單元 2 的梯度下降是同一個想法,只是這裡更新的是「預測函數」而不是係數。換成分類用的交叉熵損失,負梯度變成 y − p,流程完全一樣。
二、XGBoost 與 LightGBM
這兩個套件都是梯度提升的高效實作,常見於資料科學競賽與業界:
| XGBoost(Chen & Guestrin, 2016) | LightGBM(Ke et al., 2017) | |
|---|---|---|
| 樹的長法 | 預設逐層(level-wise)長到 max_depth |
逐葉(leaf-wise):每次分裂增益最大的葉子,用 num_leaves 控制 |
| 速度 | 快(tree_method="hist") |
通常更快,記憶體更省 |
| 類別特徵 | enable_categorical=True |
pandas 的 category 型態可直接使用 |
| 共同點 | 直方圖分箱、正則化、子抽樣、缺值自動處理、提早停止 | 同左 |
關鍵參數
| 參數 | XGBoost | LightGBM | 效果 |
|---|---|---|---|
| 學習率 | learning_rate |
learning_rate |
越小越穩,但需要越多棵樹 |
| 樹的數量 | n_estimators |
n_estimators |
搭配提早停止自動決定 |
| 樹的複雜度 | max_depth |
num_leaves、max_depth |
越複雜越容易過度配適 |
| 葉子的最少樣本 | min_child_weight |
min_child_samples |
越大越保守 |
| 子抽樣 | subsample、colsample_bytree |
subsample(需設 subsample_freq)、colsample_bytree |
每棵樹只用部分資料/特徵,降低變異 |
| 正則化 | reg_lambda、reg_alpha |
reg_lambda、reg_alpha |
葉子權重的 L2/L1 懲罰(單元 2 的觀念) |
提早停止(early stopping):另外切一份驗證集,每加一棵樹就看驗證分數,連續 N 棵都沒有進步就停下來。這份驗證集不能是測試集。
三、SHAP:每個特徵貢獻了多少?
傳統的樹模型特徵重要性(分割次數、增益)有兩個問題:只告訴你「整體」重要,不告訴你「方向」與「對某個人」的影響;而且分割次數會偏好有很多不同值的連續特徵。
SHAP(SHapley Additive exPlanations,Lundberg & Lee, 2017)源自合作賽局的 Shapley 值:把一筆預測「公平地」分配給每個特徵。
這個人的預測(對數勝算)= 基準值(全體平均)+ 特徵 1 的 SHAP + 特徵 2 的 SHAP + …
- 個別解釋:某個人為什麼被預測為高收入?哪些特徵往上推、哪些往下拉?
- 整體重要性:所有人的 |SHAP| 平均。
- 依賴圖:某個特徵的值與它的 SHAP 值的關係(例如年齡越大,SHAP 越高嗎?)。
shap.TreeExplainer 對樹模型有快速的精確演算法(TreeSHAP),幾千筆資料幾秒就能算完。
⚠️ SHAP 解釋的是「模型怎麼用特徵」,不是「真實世界的因果」。特徵彼此相關時(例如婚姻狀態與家庭角色),功勞的分配也會互相影響。
四、Stacking 與「梯度提升為什麼常勝」
Stacking 用交叉驗證取得多個基礎模型的預測,再訓練一個「元模型」(通常是邏輯斯迴歸)把它們組合起來。理論上不會比最好的單一模型差太多,但會增加複雜度與訓練時間。
在表格資料(每一欄是一個有意義的特徵)上,梯度提升樹常常是最強的單一模型,研究(例如 Grinsztajn et al., 2022)提到的原因包括:樹模型不受特徵尺度與單調轉換影響、能處理不規則(非平滑)的關係、對無用的特徵較不敏感。影像、聲音、文字等非表格資料則是深度學習的強項(單元 6~9)。
五、Python 實作
範例資料說明
| 資料 | 用途 | 來源與授權 |
|---|---|---|
| 合成一維資料 | 手寫梯度提升 | 程式自行產生 |
| Bike Sharing(UCI #275) | 迴歸:bagging vs. boosting,和單元 2 的線性模型比較 | CC BY 4.0 |
| Census Income(Adult,UCI #2) | 分類:XGBoost、LightGBM、SHAP、stacking | CC BY 4.0 |
兩份 UCI 資料都會在第一次執行時自動下載。Adult 的切分方式和單元 3 相同(random_state=42),所以測試集也相同,可以直接比較。
📥 完整程式碼:ml_unit04_code.zip(內含 ml_unit04.py 與可直接上傳 Colab 的 ml_unit04.ipynb;資料會在第一次執行時自動下載到 data/ 資料夾)
環境準備
Colab 通常已內建 XGBoost、LightGBM 與 SHAP;若版本較舊或在自己的電腦執行:
pip install numpy pandas scikit-learn matplotlib xgboost lightgbm shap
儲存格 1:匯入套件與下載資料
import os, time, random, warnings
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
warnings.filterwarnings("ignore")
# 讓圖表可以顯示繁體中文(依序嘗試 Windows / macOS / Linux 的字型;Colab 請見講義「環境準備」)
plt.rcParams["font.sans-serif"] = [
"Microsoft JhengHei", "PingFang TC", "Noto Sans CJK TC",
"Noto Serif CJK TC", "Arial Unicode MS", "DejaVu Sans",
]
plt.rcParams["axes.unicode_minus"] = False
pd.set_option("display.unicode.east_asian_width", True)
pd.set_option("display.width", 160)
SEED = 42 # 固定亂數種子,讓結果可以重現
random.seed(SEED)
np.random.seed(SEED)
import io, zipfile, urllib.request
os.makedirs("data", exist_ok=True)
def fetch(url, path):
"""下載一次就存在 data/ 資料夾,之後直接讀取本機檔案。"""
if not os.path.exists(path):
req = urllib.request.Request(url, headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36",
"Accept": "*/*", "Accept-Language": "zh-TW,zh;q=0.9,en;q=0.8"})
try:
with urllib.request.urlopen(req, timeout=120) as r:
data = r.read()
except Exception as e:
raise SystemExit(f"下載失敗:{url}\n請用瀏覽器手動下載,存成 {path} 後再執行。({e})")
with open(path, "wb") as f:
f.write(data)
return path
import xgboost as xgb
import lightgbm as lgb
import shap
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import (GradientBoostingRegressor, RandomForestRegressor, HistGradientBoostingRegressor,
RandomForestClassifier, HistGradientBoostingClassifier, StackingClassifier)
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder, StandardScaler, OrdinalEncoder
from sklearn.impute import SimpleImputer
from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score
from sklearn.metrics import mean_squared_error, roc_auc_score
print(f"xgboost {xgb.__version__}、lightgbm {lgb.__version__}、shap {shap.__version__}")
# Bike Sharing(UCI #275,CC BY 4.0):華盛頓特區 Capital Bikeshare 2011–2012 每小時租借量
z = zipfile.ZipFile(fetch("https://archive.ics.uci.edu/static/public/275/bike+sharing+dataset.zip", "data/bike_sharing.zip"))
bike = pd.read_csv(z.open("hour.csv"), parse_dates=["dteday"])
print(f"Bike Sharing:{len(bike):,} 小時 × {bike.shape[1]} 欄,期間 {bike['dteday'].min():%Y-%m-%d} ~ {bike['dteday'].max():%Y-%m-%d}")
# Census Income(Adult,UCI #2,CC BY 4.0):1994 年美國人口普查資料,預測年收入是否超過 5 萬美元
z = zipfile.ZipFile(fetch("https://archive.ics.uci.edu/static/public/2/adult.zip", "data/adult.zip"))
cols = ["age", "workclass", "fnlwgt", "education", "education_num", "marital_status", "occupation",
"relationship", "race", "sex", "capital_gain", "capital_loss", "hours_per_week", "native_country", "income"]
adult = pd.concat([pd.read_csv(z.open(f), header=None, names=cols, skipinitialspace=True, na_values="?",
skiprows=1 if f == "adult.test" else 0) for f in ("adult.data", "adult.test")],
ignore_index=True)
adult["income"] = adult["income"].str.rstrip(".") # adult.test 的標籤多了句點
y_adult = (adult["income"] == ">50K").astype(int)
X_adult = adult.drop(columns=["income", "fnlwgt", "education"]) # fnlwgt 是抽樣權重;education 與 education_num 重複
NUM = ["age", "education_num", "capital_gain", "capital_loss", "hours_per_week"]
CAT = [c for c in X_adult.columns if c not in NUM]
print(f"Adult:{len(adult):,} 人,{X_adult.shape[1]} 個特徵(數值 {len(NUM)}、類別 {len(CAT)}),收入 >50K 的比例 {y_adult.mean():.1%}")
rmse = lambda a, b: np.sqrt(mean_squared_error(a, b))
執行結果:
xgboost 3.4.1、lightgbm 4.7.0、shap 0.54.1
Bike Sharing:17,379 小時 × 17 欄,期間 2011-01-01 ~ 2012-12-31
Adult:48,842 人,12 個特徵(數值 5、類別 7),收入 >50K 的比例 23.9%
儲存格 2:手寫梯度提升
rng = np.random.default_rng(SEED)
x1 = np.sort(rng.uniform(0, 1, 200)); y1 = np.sin(2 * np.pi * x1) + rng.normal(0, 0.3, 200)
X1 = x1[:, None]
LR, M = 0.1, 100
pred = np.full_like(y1, y1.mean()) # 第 0 步:全部預測平均數
trees, stages = [], {0: pred.copy()}
for m in range(1, M + 1):
resid = y1 - pred # 平方誤差損失的負梯度 = 殘差
tree = DecisionTreeRegressor(max_depth=2, random_state=SEED).fit(X1, resid)
pred += LR * tree.predict(X1) # 只往殘差的方向走一小步(學習率)
trees.append(tree)
if m in (1, 10, 100): stages[m] = pred.copy()
if m in (1, 5, 10, 30, 100): print(f"第 {m:>3} 棵樹之後:訓練 MSE {np.mean(np.square(y1 - pred)):.4f}")
sk = GradientBoostingRegressor(n_estimators=M, learning_rate=LR, max_depth=2, random_state=SEED).fit(X1, y1)
print(f"scikit-learn GradientBoostingRegressor(同樣設定):訓練 MSE {np.mean(np.square(y1 - sk.predict(X1))):.4f}")
執行結果:
第 1 棵樹之後:訓練 MSE 0.5002
第 5 棵樹之後:訓練 MSE 0.2846
第 10 棵樹之後:訓練 MSE 0.1677
第 30 棵樹之後:訓練 MSE 0.0813
第 100 棵樹之後:訓練 MSE 0.0576
scikit-learn GradientBoostingRegressor(同樣設定):訓練 MSE 0.0576
每棵樹只有深度 2(最多 4 個葉子),單獨一棵幾乎沒用;但每一棵都去修正前面剩下的殘差,100 棵之後訓練 MSE 從 0.50 降到 0.058。scikit-learn 的 GradientBoostingRegressor 用同樣設定,得到一樣的訓練 MSE(0.0576)——它做的就是這 10 行程式。
儲存格 3:bagging vs. boosting
FEAT = ["season", "yr", "mnth", "hr", "holiday", "weekday", "workingday", "weathersit", "temp", "atemp", "hum", "windspeed"]
cut = pd.Timestamp("2012-07-01")
btr, bte = bike[bike["dteday"] < cut], bike[bike["dteday"] >= cut]
reg_models = {"隨機森林(bagging,300 棵)": RandomForestRegressor(300, min_samples_leaf=2, n_jobs=-1, random_state=SEED),
"GradientBoosting(300 棵,深度 5)": GradientBoostingRegressor(n_estimators=300, max_depth=5, learning_rate=0.1, random_state=SEED),
"HistGradientBoosting": HistGradientBoostingRegressor(max_iter=300, random_state=SEED)}
bike_res = {}
for name, m in reg_models.items():
t = time.time(); m.fit(btr[FEAT], np.log1p(btr["cnt"]))
p = np.expm1(m.predict(bte[FEAT]))
bike_res[name] = rmse(bte["cnt"], p)
print(f"{name:<32} 測試 RMSE {bike_res[name]:6.1f} 訓練 {time.time() - t:5.1f} 秒")
print("對照:單元 2 最好的線性模型(D,含交互作用)測試 RMSE 約 91")
執行結果:
隨機森林(bagging,300 棵) 測試 RMSE 78.2 訓練 4.1 秒
GradientBoosting(300 棵,深度 5) 測試 RMSE 67.1 訓練 4.0 秒
HistGradientBoosting 測試 RMSE 69.6 訓練 0.5 秒
對照:單元 2 最好的線性模型(D,含交互作用)測試 RMSE 約 91
和單元 2 相同的時間切分(2012 下半年當測試集)。樹模型直接使用原始的時段、月份等欄位,不需要 one-hot,也不需要手動建立交互作用——樹會自己找出「上班日 × 時段」這種交互作用。
| 模型 | 測試 RMSE |
|---|---|
| 單元 2 最好的線性模型 | 約 91 |
| 隨機森林 | 78.2 |
| HistGradientBoosting(預設參數) | 69.6 |
| GradientBoosting(深度 5) | 67.1 |
HistGradientBoosting 先把每個特徵分成最多 255 個區間(直方圖),只花 0.5 秒,比傳統的 GradientBoosting 快將近 9 倍,準確度卻差不多。
儲存格 4:XGBoost 與 LightGBM
Xa = X_adult.copy()
for c in CAT: Xa[c] = Xa[c].astype("category") # 兩個套件都能直接處理 pandas 的類別型態
Xa_tr, Xa_te, ya_tr, ya_te = train_test_split(Xa, y_adult, test_size=0.2, stratify=y_adult, random_state=SEED)
Xa_fit, Xa_val, ya_fit, ya_val = train_test_split(Xa_tr, ya_tr, test_size=0.2, stratify=ya_tr, random_state=SEED)
print(f"訓練 {len(ya_fit):,}/驗證(提早停止用){len(ya_val):,}/測試 {len(ya_te):,}")
t = time.time()
xgb_m = xgb.XGBClassifier(n_estimators=2000, learning_rate=0.05, max_depth=6, subsample=0.8, colsample_bytree=0.8,
tree_method="hist", enable_categorical=True, eval_metric="auc", early_stopping_rounds=50,
random_state=SEED, n_jobs=2)
xgb_m.fit(Xa_fit, ya_fit, eval_set=[(Xa_val, ya_val)], verbose=False)
print(f"XGBoost:最佳迭代 {xgb_m.best_iteration},驗證 AUC {xgb_m.best_score:.4f},"
f"測試 AUC {roc_auc_score(ya_te, xgb_m.predict_proba(Xa_te)[:, 1]):.4f},{time.time() - t:.1f} 秒")
t = time.time()
lgb_m = lgb.LGBMClassifier(n_estimators=2000, learning_rate=0.05, num_leaves=31, subsample=0.8, subsample_freq=1,
colsample_bytree=0.8, random_state=SEED, n_jobs=2, verbose=-1)
lgb_m.fit(Xa_fit, ya_fit, eval_set=[(Xa_val, ya_val)], eval_metric="auc", callbacks=[lgb.early_stopping(50, verbose=False)])
print(f"LightGBM:最佳迭代 {lgb_m.best_iteration_},驗證 AUC {lgb_m.best_score_['valid_0']['auc']:.4f},"
f"測試 AUC {roc_auc_score(ya_te, lgb_m.predict_proba(Xa_te)[:, 1]):.4f},{time.time() - t:.1f} 秒")
執行結果:
訓練 31,258/驗證(提早停止用)7,815/測試 9,769
XGBoost:最佳迭代 289,驗證 AUC 0.9303,測試 AUC 0.9299,1.3 秒
LightGBM:最佳迭代 236,驗證 AUC 0.9293,測試 AUC 0.9308,0.8 秒
我們把訓練資料再切出 20% 當驗證集給提早停止用。最多 2,000 棵、學習率 0.05,XGBoost 在第 289 棵、LightGBM 在第 236 棵左右就停了。兩者的測試 AUC 都約 0.930,比單元 3 的邏輯斯迴歸(0.904)好得多,也略優於單元 3 調參後的 HistGradientBoosting(0.927)。
儲存格 5:學習率與樹的數量
lr_curves = {}
for lr in (0.3, 0.1, 0.03):
m = lgb.LGBMClassifier(n_estimators=3000, learning_rate=lr, num_leaves=31, random_state=SEED, n_jobs=2, verbose=-1)
m.fit(Xa_fit, ya_fit, eval_set=[(Xa_val, ya_val)], eval_metric="auc", callbacks=[lgb.early_stopping(100, verbose=False)])
lr_curves[lr] = m.evals_result_["valid_0"]["auc"]
print(f"learning_rate = {lr:<5}:最佳迭代 {m.best_iteration_:>4},驗證 AUC {max(lr_curves[lr]):.4f}")
執行結果:
learning_rate = 0.3 :最佳迭代 30,驗證 AUC 0.9293
learning_rate = 0.1 :最佳迭代 159,驗證 AUC 0.9298
learning_rate = 0.03 :最佳迭代 480,驗證 AUC 0.9302
學習率 0.3 只要 30 棵樹就達到最佳,0.03 要 480 棵,但驗證 AUC 最高(0.9302)。規則是:學習率 × 樹的數量 大致固定;學習率小一點通常略好,代價是訓練時間。實務上常先用較大的學習率快速調其他參數,最後再把學習率調小、讓提早停止決定樹的數量。
儲存格 6:樹的複雜度
rows = []
for leaves in (4, 15, 63, 255):
for mcs in (5, 50):
m = lgb.LGBMClassifier(n_estimators=3000, learning_rate=0.1, num_leaves=leaves, min_child_samples=mcs,
random_state=SEED, n_jobs=2, verbose=-1)
m.fit(Xa_fit, ya_fit, eval_set=[(Xa_val, ya_val)], eval_metric="auc", callbacks=[lgb.early_stopping(100, verbose=False)])
rows.append({"num_leaves": leaves, "min_child_samples": mcs, "最佳迭代": m.best_iteration_,
"訓練 AUC": roc_auc_score(ya_fit, m.predict_proba(Xa_fit)[:, 1]), "驗證 AUC": m.best_score_["valid_0"]["auc"]})
print(pd.DataFrame(rows).round(4).to_string(index=False))
執行結果:
num_leaves min_child_samples 最佳迭代 訓練 AUC 驗證 AUC
4 5 970 0.9404 0.9300
4 50 1229 0.9414 0.9302
15 5 187 0.9435 0.9298
15 50 324 0.9484 0.9304
63 5 87 0.9547 0.9290
63 50 127 0.9574 0.9295
255 5 35 0.9642 0.9243
255 50 43 0.9571 0.9242
num_leaves越大,訓練 AUC 越高(0.940 → 0.964),但 255 片葉子時驗證 AUC 反而最低(0.924)——過度配適。min_child_samples = 50(每片葉子至少 50 筆)在多數情況下讓驗證 AUC 略為提高。- 最佳組合(15 片葉子、50)的驗證 AUC 0.9304;4 片葉子也有 0.930,只是需要上千棵樹。
儲存格 7:SHAP
expl = shap.TreeExplainer(lgb_m)
Xs = Xa_te.sample(2000, random_state=SEED)
sv = expl.shap_values(Xs)
sv = sv[1] if isinstance(sv, list) else sv # 不同版本的 shap 輸出格式略有不同
imp = pd.DataFrame({"平均 |SHAP|": np.abs(sv).mean(axis=0),
"分割次數重要性": lgb_m.booster_.feature_importance("split"),
"增益重要性": lgb_m.booster_.feature_importance("gain")}, index=Xs.columns)
imp["分割次數排名"] = imp["分割次數重要性"].rank(ascending=False).astype(int)
imp["增益排名"] = imp["增益重要性"].rank(ascending=False).astype(int)
print(imp.sort_values("平均 |SHAP|", ascending=False)[["平均 |SHAP|", "增益排名", "分割次數排名"]].round(3).to_string())
base = float(np.ravel(expl.expected_value)[-1])
i = int(np.argmax(lgb_m.predict_proba(Xs)[:, 1])) # 預測機率最高的一個人
row = pd.DataFrame({"特徵值": Xs.iloc[i].astype(str), "SHAP(對數勝算)": sv[i]}).sort_values("SHAP(對數勝算)", key=np.abs, ascending=False)
print(f"\n個別解釋:基準值(平均對數勝算){base:.3f},這個人的對數勝算 {base + sv[i].sum():.3f},"
f"機率 {1 / (1 + np.exp(-(base + sv[i].sum()))):.3f}")
print(row.head(6).round(3).to_string())
執行結果:
平均 |SHAP| 增益排名 分割次數排名
relationship 0.803 1 10
age 0.736 4 1
capital_gain 0.595 2 4
marital_status 0.521 5 11
education_num 0.429 3 3
occupation 0.399 6 6
hours_per_week 0.315 8 2
capital_loss 0.145 7 5
sex 0.143 11 9
workclass 0.079 9 7
race 0.055 12 12
native_country 0.053 10 8
個別解釋:基準值(平均對數勝算)-2.384,這個人的對數勝算 6.828,機率 0.999
特徵值 SHAP(對數勝算)
capital_gain 15024 6.021
education_num 14 0.793
relationship Husband 0.542
occupation Exec-managerial 0.529
hours_per_week 50 0.425
marital_status Married-civ-spouse 0.390
整體重要性:平均 |SHAP| 最大的是 relationship(家庭角色,0.803)、age(0.736)、capital_gain(0.595)。傳統的「分割次數重要性」把 relationship 排到第 10、hours_per_week 排到第 2——因為連續特徵有很多可分的切點,分割次數多不代表影響大。用 SHAP 或增益排名較可靠。
個別解釋:預測機率最高(0.999)的人,主要原因是資本利得 15,024 美元(SHAP +6.02,遠大於其他特徵),其次是教育年數 14 年、身為丈夫、高階主管職位。基準值 −2.384 加上所有 SHAP 值,正好等於這個人的對數勝算 6.828。
儲存格 8:Stacking
pre_lin = ColumnTransformer([("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), NUM),
("cat", make_pipeline(SimpleImputer(strategy="most_frequent"), OneHotEncoder(handle_unknown="ignore", min_frequency=20)), CAT)])
pre_tree = ColumnTransformer([("num", "passthrough", NUM),
("cat", OrdinalEncoder(handle_unknown="use_encoded_value", unknown_value=-1, encoded_missing_value=-1), CAT)])
cat_idx = list(range(len(NUM), len(NUM) + len(CAT)))
base_models = [("logit", make_pipeline(pre_lin, LogisticRegression(max_iter=2000))),
("rf", make_pipeline(pre_tree, RandomForestClassifier(150, min_samples_leaf=3, n_jobs=-1, random_state=SEED))),
("hgb", make_pipeline(pre_tree, HistGradientBoostingClassifier(categorical_features=cat_idx, random_state=SEED)))]
Xo_tr, Xo_te = X_adult.loc[Xa_tr.index], X_adult.loc[Xa_te.index]
cv3 = StratifiedKFold(3, shuffle=True, random_state=SEED)
stack = StackingClassifier(base_models, final_estimator=LogisticRegression(), cv=cv3, stack_method="predict_proba", n_jobs=1)
t = time.time()
for name, m in base_models + [("stacking", stack)]:
m.fit(Xo_tr, ya_tr)
print(f"{name:<9} 測試 AUC {roc_auc_score(ya_te, m.predict_proba(Xo_te)[:, 1]):.4f}")
print(f"(共 {time.time() - t:.0f} 秒)Stacking 的組合權重:{', '.join(f'{n} {w:.2f}' for (n, _), w in zip(base_models, stack.final_estimator_.coef_[0]))}")
執行結果:
logit 測試 AUC 0.9039
rf 測試 AUC 0.9197
hgb 測試 AUC 0.9300
stacking 測試 AUC 0.9294
(共 10 秒)Stacking 的組合權重:logit 0.15, rf 1.36, hgb 5.21
Stacking(0.9294)並沒有比單獨的 HistGradientBoosting(0.9300)好;元模型給梯度提升的權重最大(5.21),幾乎就是在使用梯度提升本身。基礎模型差距很大、而且錯誤型態相似時,stacking 的好處有限,卻要多花好幾倍的訓練時間。先把最強的單一模型調好,通常比堆疊更划算。
儲存格 9:畫出結果
fig, ax = plt.subplots(2, 2, figsize=(12, 9))
ax[0, 0].scatter(x1, y1, s=10, c="lightgray", label="資料")
for m, c in ((1, "tab:blue"), (10, "tab:orange"), (100, "tab:green")):
ax[0, 0].plot(x1, stages[m], c=c, label=f"{m} 棵樹")
ax[0, 0].legend(fontsize=8); ax[0, 0].set_title("手寫梯度提升:每加一棵小樹,往殘差走一小步")
for lr, curve in lr_curves.items():
ax[0, 1].plot(range(1, len(curve) + 1), curve, label=f"learning_rate = {lr}")
ax[0, 1].set_xscale("log"); ax[0, 1].set_ylim(0.90, 0.935); ax[0, 1].set_xlabel("樹的數量(對數刻度)"); ax[0, 1].set_ylabel("驗證 AUC")
ax[0, 1].set_title("學習率越小,需要越多棵樹"); ax[0, 1].legend(fontsize=8)
top = imp.sort_values("平均 |SHAP|")
ax[1, 0].barh(top.index, top["平均 |SHAP|"], color="tab:blue")
ax[1, 0].set_xlabel("平均 |SHAP 值|(對數勝算)"); ax[1, 0].set_title("SHAP 整體重要性(LightGBM,Adult 測試集 2,000 人)")
j = list(Xs.columns).index("age")
ax[1, 1].scatter(Xs["age"], sv[:, j], s=6, alpha=0.5, c=(Xs["marital_status"] == "Married-civ-spouse"), cmap="coolwarm")
ax[1, 1].axhline(0, color="k", lw=0.8)
ax[1, 1].set_xlabel("年齡"); ax[1, 1].set_ylabel("年齡的 SHAP 值"); ax[1, 1].set_title("SHAP 依賴圖:年齡(紅=已婚、藍=其他)")
plt.tight_layout()
plt.savefig("ml_unit04_charts.png", dpi=110)
plt.show()

怎麼讀這張圖: 左上是手寫梯度提升在 1、10、100 棵樹時的預測,曲線逐步逼近資料的形狀;右上是三種學習率的驗證 AUC 隨樹的數量變化,學習率 0.3 很快到頂後開始下降(過度配適);左下是 SHAP 整體重要性;右下是年齡的 SHAP 依賴圖:年齡的影響大約在 25~50 歲之間快速上升、之後持平或下降,而且紅點(已婚)多半在藍點上方,顯示年齡與婚姻狀態有交互作用。
六、本單元重點整理
- Bagging 平行訓練深樹、降低變異;Boosting 循序訓練淺樹、每棵修正前面的殘差,降低偏差。
- 梯度提升=在「函數空間」做梯度下降;平方誤差的負梯度就是殘差。
- 學習率 × 樹的數量大致固定;用驗證集做提早停止決定樹的數量。
- 樹太複雜(
num_leaves、max_depth太大)會過度配適;min_child_samples、子抽樣、正則化讓模型保守一點。 - SHAP 提供個別與整體的解釋,比分割次數重要性可靠;但它解釋的是模型,不是因果。
- 表格資料上,調好的梯度提升常常就是最強的單一模型;stacking 的邊際效益通常很小。
七、練習題
第 1 題 把手寫梯度提升的學習率改為 1.0、0.1、0.01(都是 100 棵樹),比較訓練 MSE 和「與真實函數 sin(2πx) 的 MSE」。哪個學習率最好?為什麼?
第 2 題 LightGBM 用學習率 0.3、固定 2,000 棵樹、不用提早停止,驗證 AUC 會怎麼變化?
第 3 題 在 SHAP 的 2,000 人中,找出預測機率在中位數的那個人,列出影響最大的 5 個特徵。你相信這些解釋嗎?
第 4 題 是非題,並說明理由:
(a) 隨機森林的樹越多越容易過度配適。
(b) 梯度提升中,每一棵樹都是用原始的 y 訓練的。
(c) 學習率越小,通常需要越多棵樹才能達到同樣的訓練誤差。
(d) 分割次數最多的特徵,一定是對預測影響最大的特徵。
(e) 某特徵的 SHAP 值為正,代表在現實中改變這個特徵就能提高收入。
八、練習題參考答案
以下程式接在儲存格 9 之後執行。
第 1 題
for lr in (1.0, 0.1, 0.01):
xv = np.linspace(0, 1, 500); yv = np.sin(2 * np.pi * xv)
p_new = np.full_like(xv, y1.mean()); p_tr = np.full_like(y1, y1.mean())
for m in range(100): # 同時記錄訓練資料與新資料(500 個等距點)的預測
t_ = DecisionTreeRegressor(max_depth=2, random_state=SEED).fit(X1, y1 - p_tr)
p_tr += lr * t_.predict(X1); p_new += lr * t_.predict(xv[:, None])
print(f"lr = {lr:<4}:100 棵樹後訓練 MSE {np.mean(np.square(y1 - p_tr)):.4f},與真實函數的 MSE {np.mean(np.square(yv - p_new)):.4f}")
執行結果:
lr = 1.0 :100 棵樹後訓練 MSE 0.0010,與真實函數的 MSE 0.0881
lr = 0.1 :100 棵樹後訓練 MSE 0.0576,與真實函數的 MSE 0.0175
lr = 0.01:100 棵樹後訓練 MSE 0.1749,與真實函數的 MSE 0.1010
學習率 1.0 時訓練 MSE 只剩 0.001(把雜訊全部背下來),和真實函數的誤差反而較大(0.088);0.01 走得太慢,100 棵還沒學完(0.101,配適不足);0.1 最好(0.018)。這又是一次偏差–變異權衡。
第 2 題
m = lgb.LGBMClassifier(n_estimators=2000, learning_rate=0.3, num_leaves=31, random_state=SEED, n_jobs=2, verbose=-1)
m.fit(Xa_fit, ya_fit, eval_set=[(Xa_val, ya_val)], eval_metric="auc")
c = m.evals_result_["valid_0"]["auc"]
print(f"最高驗證 AUC {max(c):.4f}(第 {int(np.argmax(c)) + 1} 棵),第 2,000 棵時 {c[-1]:.4f};"
f"訓練 AUC {roc_auc_score(ya_fit, m.predict_proba(Xa_fit)[:, 1]):.4f}")
執行結果:
最高驗證 AUC 0.9293(第 30 棵),第 2,000 棵時 0.9062;訓練 AUC 0.9982
驗證 AUC 在第 30 棵時最高(0.9293),之後一路下降,到第 2,000 棵只剩 0.906;訓練 AUC 卻升到 0.998。梯度提升會過度配適,這就是為什麼一定要搭配提早停止(隨機森林則沒有這個問題)。
第 3 題
k = int(np.argsort(lgb_m.predict_proba(Xs)[:, 1])[len(Xs) // 2]) # 預測機率在中位數的人
r = pd.DataFrame({"特徵值": Xs.iloc[k].astype(str), "SHAP": sv[k]}).sort_values("SHAP", key=np.abs, ascending=False)
print(f"機率 {lgb_m.predict_proba(Xs.iloc[[k]])[0, 1]:.3f};基準值+SHAP 總和 = {base + sv[k].sum():.3f}")
print(r.head(5).round(3).to_string())
執行結果:
機率 0.066;基準值+SHAP 總和 = -2.656
特徵值 SHAP
native_country France 1.074
relationship Unmarried -0.752
occupation Other-service -0.741
age 58 0.726
marital_status Divorced -0.351
這位 58 歲、離婚、從事服務業的人,預測機率 6.6%。家庭角色(未婚有扶養)、職業(其他服務業)把機率往下拉;年齡 58 往上推。值得注意的是 native_country = France 的 SHAP 高達 +1.07:Adult 中來自法國的人很少,模型可能只是從少數樣本學到了偶然的規律。SHAP 忠實地說出了「模型怎麼想」,但這不代表模型的想法是對的——解釋工具最重要的用途之一,就是幫你發現這類可疑的規律。可以考慮把罕見類別合併(如單元 3 的 min_frequency),或加大 min_child_samples。
第 4 題
(a) 錯。隨機森林的樹是獨立訓練後平均,樹越多只是越穩定;會因樹太多而過度配適的是梯度提升。
(b) 錯。除了第一步,每棵樹擬合的是前面所有樹留下的殘差(負梯度)。
(c) 對。每一步走得越小,需要越多步(如儲存格 5:0.3 → 30 棵,0.03 → 480 棵)。
(d) 錯。如儲存格 7,連續特徵有很多切點,分割次數多;relationship 的分割次數排第 10,SHAP 卻排第 1。
(e) 錯。SHAP 描述的是模型的預測如何依賴特徵,不是因果效果;要回答「改變它會怎樣」,需要實驗或因果推論的方法。
👉 前往單元 5:非監督式學習進階——降維、視覺化與異常偵測 →
© 分享AI學習的熊(suhsiung.com)・機器學習與深度學習課程・授課教師:蘇志雄。資料來源:Becker, B. & Kohavi, R. (1996). Adult [Dataset]. UCI Machine Learning Repository. https://doi.org/10.24432/C5XW20;Fanaee-T, H. (2013). Bike Sharing [Dataset]. UCI Machine Learning Repository. https://doi.org/10.24432/C5W894(皆為 CC BY 4.0)。方法參考:Friedman, J. H. (2001). Greedy function approximation: A gradient boosting machine. Annals of Statistics, 29(5);Chen, T., & Guestrin, C. (2016). XGBoost: A scalable tree boosting system. KDD;Ke, G. et al. (2017). LightGBM: A highly efficient gradient boosting decision tree. NeurIPS;Lundberg, S. M., & Lee, S.-I. (2017). A unified approach to interpreting model predictions. NeurIPS;Grinsztajn, L., Oyallon, E., & Varoquaux, G. (2022). Why do tree-based models still outperform deep learning on typical tabular data? NeurIPS Datasets and Benchmarks Track。
