首页 > 解决方案 > 分类报告 - 精度和 F 分数不明确

问题描述

我从 sklearn.metrics 导入了分类报告,当我输入我np.arrays的作为参数时,我收到以下错误:

/usr/local/lib/python3.6/dist-packages/sklearn/metrics/classification.py:1135:UndefinedMetricWarning:精度和 F 分数定义不明确,在没有预测样本的标签中设置为 0.0。'precision', 'predicted', average, warn_for) /usr/local/lib/python3.6/dist-packages/sklearn/metrics/classification.py:1137: UndefinedMetricWarning: Recall 和 F-score 定义不明确并且正在在没有真实样本的标签中设置为 0.0。'recall', 'true', 平均, warn_for)

这是代码:

svclassifier_polynomial = SVC(kernel = 'poly', degree = 7, C = 5)

svclassifier_polynomial.fit(X_train, y_train)
y_pred = svclassifier_polynomial.predict(X_test)


poly = classification_report(y_test, y_pred)

当我过去不使用 np.array 时它工作得很好,关于我如何纠正这个问题的任何想法?

标签: pythonmachine-learningscikit-learnclassification

解决方案


这不是错误,只是警告并非所有标签都包含在您的 中y_pred,即您的分类器中有些标签y_test永远不会预测。

这是一个简单的可重现示例:

from sklearn.metrics import precision_score, f1_score, classification_report

y_true = [0, 1, 2, 0, 1, 2] # 3-class problem
y_pred = [0, 0, 1, 0, 0, 1] # we never predict '2'

precision_score(y_true, y_pred, average='macro') 
[...] UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. 
  'precision', 'predicted', average, warn_for)
0.16666666666666666

precision_score(y_true, y_pred, average='micro') # no warning
0.3333333333333333

precision_score(y_true, y_pred, average=None) 
[...] UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. 
  'precision', 'predicted', average, warn_for)
array([0.5, 0. , 0. ])

产生完全相同的警告f1_score(未显示)。

实际上,这只会警告您,在 中classification_report,没有预测样本的标签的相应值(此处2)将设置为 0:

print(classification_report(y_true, y_pred))


              precision    recall  f1-score   support

           0       0.50      1.00      0.67         2
           1       0.00      0.00      0.00         2
           2       0.00      0.00      0.00         2

   micro avg       0.33      0.33      0.33         6
   macro avg       0.17      0.33      0.22         6
weighted avg       0.17      0.33      0.22         6

[...] UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 in labels with no predicted samples. 
  'precision', 'predicted', average, warn_for)

当我过去不使用 np.array 时,它工作得很好

非常值得怀疑,因为在上面的示例中,我使用了简单的 Python 列表,而不是 Numpy 数组......


推荐阅读