如何在sklearn的randomforest中获得决策函数

EmJ*_*EmJ 5 python machine-learning random-forest scikit-learn grid-search

我使用下面的代码,以获得优化的参数randomforest使用gridsearchcv

x_train, x_test, y_train, y_test = train_test_split(X, y, random_state=0)
rfc = RandomForestClassifier(random_state=42, class_weight = 'balanced')
param_grid = { 
    'n_estimators': [200, 500],
    'max_features': ['auto', 'sqrt', 'log2'],
    'max_depth' : [4,5,6,7,8],
    'criterion' :['gini', 'entropy']
}
k_fold = StratifiedKFold(n_splits=10, shuffle=True, random_state=0)
CV_rfc = GridSearchCV(estimator=rfc, param_grid=param_grid, cv= 10, scoring = 'roc_auc')
CV_rfc.fit(x_train, y_train)
print(CV_rfc.best_params_)
print(CV_rfc.best_score_)
Run Code Online (Sandbox Code Playgroud)

现在,我想将调整后的参数应用于X_test. 为此,我做了以下工作,

pred = CV_rfc.decision_function(x_test)
print(roc_auc_score(y_test, pred))
Run Code Online (Sandbox Code Playgroud)

但是,decision_function似乎不支持,randomforest因为我收到以下错误。

AttributeError: 'RandomForestClassifier' 对象没有属性 'decision_function'。

有没有其他方法可以做到这一点?

如果需要,我很乐意提供更多详细信息。

Ven*_*lam 7

如果您的目的是获得模型评分函数以便评分可以用于 auc_roc_score,那么您可以去predict_proba()

y_pred_proba = CV_rfc.predict_proba(x_test)
print(roc_auc_score(y_test, y_pred_proba[:,1]))
Run Code Online (Sandbox Code Playgroud)