首页 > 解决方案 > np.vectorize 只有大小为 1 的数组可以转换为标量

问题描述

我正在尝试打印评估我的贝叶斯模型的 ROC 曲线

fpr, tpr, _ =roc_curve(y_test, y_pred)

功能:

plt.plot(fpr, tpr, label='Naive Bayes (AUROC = %0.3f)' % y_pred)

plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.legend()  
plt.show()

我在绘制它时收到错误。以前的帖子建议使用 但我在我的和这里np.vectorize 尝试过:astype(int)fprtpr

x = fpr.astype(int)
y = tpr.astype(int)

它仍然没有帮助

这里有什么问题?这是 fpr,tpr 在调用之前的样子astype

在此处输入图像描述

标签: pythonmatplotlibscikit-learn

解决方案


使用fprandtpr你展示的值,plot工作得很好:

import numpy as np
from matplotlib import pyplot as plt

fpr = np.array([0, 0.136, 1.])
tpr = np.array([0, 0.5, 1.])

plt.plot(fpr, tpr)
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.show()

在此处输入图像描述

问题出现y_pred在它不属于的地方令人费解的存在,即在label论点中:

# dummy y_pred - exact values do not matter
y_pred = np.array([0.1, 0.34, 0.43, 0.89])

plt.plot(fpr, tpr, label='Naive Bayes (AUROC = %0.3f)' % y_pred)

结果(不足为奇):

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-8-ccbf0542501c> in <module>()
----> 1 plt.plot(fpr, tpr, label='Naive Bayes (AUROC = %0.3f)' % y_pred)

TypeError: only size-1 arrays can be converted to Python scalars

令人费解的是,为什么您尝试 y_pred在明确暗示您确实想要 AUC 分数的地方使用预测。

您应该单独计算 AUC,并在绘图的适当位置使用它,而不是y_pred

from sklearn.metrics import roc_auc_score
AUC = roc_auc_score(y_test, y_pred)
plt.plot(fpr, tpr, label='Naive Bayes (AUROC = %0.3f)' % AUC)

推荐阅读