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

时间:2019-11-18 19:13:19

标签: python confusion-matrix

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

这是它的代码-

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

1 个答案:

答案 0 :(得分:0)

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

    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.]])