模型調整
要調整隨機森林模型以應對高度不平衡的詐欺資料,一個簡單的方法是在建立 sklearn 模型時使用 class_weights 選項。不過,你也會看到這是一種較粗略的手段,在你的特殊情境下可能未必有效。
在這個練習中,你會以先前練習的 Random Forest 模型,探索 weight = "balanced_subsample" 模式。你已經將資料分成訓練集與測試集,也就是 X_train、X_test、y_train、y_test 已可使用。評估指標的函式也已匯入。
本練習屬於課程
Fraud Detection in Python
練習說明
- 將分類器的
class_weight參數設為balanced_subsample。 - 將模型擬合到訓練集。
- 從
X_test取得預測與機率。 - 計算
roc_auc_score、分類報告與混淆矩陣。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Define the model with balanced subsample
model = RandomForestClassifier(class_weight='____', random_state=5)
# Fit your training model to your training set
model.fit(____, ____)
# Obtain the predicted values and probabilities from the model
predicted = ____.____(____)
probs = ____.____(____)
# Print the roc_auc_score, the classification report and confusion matrix
print(____(____, ____))
print(____(____, ____))
print(____(____, ____))