简体   繁体   English

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

[英]To compute Confusion matrix without using sklearn

We have data frame which contains actual value and prediction value, we have to compute confusion matrix.我们有包含实际值和预测值的数据框,我们必须计算混淆矩阵。

Here is the code for it-这是它的代码-

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)

But i am getting following error:但我收到以下错误:

---------------------------------------------------------------------------
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

There is a problem with your input arrays, because:您的输入 arrays 有问题,因为:

    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)

will print:将打印:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM