混淆矩阵的两种计算方法

import numpy as np

from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix


def fast_hist(label_pred, label_true, num_classes):
    mask = (label_true >= 0) & (label_true < num_classes)
    hist = np.bincount(
        num_classes * label_true[mask].astype(int) +
        label_pred[mask], minlength=num_classes ** 2).reshape(num_classes, num_classes)
    return hist


label_pred = np.array([np.arange(3, dtype='int32')] * 3)
label_true = np.array([np.ones(3, dtype='int32')] * 3)

# 第一种方式
num_classes = 3
hist = fast_hist(label_pred, label_true, num_classes)
print(hist)

# 第二种方式
label_pred = label_pred.reshape(1, -1)[0]
label_true = label_true.reshape(1, -1)[0]

print(classification_report(label_true, label_pred))
print(confusion_matrix(label_true, label_pred))
[[0 0 0]
 [3 3 3]
 [0 0 0]]
  'recall', 'true', average, warn_for)
              precision    recall  f1-score   support
           0       0.00      0.00      0.00         0
           1       1.00      0.33      0.50         9
           2       0.00      0.00      0.00         0
   micro avg       0.33      0.33      0.33         9
   macro avg       0.33      0.11      0.17         9
weighted avg       1.00      0.33      0.50         9
[[0 0 0]
 [3 3 3]
 [0 0 0]]

你可能感兴趣的:(小玩意儿)