XGBoost

定義迭代 $t$ 次目標函數為

$$\begin{align*} \mathcal{L}^{(t)} = \sum_{i=1}^{n} l(y_i, \hat{y}_i^{(t-1)} + f_t(\mathbf{x}_i)) + \Omega(f_t) \end{align*}$$

where

  • $\Omega(f) = \gamma T + \frac{1}{2}\lambda \|\mathbf{w}\|^2$
  • loss function $l(y_i, \hat{y}_i^{(t-1)})$ measures the difference between $y_i, \hat{y}_i^{(t-1)}$
  • $\Omega(f_t)$ is the penalty
  • leaf weight $\mathbf{w}=(w_1, ,\cdots, w_T)$
  • sample index $i=1, \cdots, n$
  • tree index $t=1, \cdots, K$
  • leaf index $j=1, \cdots, T$
  • $\lambda, \gamma$ are parameters

目的

根據舊模型造成的殘差,逐個增加分類樹,在迭代$t$ 次建立能讓當下目標函數降最多的分類樹 $f_t$

$$\begin{align*}\arg\min_{f_t} \mathcal{L}^{(t)}\end{align*}$$

做法

當 loss function $l$太過複雜,權重$w$ 無法導出解析解。因此統一使用泰勒展開,逼近目標函數求解

$$\begin{align*}\mathcal{L}^{(t)} \simeq \sum_{i=1}^{n} [l(y_i, \hat{y}^{(t-1)}) + g_i f_t(\mathbf{x}_i) + \frac{1}{2} h_i f_t^2(\mathbf{x}_i)] + \Omega(f_t)\end{align*}$$

where

$$\begin{align*}g_i = \partial_{\hat{y}^{(t-1)}} l(y_i, \hat{y}^{(t-1)}) \text{ and } h_i = \partial_{\hat{y}^{(t-1)}}^2 l(y_i, \hat{y}^{(t-1)})\end{align*}$$

第$t$ 次迭代,前面 $t-1$ 個樹結構已經決定,$l(y_i, \hat{y}^{(t-1)})$ 視作常數

$$\begin{align*}\tilde{\mathcal{L}}^{(t)} = \sum_{i=1}^{n} [g_i f_t(\mathbf{x}_i) + \frac{1}{2} h_i f_t^2(\mathbf{x}_i)] + \Omega(f_t)\end{align*}$$

當樣本 $\mathbf{x}_i$ 歸類在 $j$ 葉子, $f_t(\mathbf{x}_i)=w_j$

$$\begin{align*} \tilde{\mathcal{L}}^{(t)} &= \sum_{i=1}^{n} [g_i f_t(\mathbf{x}_i) + \frac{1}{2} h_i f_t^2(\mathbf{x}_i)] + \gamma T + \frac{1}{2}\lambda \sum_{j=1}^{T} w_j^2 \\ &= \sum_{j=1}^{T} [(\sum_{i \in I_j} g_i)w_j + \frac{1}{2}(\sum_{i \in I_j} h_i + \lambda)w_j^2] + \gamma T \end{align*}$$

微分找出極小值發生點,亦即 $j$ 葉子的最佳權重

$$\begin{align*}w_j^* = -\frac{\sum_{i \in I_j} g_i}{\sum_{i \in I_j} h_i + \lambda}\end{align*}$$

$w_j^*$ 帶入step3,得到 score function

$$\begin{align*}\tilde{\mathcal{L}}^{(t)}(q) = -\frac{1}{2} \sum_{j=1}^{T} \frac{(\sum_{i \in I_j} g_i)^2}{\sum_{i \in I_j} h_i + \lambda} + \gamma T\end{align*}$$

score function表示當前結構下的最小總成本,score 越低越好

剪枝(pruning)

分裂前,葉子 $j$ 的 score

$$\begin{align*} -\frac{1}{2}\frac{(\sum_{i \in I_j} g_i)^2}{\sum_{i \in I_j} h_i + \lambda} + \gamma \end{align*}$$

分裂後,葉子 $j$ 生出兩個葉子,score 變成

$$\begin{align*}-\frac{1}{2} \left[\frac{(\sum_{i \in I_L} g_i)^2}{\sum_{i \in I_L} h_i + \lambda} + \frac{(\sum_{i \in I_R} g_i)^2}{\sum_{i \in I_R} h_i + \lambda}\right] + 2\gamma\end{align*}$$

定義 gain= 分裂前的 score- 分裂後的 score

$$\begin{align*}\mathcal{gain} = \frac{1}{2} \left[ \frac{(\sum_{i \in I_L} g_i)^2}{\sum_{i \in I_L} h_i + \lambda} + \frac{(\sum_{i \in I_R} g_i)^2}{\sum_{i \in I_R} h_i + \lambda} - \frac{(\sum_{i \in I} g_i)^2}{\sum_{i \in I} h_i + \lambda} \right] - \gamma\end{align*}$$

如果分裂後 score 減少,$i.e. \ gain>0$,該次分裂對於降低 loss+penalty 是有益的。因此,只需修剪那些 $gain\leq 0$ 的分支。pruning 目的是清除部分分支,避免 ovefitting,常見以下兩種

  • Pre-stopping(預剪枝):當節點的 $\text{gain} \le 0$,就停止繼續向下分支
  • Post-pruning(後剪枝):為了避免第一次切分表現不好,但第二次切分讓 loss 大幅度降低,這樣的情況。會先讓樹長到最大深度 max_depth,再由下往上檢查,並遞迴剪去 $\text{Gain} < 0$ 的枝葉

xgboost 使用 Post-pruning

處理缺失值

  • 分別用左分支、右分支歸類所有的 missing data,看哪個 score 較高,決定所有的 missing data 該使用哪個分支

參數

  • 隨著樹的數量增加, training set 的 loss 會陡降後趨於平緩;Validation Set loss 則是下降後,因為樹的數量過多造成的雜訊,loss 回升

  • 如何控制樹的數量過多的情況?
  • early_stopping_rounds = N ,表示當連續 N 輪,Validation loss 沒有突破歷史新低,停止增加樹。或是用 n_estimators=N 限制樹的總數量為 N
  • 如何防止 overfitting?
  • reg_lambda, reg_alpha , gamma 數字調大,增加樹的數目懲罰效果;或是 colsample_bytree, subsample調小
  • learning_rate $\eta$ 調小,可減少新建立的樹對預測的影響 $$\begin{align*}\hat{y}_i^{(t)}=\hat{y}_i^{(t-1)} + \eta f_t(\mathbf{x}_i)\end{align*}$$

缺點

  • 用泰勒二階計算 loss+penalty 的近似值,因此優化的函數並不是原本的目標函數,有些誤差
  • 想得到全域最佳解,必須列出所有可能結構,逐一比較,是個NP hard問題,退而求其次,限制樹的數量並使用 Post-pruning 剪枝

實作

資料來自 kaggle

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
from sklearn.model_selection import RandomizedSearchCV, StratifiedKFold
from sklearn.preprocessing import LabelEncoder
from xgboost import XGBClassifier
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics import (
    auc,
    confusion_matrix,
    balanced_accuracy_score,
    roc_curve,
    roc_auc_score
)
import time



df=pd.read_csv("C:/Users/user/Desktop/data/Predicting_purchase/train.csv")
test_data=pd.read_csv("C:/Users/user/Desktop/data/Predicting_purchase/test.csv")
df.columns
df.info()


# 類別變數->數值 ----

# 找出所有字串欄位
str_cols = df.select_dtypes(include=["str", "object", "string"]).columns

# 儲存各欄位的 encoder
encoders = {}
for col in str_cols:
    encoders[f"{col}_encoder"] = LabelEncoder()
    df[col] = encoders[f"{col}_encoder"].fit_transform(df[col])
    print(f"\n{col}_encoder 對應關係:")
    for i, value in enumerate(encoders[f"{col}_encoder"].classes_):
        print(i, value)


str_cols_test = [j for j in str_cols if j != "Will_Buy_EV"]
for col in str_cols_test:
    test_data[col] = encoders[f"{col}_encoder"].fit_transform(test_data[col])

# Separate X and y
train_data = df.copy()
x_train = train_data.drop(columns=["Will_Buy_EV"])
y_train = train_data["Will_Buy_EV"]





# 調參數 ----
# 定義要搜尋的超參數範圍
param_grid = {
    'max_depth': [3, 5],  # 每棵樹的最大深度
    'learning_rate': [0.01, 0.05, 0.1], # 每一棵新樹對最終模型的影響程度
    'n_estimators': [300, 500], # 共建立幾棵樹
    'subsample': [0.6, 0.8, 1.0], # 每棵樹隨機使用 80% 的 training samples
    'colsample_bytree': [0.6, 0.8, 1.0], # 每棵樹隨機使用 80% 的 features
    'min_child_weight': [1, 3, 5] # 一個 leaf 至少需要的 Hessian 總量
}

# 建立基本模型
base_xgb = XGBClassifier(eval_metric="logloss", random_state=42)
# 建立切分器並固定 random_state
cv_splitter = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

# 自動進行 K-Fold 交叉驗證與參數搜尋
search = RandomizedSearchCV(
    estimator=base_xgb,
    param_distributions=param_grid,
    n_iter=2,                 # 隨機嘗試 2 種組合
    scoring='balanced_accuracy', # 評估指標
    cv=cv_splitter,                     # 傳入這個切分器
    random_state=42,
    n_jobs=-1
)

# 開始搜尋
search.fit(x_train, y_train)

# 取得最好的模型與最佳參數
best_model = search.best_estimator_
print("最佳超參數組合:", search.best_params_)
print("最佳 CV 得分:", search.best_score_)













# 提取第 Fold N 的資料索引
target_fold = 0  # 可改為 0~4
splits = list(cv_splitter.split(x_train, y_train))
train_idx, val_idx = splits[target_fold]

# 取得該次 CV 的訓練集與驗證集資料
fold_x_train, fold_y_train = x_train.iloc[train_idx], y_train.iloc[train_idx]
fold_x_val, fold_y_val = x_train.iloc[val_idx], y_train.iloc[val_idx]

print(f"第 {target_fold + 1} 折的訓練集筆數:", len(fold_x_train))
print(f"第 {target_fold + 1} 折的驗證集筆數:", len(fold_x_val))


# ROC ----
y_prob = best_model.predict_proba(fold_x_val)[:, 1]
fpr, tpr, thresholds = roc_curve(fold_y_val, y_prob)
roc_auc = auc(fpr, tpr)

plt.figure(figsize=(6, 6))

plt.plot(
    fpr,
    tpr,
    label=f"XGBoost (AUC = {roc_auc:.3f})"
)
plt.plot(
    [0, 1],
    [0, 1],
    linestyle="--",
    label="Random"
)
plt.xlabel("False Positive Rate")
plt.ylabel("True Positive Rate")
plt.title("ROC Curve")
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.savefig(
    r"C:\Users\user\Desktop\roc_1.png",
    dpi=300,
    bbox_inches="tight"
)
plt.show()



# loss curve ----

# 訓練模型並傳入驗證集
best_model.fit(
    fold_x_train,
    fold_y_train,
    eval_set=[(fold_x_train, fold_y_train), (fold_x_val, fold_y_val)],
    verbose=False,
)

# 提取訓練歷史紀錄
results = best_model.evals_result()
train_loss = results["validation_0"]["logloss"]
val_loss = results["validation_1"]["logloss"]
trees_range = range(1, len(train_loss) + 1)

# 繪製 Loss 曲線圖
plt.figure(figsize=(10, 6))
plt.plot(trees_range, train_loss, label="Train Loss", color="blue")
plt.plot(trees_range, val_loss, label="Validation Loss", color="orange")
plt.xlabel("Number of Trees (n_estimators)")
plt.ylabel("Log Loss")
plt.title("XGBoost Learning Curve (Train vs Validation Loss)")
plt.legend()
plt.grid(True)
plt.savefig(
    r"C:\Users\user\Desktop\loss_1.png",
    dpi=300,
    bbox_inches="tight"
)
plt.show()













# 用於test data ----
# 用最佳模型對 test_data 進行預測
predicted_probabilities = best_model.predict_proba(
    test_data
)[:, 1]

# Predict class
predicted_classes = np.where(
    predicted_probabilities >= 0.5,
    1,
    0
)

test_data["Will_Buy_EV"] = predicted_classes



# 變數轉回類別
for col in str_cols:
    start = time.time()
    test_data[col] = encoders[f"{col}_encoder"].inverse_transform(test_data[col])
    print(col, round(time.time() - start, 3), "秒")


submission = pd.DataFrame({
    'id': test_data['id'],
    'Will_Buy_EV': predicted_probabilities
})


# 存檔
submission.to_csv(
    r"C:\Users\user\Desktop\test_data.csv",
    index=False,
    encoding="utf-8"
)

Reference

Paper
Data

Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
使用 Hugo 建立
主題 Stack 由 Jimmy 設計