“AttributeError: type object ‘RocCurveDisplay‘ has no attribute ‘from_estimator‘ “.

Posted Data+Science+Insight

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了“AttributeError: type object ‘RocCurveDisplay‘ has no attribute ‘from_estimator‘ “.相关的知识,希望对你有一定的参考价值。

"AttributeError: type object 'RocCurveDisplay' has no attribute 'from_estimator' ".

目录

"AttributeError: type object 'RocCurveDisplay' has no attribute 'from_estimator' ".

问题:

解决:

完整错误:


问题:

使用sklearn中的RocCurveDisplay函数绘制交叉验证ROC曲线、发生错误。

import numpy as np

from sklearn import datasets

# Import some data to play with
iris = datasets.load_iris()
X = iris.data
y = iris.target
X, y = X[y != 2], y[y != 2]
n_samples, n_features = X.shape

# Add noisy features
random_state = np.random.RandomState(0)
X = np.c_[X, random_state.randn(n_samples, 200 * n_features)]



import matplotlib.pyplot as plt

from sklearn import svm
from sklearn.metrics import auc
from sklearn.metrics import RocCurveDisplay
from sklearn.model_selection import StratifiedKFold

# Run classifier with cross-validation and plot ROC curves
cv = StratifiedKFold(n_splits=6)
classifier = svm.SVC(kernel="linear", probability=True, random_state=random_state)

tprs = []
aucs = []
mean_fpr = np.linspace(0, 1, 100)

fig, ax = plt.subplots()
for i, (train, test) in enumerate(cv.split(X, y)):
    classifier.fit(X[train], y[train])
    viz = RocCurveDisplay.from_estimator(
        classifier,
        X[test],
        y[test],
        name="ROC fold ".format(i),
        alpha=0.3,
        lw=1,
        ax=ax,
    )
    interp_tpr = np.interp(mean_fpr, viz.fpr, viz.tpr)
    interp_tpr[0] = 0.0
    tprs.append(interp_tpr)
    aucs.append(viz.roc_auc)

ax.plot([0, 1], [0, 1], linestyle="--", lw=2, color="r", label="Chance", alpha=0.8)

mean_tpr = np.mean(tprs, axis=0)
mean_tpr[-1] = 1.0
mean_auc = auc(mean_fpr, mean_tpr)
std_auc = np.std(aucs)
ax.plot(
    mean_fpr,
    mean_tpr,
    color="b",
    label=r"Mean ROC (AUC = %0.2f $\\pm$ %0.2f)" % (mean_auc, std_auc),
    lw=2,
    alpha=0.8,
)

std_tpr = np.std(tprs, axis=0)
tprs_upper = np.minimum(mean_tpr + std_tpr, 1)
tprs_lower = np.maximum(mean_tpr - std_tpr, 0)
ax.fill_between(
    mean_fpr,
    tprs_lower,
    tprs_upper,
    color="grey",
    alpha=0.2,
    label=r"$\\pm$ 1 std. dev.",
)

ax.set(
    xlim=[-0.05, 1.05],
    ylim=[-0.05, 1.05],
    title="Receiver operating characteristic example",
)
ax.legend(loc="lower right")
plt.show()

解决:

版本更新一下、因为sklearn的版本低的缘故,需要升级。

scikit-learn 1.0之后才提供了from_estimator这些函数、类;

pip install --upgrade scikit-learn

完整错误:

"AttributeError: type object 'RocCurveDisplay' has no attribute 'from_from_estimator' ".

参考:python - Error message with sklearn function " 'RocCurveDisplay' has no attribute 'from_predictions' " - Stack Overflow

参考:Receiver Operating Characteristic (ROC) with cross validation — scikit-learn 1.1.2 documentation

以上是关于“AttributeError: type object ‘RocCurveDisplay‘ has no attribute ‘from_estimator‘ “.的主要内容,如果未能解决你的问题,请参考以下文章