calculate precision and recall in a confusion matrix

后端 未结 4 922
孤街浪徒
孤街浪徒 2021-01-05 13:48

Suppose I have a confusion matrix as like as below. How can I calculate precision and recall?

4条回答
  •  没有蜡笔的小新
    2021-01-05 14:13

    first, your matrix is arranged upside down. You want to arrange your labels so that true positives are set on the diagonal [(0,0),(1,1),(2,2)] this is the arrangement that you're going to find with confusion matrices generated from sklearn and other packages.

    Once we have things sorted in the right direction, we can take a page from this answer and say that:

    1. True Positives are on the diagonal position
    2. False positives are column-wise sums. Without the diagonal
    3. False negatives are row-wise sums. Without the diagonal.

    \ Then we take some formulas from sklearn docs for precision and recall. And put it all into code:

    import numpy as np
    cm = np.array([[2,1,0], [3,4,5], [6,7,8]])
    true_pos = np.diag(cm)
    false_pos = np.sum(cm, axis=0) - true_pos
    false_neg = np.sum(cm, axis=1) - true_pos
    
    precision = np.sum(true_pos / (true_pos + false_pos))
    recall = np.sum(true_pos / (true_pos + false_neg))
    

    Since we remove the true positives to define false_positives/negatives only to add them back... we can simplify further by skipping a couple of steps:

     true_pos = np.diag(cm) 
     precision = np.sum(true_pos / np.sum(cm, axis=0))
     recall = np.sum(true_pos / np.sum(cm, axis=1))
    

提交回复
热议问题