Last active
August 29, 2015 14:06
-
-
Save abhik1368/f2f7574785296c2f0e59 to your computer and use it in GitHub Desktop.
Function to calculate AUC
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
# x = a vector for scores | |
# y = a vector of labels | |
function (x, y, decreasing = TRUE, top = 1) | |
{ | |
if (length(x) != length(y)) { | |
stop(paste("Length of scores does not match with labels.")) | |
} | |
N <- length(y) | |
n <- sum(y == 1) | |
x_p <- -Inf | |
area <- 0 | |
fp = tp = fp_p = tp_p = 0 | |
ord <- order(x, decreasing = decreasing) | |
for (i in seq_along(ord)) { | |
j <- ord[i] | |
if (x[j] != x_p) { | |
if (fp >= (N - n) * top) { | |
rat <- ((N - n) * top - fp_p)/(fp - fp_p) | |
area <- area + rat * (fp - fp_p) * (tp + tp_p)/2 | |
return(area/(n * (N - n) * top)) | |
} | |
area <- area + (fp - fp_p) * (tp + tp_p)/2 | |
x_p <- x[j] | |
fp_p <- fp | |
tp_p <- tp | |
} | |
if (y[j] == 1) { | |
tp <- tp + 1 | |
} | |
else { | |
fp <- fp + 1 | |
} | |
} | |
area <- area + (fp - fp_p) * (tp + tp_p)/2 | |
return(area/(n * (N - n))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment