Monday, May 14, 2018

Make a ROC plot with possible cutoff points


roc.curve <- function(response, predicted, cutoff = c(seq(0.1, 0.9, 0.1), 0.45, 0.55), ...) {
    ## Purpose: Make a ROC plot with possible cutoff points.
    ##          Require R package "ROCR"
    ## Arguments:
    ##    response: a vector of truth (0/FALSE/"negative" or 1/TRUE/"positive")
    ##    predicted: a vector of prediction (continuous);
    ##    cutoff: a list of values to be plotted on ROC curve.
    ##    ...: passed to "plot". 

    ## Return: a ROC plot.
    ## Author: Feiming Chen, Date: 14 May 2018, 15:01
    ## ________________________________________________

    require(ROCR)
    ans <- ROCR::prediction(predicted, response)
    ## ROC for Sensitivity vs. Specificity.
    plot((pp <- ROCR::performance(ans, "sens", "spec")), colorize=T,
         print.cutoffs.at=cutoff, text.adj=c(1.2, 1.2), text.cex=0.7, lwd=2,
         ...)
    grid(col="orange")

    ## Draw a "line of no-discrimination".
    ## Sens = P(X=+ | T=+), Spec = P(X=- | T=-),
    ## if X is independent of T, then Sens + Spec = P(X+)+P(X-) = 1, so the pair
    ## (Sens, Spec) lies on a off-diagonal line.
    abline(c(1, -1), col="gray70", lty=2)
    return(invisible(pp))
}
if (F) {
    roc.curve(rep(c(0,1), 50), runif(100), main = "ROC Curve Test")
}


No comments:

Post a Comment