Search code examples
pythonmachine-learningconfusion-matrix

Confusion_matrix according two indicators


y_true means correct target values;

Y_pred represents the probability value returned by the classifier to estimate the target

Please calculate the confusion matrix according to these two indicators.

y_true = [True,False,False,True]

y_pred = [0.15,0.97,0.24,0.88]

def func(y_true,y_pred,thresh):

I don't have a solution yet, anyone has a idea?


Solution

  • You can use confusion_matrix from sklearn.metrics. All you have to do is transform y_true and y_pred to binary values.

    from sklearn.metrics import confusion_matrix
    def conf_m(y_true, y_pred, thresh = 0.5):
        y_true = [int(i) for i in y_true]
        y_pred = [1 if x>=thresh else 0 for x in y_pred]
        cm = confusion_matrix(y_true, y_pred)
        return cm
    

    Without sklearn:

    import numpy as np
    def conf_m(y_true, y_pred, thresh = 0.5):
        y_true = [int(i) for i in y_true]
        y_pred = [1 if x>=thresh else 0 for x in y_pred]
        K = len(np.unique(y_true))
        cm = np.zeros((K, K))
    
        for i in range(len(y_true)):
            cm[y_true[i]][y_pred[i]] += 1
    
        return cm