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?
CodePudding user response:
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
CodePudding user response:
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)
TP, FP, TN, FN = 0, 0, 0, 0
for i in range(len(y_true)):
if y_true[i] == 1 and y_pred[i] == 1:
TP = 1
if y_true[i] == 0 and y_pred[i] == 1:
FP = 1
if y_true[i] == 0 and y_pred[i] == 0:
TN = 1
if y_true[i] == 1 and y_pred[i] == 0:
FN = 1
return TP, FP, TN, FN