【问题标题】:How to get decision function in randomforest in sklearn如何在sklearn的随机森林中获得决策函数
【发布时间】:2019-08-31 12:09:41
【问题描述】:

我正在使用以下代码使用gridsearchcv 获取randomforest 的优化参数。

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_)

现在,我想将调整后的参数应用到X_test。为此,我做了以下,

pred = CV_rfc.decision_function(x_test)
print(roc_auc_score(y_test, pred))

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

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

还有其他方法吗?

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

【问题讨论】:

  • 你不是在找CV_rfc.predict(x_test)吗?

标签: python machine-learning scikit-learn random-forest grid-search


【解决方案1】:

如果您的目的是获得模型评分功能,以便评分可用于auc_roc_score,那么您可以选择predict_proba()

y_pred_proba = CV_rfc.predict_proba(x_test)
print(roc_auc_score(y_test, y_pred_proba[:,1]))

【讨论】:

  • 如果您知道这个问题的答案,请告诉我:stackoverflow.com/questions/55609339/… 非常感谢 :)
  • 我们如何使用这个函数进行 GMM 聚类。
  • roc_auc_score 用于分类问题。聚类可以参考here
【解决方案2】:

您的代码,

pred = CV_rfc.decision_function(x_test)
print(roc_auc_score(y_test, pred))

让我觉得您正在尝试使用经过训练的模型进行预测。

如果你想得到预测标签,你可以这样做,

pred = CV_rfc.predict(x_test)

然后输出将是类标签,如[1, 2, 1, ... ]

如果你想获得类概率,你可以像这样使用predict_proba

pred = CV_rfc.predict_proba(x_test)

【讨论】:

    【解决方案3】:

    您可以使用 predict() 方法或使用 best_estimator_ 获得优化的随机森林模型

    【讨论】:

      猜你喜欢
      • 2017-03-15
      • 2018-02-19
      • 2018-06-11
      • 2019-10-13
      • 2021-03-24
      • 2016-07-23
      • 2021-12-25
      • 2019-03-14
      • 2019-04-11
      相关资源
      最近更新 更多