Created
June 13, 2017 10:51
-
-
Save wugh/5e803783e97166a0c878c6f64fa04a21 to your computer and use it in GitHub Desktop.
simple version of auc roc calculate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
''' | |
simple version of auc roc calculate | |
''' | |
import numpy as np | |
def area(x, y): | |
''' | |
reference: https://en.wikipedia.org/wiki/Trapezoidal_rule | |
print fpr | |
print tpr | |
''' | |
ret = 0 | |
for i in xrange(1, len(x)): | |
ret += (x[i] - x[i-1]) * ((y[i-1] + y[i]) / 2.0) | |
return ret | |
def roc_auc(y_true, y_score, pos_label): | |
''' | |
y_true: (n, ) | |
y_score: (n, ) | |
pos_label: label of postive class | |
''' | |
y_true = np.array(y_true) | |
y_score = np.array(y_score) | |
y_true = (y_true == pos_label) | |
# comput fpr and tpr | |
desc_index = np.argsort(y_score)[::-1] | |
y_score = y_score[desc_index] | |
y_true = y_true[desc_index] | |
# threshold is y_score[i] | |
# score <= y_score[i] compute true pos num (tps[i]) | |
# and false pos num (fps[i]) | |
tps = np.cumsum(y_true) | |
fps = 1 + np.arange(len(y_true)) - tps | |
fpr = fps/float(fps[-1]) | |
tpr = tps/float(tps[-1]) | |
# reorder fpr and tpr according to fpr increase | |
incr_index = np.argsort(fpr) | |
fpr = fpr[incr_index] | |
tpr = tpr[incr_index] | |
# calculate area under roc | |
return area(fpr, tpr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment