gpt4 book ai didi

scikit-learn - sklearn auc 值错误 : Only one class present in y_true

转载 作者:行者123 更新时间:2023-12-04 01:12:26 25 4
gpt4 key购买 nike

我搜索了谷歌,看到了一些关于这个错误的 StackOverflow 帖子。他们不是我的情况。

我使用 keras 来训练一个简单的神经网络,并对拆分的测试数据集进行一些预测。但是使用时roc_auc_score计算AUC,我收到以下错误:
"ValueError: Only one class present in y_true. ROC AUC score is not defined in that case." .

我检查了目标标签分布,它们非常不平衡。一些标签(总共 29 个标签中)只有 1 个实例。因此,他们很可能在测试标签中没有正标签实例。所以sklearn的roc_auc_score函数报告了唯一的一类问题。这是合理的。

但我很好奇,就像我使用 sklearn 的 cross_val_score 一样功能,它可以无误地处理AUC计算。

my_metric = 'roc_auc' 
scores = cross_validation.cross_val_score(myestimator, data,
labels, cv=5,scoring=my_metric)

我想知道 cross_val_score 中发生了什么,是不是因为 cross_val_score使用分层交叉验证数据拆分?

更新
继续挖,还是没找到后面的区别。看到cross_val_score调用 check_scoring(estimator, scoring=None, allow_none=False)返回一个得分手,以及 check_scoring将调用 get_scorer(scoring)这将返回 scorer=SCORERS[scoring]
SCORERS['roc_auc']roc_auc_scorerroc_auc_scorer是由
roc_auc_scorer = make_scorer(roc_auc_score, greater_is_better=True,
needs_threshold=True)

所以,它仍然使用 roc_auc_score 函数。我不明白为什么 cross_val_score 与直接调用 roc_auc_score 的行为不同。

最佳答案

我认为你的预感是正确的。 AUC(ROC 曲线下的面积)需要足够数量的任一类才能有意义。

默认情况下,cross_val_score分别计算性能指标一。另一种选择是做 cross_val_predict并计算所有折叠组合的 AUC。

你可以这样做:

from sklearn.metrics import roc_auc_score
from sklearn.cross_validation import cross_val_predict
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import make_classification


class ProbaEstimator(LogisticRegression):
"""
This little hack needed, because `cross_val_predict`
uses `estimator.predict(X)` internally.

Replace `LogisticRegression` with whatever classifier you like.

"""
def predict(self, X):
return super(self.__class__, self).predict_proba(X)[:, 1]


# some example data
X, y = make_classification()

# define your estimator
estimator = ProbaEstimator()

# get predictions
pred = cross_val_predict(estimator, X, y, cv=5)

# compute AUC score
roc_auc_score(y, pred)

关于scikit-learn - sklearn auc 值错误 : Only one class present in y_true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39018097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com