在不使用 sklearn 的情况下计算混淆矩阵

To compute Confusion matrix without using sklearn

我们有包含实际值和预测值的数据框,我们必须计算混淆矩阵。

这是它的代码-

def compute_confusion_matrix(true, pred):


  K = len(np.unique(true)) # Number of classes 
  result = np.zeros((K, K))

  for i in range(len(true)):
    result[true[i]][pred[i]] += 1

  return result

actual = np.array(df1['y'])
predicted = np.array(df1['Class'])

result = compute_confusion_matrix(actual,predicted)

print(result)

但我收到以下错误:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-29-5795bf5f37e5> in <module>
     36 predicted = np.array(df1['Class'])
     37 
---> 38 result = compute_confusion_matrix(actual,predicted)
     39 
     40 print(result)

<ipython-input-29-5795bf5f37e5> in compute_confusion_matrix(true, pred)
     29 
     30   for i in range(len(true)):
---> 31     result[true[i]][pred[i]] += 1
     32 
     33   return result

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

您的输入数组有问题,因为:

    result=compute_confusion_matrix(np.array([0,0,1,0,1,1,0,1,1]),
    np.array([0,1,1,0,1,0,0,1,1]))
    print(result)

将打印:

    array([[3., 1.],
          [1., 4.]])