roc_auc_score - y_true 中只有一个类 [英] roc_auc_score - Only one class present in y_true
问题描述
我正在对现有数据框进行 k 折 XV,我需要获得 AUC 分数.问题是——有时测试数据只包含 0,而不包含 1!
I am doing a k-fold XV on an existing dataframe, and I need to get the AUC score. The problem is - sometimes the test data only contains 0s, and not 1s!
我尝试使用 this 示例,但使用不同的数字:
I tried using this example, but with different numbers:
import numpy as np
from sklearn.metrics import roc_auc_score
y_true = np.array([0, 0, 0, 0])
y_scores = np.array([1, 0, 0, 0])
roc_auc_score(y_true, y_scores)
我得到这个例外:
ValueError:y_true 中只存在一个类.ROC AUC 分数不是在那种情况下定义.
ValueError: Only one class present in y_true. ROC AUC score is not defined in that case.
是否有任何解决方法可以使其在这种情况下工作?
Is there any workaround that can make it work in such cases?
推荐答案
您可以使用 try-except 来防止错误:
You could use try-except to prevent the error:
import numpy as np
from sklearn.metrics import roc_auc_score
y_true = np.array([0, 0, 0, 0])
y_scores = np.array([1, 0, 0, 0])
try:
roc_auc_score(y_true, y_scores)
except ValueError:
pass
现在,如果只有一个类,您还可以将 roc_auc_score
设置为零.不过,我不会这样做.我猜你的测试数据非常不平衡.我建议改用分层 K 折,这样您至少可以同时存在两个类.
Now you can also set the roc_auc_score
to be zero if there is only one class present. However, I wouldn't do this. I guess your test data is highly unbalanced. I would suggest to use stratified K-fold instead so that you at least have both classes present.
这篇关于roc_auc_score - y_true 中只有一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!