以自助抽樣進行訓練
現在來建立一個「弱」的決策樹分類器,並在以「有放回」方式從訓練集抽出的樣本上進行訓練。這會幫助你理解 bagging 集成在每次迭代時會發生什麼事。
要進行抽樣,你將使用 pandas 的 .sample() 方法,其中包含 replace 參數。例如,以下這行程式碼會從整個資料框 df 進行「有放回」抽樣:
df.sample(frac=1.0, replace=True, random_state=42)
本練習屬於課程
Python 的 Ensemble 方法
練習說明
- 從整個(
frac=1.0)訓練集X_train進行「有放回」抽樣(replace=True)。 - 建立一個決策樹分類器,並設定參數
max_depth = 4。 - 將模型擬合到抽樣後的訓練資料。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Take a sample with replacement
X_train_sample = X_train.____(____, ____, random_state=42)
y_train_sample = y_train.loc[X_train_sample.index]
# Build a "weak" Decision Tree classifier
clf = ____(____, random_state=500)
# Fit the model to the training sample
____