調整 bagging 的超參數
雖然你可以直接用預設參數建立一個 bagging 分類器,但強烈建議你調整參數,才能得到更佳的效能。理想情況下,應該使用 K 折交叉驗證來最佳化這些參數。
在這個練習中,讓我們嘗試透過修改 bagging 分類器的參數,看看能否提升模型效能。
另外,我們在 LogisticRegression 中傳入參數 solver='liblinear',以降低計算時間。
本練習屬於課程
Python 的 Ensemble 方法
練習說明
- 以羅吉斯迴歸作為基礎分類器,建立一個 bagging 分類器,並設定
20個基礎估計器、10個最大特徵、0.65(65%)的最大樣本數(max_samples),且採用「不放回」的抽樣方式。 - 使用
clf_bag對測試集X_test預測標籤。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Build a balanced logistic regression
clf_base = LogisticRegression(class_weight='balanced', solver='liblinear', random_state=42)
# Build and fit a bagging classifier with custom parameters
clf_bag = ____(____, ____, ____, ____, ____, random_state=500)
clf_bag.fit(X_train, y_train)
# Calculate predictions and evaluate the accuracy on the test set
y_pred = ____
print('Accuracy: {:.2f}'.format(accuracy_score(y_test, y_pred)))
# Print the classification report
print(classification_report(y_test, y_pred))