sklearn 如何计算随机森林的 AUC 以及为什么使用不同函数时会有所不同?

问题描述 投票:0回答:1

我从使用可视化 API 的 ROC 曲线给出的示例开始:

import matplotlib.pyplot as plt
from sklearn.datasets import load_wine
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import RocCurveDisplay
from sklearn.model_selection import train_test_split

X, y = load_wine(return_X_y=True)
y = y == 2

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)

rfc = RandomForestClassifier(n_estimators=10, random_state=42)
rfc.fit(X_train, y_train)
ax = plt.gca()
rfc_disp = RocCurveDisplay.from_estimator(rfc, X_test, y_test, ax=ax, alpha=0.8)
print(rfc_disp.roc_auc)

答案

0.9823232323232323

立即关注此内容

from sklearn.metrics import roc_auc_score
auc = roc_auc_score(y_test, rfc.predict(X_test))
print(auc)

我得到了

0.928030303030303
,这明显不同。

造成这种差异的原因是什么?我假设它与两个函数如何计算 AUC 有关(可能是平滑曲线的不同方式?)这给我带来了一个更普遍的问题:sklearn 中的随机森林如何获得 ROC 曲线? - 改变什么参数/阈值以获得不同的预测?这些只是森林中不同树木的分数吗?

python scikit-learn random-forest roc auc
1个回答
0
投票

您应该使用 predict_proba 来计算 AUC。

试试这个:

from sklearn.metrics import roc_auc_score
auc = roc_auc_score(y_test, rfc.predict_proba(X_test)[:, 1])
print(auc)
© www.soinside.com 2019 - 2024. All rights reserved.