How to write a confusion matrix in Python?

前端 未结 14 1961
太阳男子
太阳男子 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:39

    This function creates confusion matrices for any number of classes.

    def create_conf_matrix(expected, predicted, n_classes):
        m = [[0] * n_classes for i in range(n_classes)]
        for pred, exp in zip(predicted, expected):
            m[pred][exp] += 1
        return m
    
    def calc_accuracy(conf_matrix):
        t = sum(sum(l) for l in conf_matrix)
        return sum(conf_matrix[i][i] for i in range(len(conf_matrix))) / t
    

    In contrast to your function above, you have to extract the predicted classes before calling the function, based on your classification results, i.e. sth. like

    [1 if p < .5 else 2 for p in classifications]
    

提交回复
热议问题