roc_auc_score在RandomForestClassifier的GridSearchCV与显式编码的RandomForestClassifier之间不同
为什么一个用特定参数训练出来的 RandomForestClassifier
的表现,和用 GridSearchCV
调整参数后的表现不一样呢?
def random_forest(X_train, y_train):
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import roc_auc_score, make_scorer
from sklearn.model_selection import train_test_split
X_train, X_validate, y_train, y_validate = train_test_split(X_train, y_train, random_state=0)
# various combinations of max depth and max features
max_depth_vals = [1,2,3]
max_features_vals = [2,3,4]
grid_values = {'max_depth': max_depth_vals, 'max_features': max_features_vals}
# build GridSearch
clf = RandomForestClassifier(n_estimators=10)
grid = GridSearchCV(clf, param_grid=grid_values, cv=3, scoring='roc_auc')
grid.fit(X_train, y_train)
y_hat_proba = grid.predict_proba(X_validate)
print('Train Grid best parameter (max. AUC): ', grid.best_params_)
print('Train Grid best score (AUC): ', grid.best_score_)
print('Validation set AUC: ', roc_auc_score(y_validate, y_hat_proba[:,1]))
# build RandomForest with hard coded values. AUC should be ballpark to grid search
clf = RandomForestClassifier(max_depth=3, max_features=4, n_estimators=10)
clf.fit(X_train, y_train)
y_hat = clf.predict(X_validate)
y_hat_prob = clf.predict_proba(X_validate)[:, 1]
auc = roc_auc_score(y_hat, y_hat_prob)
print("\nMax Depth: 3 Max Features: 4\n---------------------------------------------")
print("auc: {}".format(auc))
return
结果显示,网格搜索找到了最佳参数 max_depth=3
和 max_features=4
,并计算出一个 roc_auc_score
为 0.85
;但是当我用保留的验证集来测试时,得到的 roc_auc_score
是 0.84
。然而,当我直接用这些参数来编写分类器时,计算出的 roc_auc_score
却是 1.0
。我以为结果应该差不多在 0.85
左右,但感觉差得太远了。
Validation set AUC: 0.8490471073563559
Grid best parameter (max. AUC): {'max_depth': 3, 'max_features': 4}
Grid best score (AUC): 0.8599727094965482
Max Depth: 3 Max Features: 4
---------------------------------------------
auc: 1.0
我可能对某些概念理解错了,或者没有正确应用技术,甚至可能有编码方面的问题。谢谢。
1 个回答
1
这里有两个问题:
可变性
为了得到可重复的结果,尽量在可能的地方指定种子或随机状态,比如:
RandomForestClassifier(n_estimators=10, random_state=1234)
cv = StratifiedKFold(n_splits=3, random_state=1234)
GridSearchCV(clf, param_grid=grid_values, cv=cv, scoring='roc_auc')
ROC-AUC计算的参数
你使用了估计的标签,而不是实际的标签:
auc = roc_auc_score(y_hat, y_hat_prob)
请使用实际的标签:
auc = roc_auc_score(y_validate, y_hat_prob)