Scikit-learn中ROC曲线错误:ValueError: y should be a 1d array

在使用Scikit-learn库绘制ROC曲线时,你可能会遇到 ValueError: y should be a 1d array, got an array of shape (30, 3) instead. 这样的错误信息。

错误原因:

这个错误通常发生在你将多分类问题的预测结果直接传递给 roc_curve 函数时。roc_curve 函数期望输入的 y_score 参数是一个一维数组,表示每个样本属于正类的概率或得分。

在使用 SVC 模型时,decision_function 方法返回的是一个二维数组,每一列对应一个类别的决策函数值。而 roc_curve 函数需要的是一维数组。

解决方案:

要解决这个问题,可以使用 predict_proba 方法来获取每个类别的概率,然后选择正例对应的概率作为 y_score

代码示例:

以下代码展示了如何修复这个错误:

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, recall_score, precision_score, roc_curve, roc_auc_score
import matplotlib.pyplot as plt

# 加载鸢尾花数据集
iris = load_iris()

# 划分数据集为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=42)

# 创建SVC模型并进行训练
model = SVC(probability=True)
model.fit(X_train, y_train)

# 在测试集上进行预测
y_pred = model.predict(X_test)

# 计算准确率、召回率、精确率
accuracy = accuracy_score(y_test, y_pred)
recall = recall_score(y_test, y_pred, average='weighted')
precision = precision_score(y_test, y_pred, average='weighted')
print('准确率:', accuracy)
print('召回率:', recall)
print('精确率:', precision)

# 计算ROC曲线和AUC值
y_prob = model.predict_proba(X_test)
y_prob_positive = y_prob[:, 2]  # 取正例的概率作为y_score
fpr, tpr, thresholds = roc_curve(y_test, y_prob_positive, pos_label=2)
roc_auc = roc_auc_score(y_test, y_prob_positive)
print('AUC值:', roc_auc)

# 绘制ROC曲线
plt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc)
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic')
plt.legend(loc='lower right')
plt.show()

修改说明:

  • 使用 predict_proba 方法获取每个类别的概率。
  • 选择正例对应的概率作为 y_score 传递给 roc_curve 函数。

通过以上修改,你就可以解决 ValueError: y should be a 1d array 错误,并成功绘制ROC曲线了。

Scikit-learn中ROC曲线错误:ValueError: y should be a 1d array

原文地址: https://www.cveoy.top/t/topic/6Um 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录