1. Code
import numpy as np
def perf_metrics_2X2(yobs, yhat):
"""
Returns the specificity, sensitivity, positive predictive value, and negeative predictive value
of a 2X2 table.
where:
0 = negative case
1 = positive case
Parameters
----------
yobs : array of positive and negative ``observed`` cases
yhat : array of positive and negative ``predicted`` cases
Returns
-------
sensitivity = TP / (TP+FN)
specificity = TN / (TN+FP)
pos_pred_val = TP/ (TP+FP)
neg_pred_val = TN/ (TN+FN)
Author: Julio Cardenas-Rodriguez
"""
TP = np.sum( yobs[yobs==1] == yhat[yobs==1] )
TN = np.sum( yobs[yobs==0] == yhat[yobs==0] )
FP = np.sum( yobs[yobs==1] == yhat[yobs==0] )
FN = np.sum( yobs[yobs==0] == yhat[yobs==1] )
sensitivity = TP / (TP+FN)
specificity = TN / (TN+FP)
pos_pred_val = TP/ (TP+FP)
neg_pred_val = TN/ (TN+FN)
return sensitivity, specificity, pos_pred_val, neg_pred_val
2. Test
import pandas as pd
y = np.array([0, 1, 1, 1, 0, 1, 0,0,1,0])
y_hat = np.array([1, 1, 0, 1, 0, 1,0, 1,1,0])
metrics = perf_metrics_2X2(y, y_hat)
print(pd.DataFrame( dict( Metric = ['Specificity', 'Sensitivity', 'PPV','NPV'],
Performance = np.round(metrics,3))))
Metric Performance
0 Specificity 0.800
1 Sensitivity 0.600
2 PPV 0.667
3 NPV 0.750
I am data scientist scientist, passionate about helping people using mathematics, programming and chemistry