/
plot_roc.R
28 lines (22 loc) · 1.24 KB
/
plot_roc.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
plot_roc <- function(roc, threshold, cost_of_fp, cost_of_fn) {
library(gridExtra)
norm_vec <- function(v) (v - min(v))/diff(range(v))
idx_threshold = which.min(abs(roc$threshold-threshold))
col_ramp <- colorRampPalette(c("green","orange","red","black"))(100)
col_by_cost <- col_ramp[ceiling(norm_vec(roc$cost)*99)+1]
p_roc <- ggplot(roc, aes(fpr,tpr)) +
geom_line(color=rgb(0,0,1,alpha=0.3)) +
geom_point(color=col_by_cost, size=4, alpha=0.5) +
coord_fixed() +
geom_line(aes(threshold,threshold), color=rgb(0,0,1,alpha=0.5)) +
labs(title = sprintf("ROC")) + xlab("FPR") + ylab("TPR") +
geom_hline(yintercept=roc[idx_threshold,"tpr"], alpha=0.5, linetype="dashed") +
geom_vline(xintercept=roc[idx_threshold,"fpr"], alpha=0.5, linetype="dashed")
p_cost <- ggplot(roc, aes(threshold, cost)) +
geom_line(color=rgb(0,0,1,alpha=0.3)) +
geom_point(color=col_by_cost, size=4, alpha=0.5) +
labs(title = sprintf("cost function")) +
geom_vline(xintercept=threshold, alpha=0.5, linetype="dashed")
sub_title <- sprintf("threshold at %.2f - cost of FP = %d, cost of FN = %d", threshold, cost_of_fp, cost_of_fn)
grid.arrange(p_roc, p_cost, ncol=2, sub=textGrob(sub_title, gp=gpar(cex=1), just="bottom"))
}