This code returns and plots the true positive rate, false positive rate, true positive count, false positive count based on predicted and true values :
def get_all_stats(y_true , y_pred) :
def perf_measure(y_true, y_pred):
TP = 0
FP = 0
TN = 0
FN = 0
for i in range(len(y_true)):
if y_true[i] == 1 and y_pred[i] == 1:
TP += 1
if y_pred[i]==1 and y_true[i]!=y_pred[i]:
FP += 1
if y_true[i]== 0 and y_pred[i]==0:
TN += 1
if y_pred[i]==0 and y_true[i] != y_pred[i]:
FN += 1
if(FP == 0) :
FPR = 0;
else :
FPR = FP / (FP + TN)
if(TP == 0) :
TPR = 0
else :
TPR = TP / (TP + FN)
return(TN , FPR, FN , TPR , TP , FP)
tn, fpr, fn, tpr, tp , fp = perf_measure(y_true, y_pred)
return tpr , fpr , tp , fp
tpr1 , fpr1 , tp1 , fp1 = get_all_stats(y_true=[1,1,1] , y_pred=[1,0,0])
tpr2 , fpr2 , tp2 , fp2 = get_all_stats(y_true=[1,0,1] , y_pred=[0,1,0])
tpr3 , fpr3 , tp3 , fp3 = get_all_stats(y_true=[0,0,0] , y_pred=[1,0,0])
plt.figure(figsize=(12,6))
plt.tick_params(labelsize=12)
print(tpr1 , fpr1 , tp1 , fp1)
print(tpr2 , fpr2 , tp2 , fp2)
print(tpr3 , fpr3 , tp3 , fp3)
plt.plot([fpr1,fpr2,fpr3], [tpr1 , tpr2, tpr3], color='blue', label='')
plt.ylabel("TPR",fontsize=16)
plt.xlabel("FPR",fontsize=16)
plt.legend()
The resultant ROC plot produced is :
In order to mimic three different false positive and true positive rates and different thresholds calculate these values by implementing the function get_all_stats three times with different
tpr1 , fpr1 , tp1 , fp1 = get_all_stats(y_true=[1,1,1] , y_pred=[1,0,0])
tpr2 , fpr2 , tp2 , fp2 = get_all_stats(y_true=[1,0,1] , y_pred=[0,1,0])
tpr3 , fpr3 , tp3 , fp3 = get_all_stats(y_true=[0,0,0] , y_pred=[1,0,0])
There are 9 instances to be classified to either 1 or 0 where the truth values are : [1,1,1,1,0,1,0,0,0]
At threshold1 the predicted values are [1,0,0] where the truth values at this threshold are [1,1,1].
At threshold2 the predicted values are [0,1,0] where the truth values at this threshold are [1,0,1].
At threshold3 the predicted values are [1,0,0] where the truth values at this threshold are [0,0,0].
As can see the generated plot of the classifier produced is different from 'typical' ROC curves :
As it first descends and then the false positive and true positive rates decrease causing the line to 'move back'. Have I implemented the ROC curve correctly ? Can the AUC be calculated for this curve ?




fpr4andtpr4are not computed in your code snippet. - Håkon T.