Bagging 的第一次嘗試
你已經看過在 bagging 集成中,單次迭代會發生什麼事。現在就來自己動手打造一個自訂的 bagging 模型!
以下已為你準備兩個函式:
def build_decision_tree(X_train, y_train, random_state=None):
# 以放回抽樣取得樣本,
# 建立一棵「弱」決策樹,
# 並對訓練集進行擬合
def predict_voting(classifiers, X_test):
# 先產生各模型的個別預測,
# 再用「Voting」方式彙整
嚴格來說,build_decision_tree() 就是你在前一個練習所做的事。在這裡,你會建立多棵類似的樹,然後把它們結合起來。來看看這個由「弱」模型組成的集成是否能提升效能吧!
本練習屬於課程
Python 的 Ensemble 方法
練習說明
- 透過呼叫
build_decision_tree()來建立各個模型,並傳入訓練集與索引i(作為 random state)。 - 使用
predict_voting()進行測試集標籤預測,輸入分類器清單clf_list與測試特徵X_test。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Build the list of individual models
clf_list = []
for i in range(21):
weak_dt = ____
clf_list.append(weak_dt)
# Predict on the test set
pred = ____
# Print the F1 score
print('F1 score: {:.3f}'.format(f1_score(y_test, pred)))