How to write a confusion matrix in Python?

前端 未结 14 1936
太阳男子
太阳男子 2020-12-04 06:48

I wrote a confusion matrix calculation code in Python:

def conf_mat(prob_arr, input_arr):
        # confusion matrix
        conf_arr = [[0, 0], [0, 0]]

            


        
14条回答
  •  独厮守ぢ
    2020-12-04 07:33

    Only with numpy, we can do as follow considering efficiency:

    def confusion_matrix(pred, label, nc=None):
        assert pred.size == label.size
        if nc is None:
            nc = len(unique(label))
            logging.debug("Number of classes assumed to be {}".format(nc))
    
        confusion = np.zeros([nc, nc])
        # avoid the confusion with `0`
        tran_pred = pred + 1
        for i in xrange(nc):    # current class
            mask = (label == i)
            masked_pred = mask * tran_pred
            cls, counts = unique(masked_pred, return_counts=True)
            # discard the first item
            cls = [cl - 1 for cl in cls][1:]
            counts = counts[1:]
            for cl, count in zip(cls, counts):
                confusion[i, cl] = count
        return confusion
    

    For other features such as plot, mean-IoU, see my repositories.

提交回复
热议问题