Debian Codegraph @

R/performance_measures.R

raw
1 ## ------------------------------------------------------------------------
2 ## classical machine learning contingency table measures
3 ## ------------------------------------------------------------------------
4
5 .performance.accuracy <-
6 function(predictions, labels, cutoffs, fp, tp, fn, tn,
7 n.pos, n.neg, n.pos.pred, n.neg.pred) {
8
9 list( cutoffs, (tn+tp) / length(predictions) )
10 }
11
12 .performance.error.rate <-
13 function(predictions, labels, cutoffs, fp, tp, fn, tn,
14 n.pos, n.neg, n.pos.pred, n.neg.pred) {
15
16 list( cutoffs, (fn+fp) / length(predictions) )
17 }
18
19 .performance.false.positive.rate <-
20 function(predictions, labels, cutoffs, fp, tp, fn, tn,
21 n.pos, n.neg, n.pos.pred, n.neg.pred) {
22
23 list( cutoffs, fp / n.neg )
24 }
25
26 .performance.true.positive.rate <-
27 function(predictions, labels, cutoffs, fp, tp, fn, tn,
28 n.pos, n.neg, n.pos.pred, n.neg.pred) {
29
30 list( cutoffs, tp / n.pos )
31 }
32
33 .performance.false.negative.rate <-
34 function(predictions, labels, cutoffs, fp, tp, fn, tn,
35 n.pos, n.neg, n.pos.pred, n.neg.pred) {
36
37 list( cutoffs, fn / n.pos )
38 }
39
40 .performance.true.negative.rate <-
41 function(predictions, labels, cutoffs, fp, tp, fn, tn,
42 n.pos, n.neg, n.pos.pred, n.neg.pred) {
43
44 list( cutoffs, tn / n.neg )
45 }
46
47 .performance.positive.predictive.value <-
48 function(predictions, labels, cutoffs, fp, tp, fn, tn,
49 n.pos, n.neg, n.pos.pred, n.neg.pred) {
50
51 ppv <- tp / (fp + tp)
52 list( cutoffs, ppv )
53 }
54
55 .performance.negative.predictive.value <-
56 function(predictions, labels, cutoffs, fp, tp, fn, tn,
57 n.pos, n.neg, n.pos.pred, n.neg.pred) {
58
59 npv <- tn / (tn + fn)
60 list( cutoffs, npv )
61 }
62
63 .performance.prediction.conditioned.fallout <-
64 function(predictions, labels, cutoffs, fp, tp, fn, tn,
65 n.pos, n.neg, n.pos.pred, n.neg.pred) {
66 ppv <- .performance.positive.predictive.value(predictions, labels,
67 cutoffs, fp, tp, fn, tn,
68 n.pos, n.neg, n.pos.pred,
69 n.neg.pred)[[2]]
70 list( cutoffs, 1 - ppv )
71 }
72
73 .performance.prediction.conditioned.miss <-
74 function(predictions, labels, cutoffs, fp, tp, fn, tn,
75 n.pos, n.neg, n.pos.pred, n.neg.pred) {
76 npv <- .performance.negative.predictive.value(predictions, labels,
77 cutoffs, fp, tp, fn, tn,
78 n.pos, n.neg, n.pos.pred,
79 n.neg.pred)[[2]]
80 list( cutoffs, 1 - npv )
81 }
82
83 ## ------------------------------------------------------------------------
84 ## ...not actually performance measures, but very useful as a second axis
85 ## against which to plot a "real" performance measure
86 ## (popular example: lift charts)
87 ## ------------------------------------------------------------------------
88
89 .performance.rate.of.positive.predictions <-
90 function(predictions, labels, cutoffs, fp, tp, fn, tn,
91 n.pos, n.neg, n.pos.pred, n.neg.pred) {
92
93 list( cutoffs, n.pos.pred / (n.pos + n.neg) )
94 }
95
96 .performance.rate.of.negative.predictions <-
97 function(predictions, labels, cutoffs, fp, tp, fn, tn,
98 n.pos, n.neg, n.pos.pred, n.neg.pred) {
99
100 list( cutoffs, n.neg.pred / (n.pos + n.neg) )
101 }
102
103
104 ## ------------------------------------------------------------------------
105 ## Classical statistical contingency table measures
106 ## ------------------------------------------------------------------------
107
108 .performance.phi <-
109 function(predictions, labels, cutoffs, fp, tp, fn, tn,
110 n.pos, n.neg, n.pos.pred, n.neg.pred) {
111
112 list(cutoffs,
113 (tn*tp - fn*fp) /
114 (sqrt(n.pos) * sqrt(n.neg) * sqrt(n.pos.pred) * sqrt(n.neg.pred))
115 )
116 }
117
118 .performance.mutual.information <-
119 function(predictions, labels, cutoffs, fp, tp, fn, tn,
120 n.pos, n.neg, n.pos.pred, n.neg.pred) {
121
122 n.samples <- n.pos + n.neg
123 mi <- c()
124 for (k in 1:length(cutoffs)) {
125 kij <- rbind( c(tn[k],fn[k]), c(fp[k],tp[k]) )
126
127 ki.j. <- rbind(c(n.neg * n.neg.pred[k], n.neg.pred[k] * n.pos),
128 c(n.neg * n.pos.pred[k], n.pos * n.pos.pred[k]))
129
130 log.matrix <- log2( kij / ki.j.)
131 log.matrix[kij/ki.j.==0] <- 0
132
133 mi <- c(mi, log2(n.samples) + sum( kij * log.matrix) / n.samples )
134 }
135
136 list( cutoffs, mi )
137 }
138
139 #' @importFrom stats chisq.test
140 .performance.chisq <-
141 function(predictions, labels, cutoffs, fp, tp, fn, tn,
142 n.pos, n.neg, n.pos.pred, n.neg.pred) {
143
144 chisq <- c()
145 for (i in 1:length(cutoffs)) {
146 A <- rbind( c( tn[i], fn[i]), c(fp[i], tp[i]) )
147 chisq <- c(chisq, stats::chisq.test(A, correct=FALSE)$statistic )
148 }
149 list( cutoffs, chisq )
150 }
151
152 .performance.odds.ratio <-
153 function(predictions, labels, cutoffs, fp, tp, fn, tn,
154 n.pos, n.neg, n.pos.pred, n.neg.pred) {
155
156
157 list( cutoffs, tp * tn / (fn * fp) )
158
159 }
160
161 ## ------------------------------------------------------------------------
162 ## Other measures based on contingency tables
163 ## ------------------------------------------------------------------------
164
165 .performance.lift <-
166 function(predictions, labels, cutoffs, fp, tp, fn, tn,
167 n.pos, n.neg, n.pos.pred, n.neg.pred) {
168
169 n.samples <- n.pos + n.neg
170 list( cutoffs, (tp / n.pos) / (n.pos.pred / n.samples) )
171 }
172
173 .performance.f <-
174 function(predictions, labels, cutoffs, fp, tp, fn, tn,
175 n.pos, n.neg, n.pos.pred, n.neg.pred, alpha) {
176
177 prec <- .performance.positive.predictive.value(predictions, labels,
178 cutoffs, fp, tp, fn, tn,
179 n.pos, n.neg, n.pos.pred,
180 n.neg.pred)[[2]]
181 list( cutoffs, 1/ ( alpha*(1/prec) + (1-alpha)*(1/(tp/n.pos)) ) )
182 }
183
184 #' @importFrom grDevices chull
185 .performance.rocconvexhull <-
186 function(predictions, labels, cutoffs, fp, tp, fn, tn,
187 n.pos, n.neg, n.pos.pred, n.neg.pred) {
188
189 x <- fp / n.neg
190 y <- tp / n.pos
191
192 finite.bool <- is.finite(x) & is.finite(y)
193 x <- x[ finite.bool ]
194 y <- y[ finite.bool ]
195 if (length(x) < 2) {
196 stop("Not enough distinct predictions to compute ROC convex hull.")
197 }
198
199 ## keep only points on the convex hull
200 ind <- grDevices::chull(x, y)
201 x.ch <- x[ind]
202 y.ch <- y[ind]
203
204 ## keep only convex hull points above the diagonal, except (0,0)
205 ## and (1,1)
206 ind.upper.triangle <- x.ch < y.ch
207 x.ch <- c(0, x.ch[ind.upper.triangle], 1)
208 y.ch <- c(0, y.ch[ind.upper.triangle], 1)
209
210 ## sort remaining points by ascending x value
211 ind <- order(x.ch)
212 x.ch <- x.ch[ind]
213 y.ch <- y.ch[ind]
214
215 list( x.ch, y.ch )
216 }
217
218 ## ----------------------------------------------------------------------------
219 ## Cutoff-independent measures
220 ## ----------------------------------------------------------------------------
221
222 #' @importFrom stats approxfun
223 .performance.auc <-
224 function(predictions, labels, cutoffs, fp, tp, fn, tn,
225 n.pos, n.neg, n.pos.pred, n.neg.pred, fpr.stop) {
226
227 x <- fp / n.neg
228 y <- tp / n.pos
229
230 finite.bool <- is.finite(x) & is.finite(y)
231 x <- x[ finite.bool ]
232 y <- y[ finite.bool ]
233 if (length(x) < 2) {
234 stop(paste("Not enough distinct predictions to compute area",
235 "under the ROC curve."))
236 }
237
238 if (fpr.stop < 1) {
239 ind <- max(which( x <= fpr.stop ))
240 tpr.stop <- stats::approxfun( x[ind:(ind+1)], y[ind:(ind+1)] )(fpr.stop)
241 x <- c(x[1:ind], fpr.stop)
242 y <- c(y[1:ind], tpr.stop)
243 }
244
245 ans <- list()
246 auc <- 0
247 for (i in 2:length(x)) {
248 auc <- auc + 0.5 * (x[i] - x[i-1]) * (y[i] + y[i-1])
249 }
250 ans <- list( c(), auc)
251 names(ans) <- c("x.values","y.values")
252 return(ans)
253 }
254
255 # written by Thomas Unterthiner ([email protected])
256 .performance.aucpr <-
257 function(predictions, labels, cutoffs, fp, tp, fn, tn,
258 n.pos, n.neg, n.pos.pred, n.neg.pred) {
259
260
261 tmp <- aggregate(list(fp=fp), by=list(tp=tp), min)
262 tp <- tmp$tp
263 fp <- tmp$fp
264 prec <- tp / (fp + tp)
265 rec <- tp / n.pos
266 if (fp[1] == 0 & tp[1] == 0) {
267 prec[1] = 1
268 }
269
270 finite.bool <- is.finite(prec) & is.finite(rec)
271 prec <- prec[ finite.bool ]
272 rec <- rec[ finite.bool ]
273 if (length(rec) < 2) {
274 stop(paste("Not enough distinct predictions to compute area",
275 "under the Precision/Recall curve."))
276 }
277
278 # if two points are too distant from each other, we need to
279 # correctly interpolate between them. This is done according to
280 # Davis & Goadrich,
281 #"The Relationship Between Precision-Recall and ROC Curves", ICML'06
282 for (i in seq_along(rec[-length(rec)])) {
283 if (tp[i+1] - tp[i] > 2) {
284 skew = (fp[i+1]-fp[i]) / (tp[i+1]-tp[i])
285 x = seq(1, tp[i+1]-tp[i], by=1)
286 rec <- append(rec, (x+tp[i])/n.pos, after=i)
287 prec <- append(prec, (x+tp[i])/(tp[i]+fp[i]+x+ skew*x), after=i)
288 }
289 }
290
291 auc <- 0
292 for (i in seq.int(from = 2, to = length(rec))) {
293 auc <- auc + 0.5 * (rec[i] - rec[i-1]) * (prec[i] + prec[i-1])
294 }
295
296 ans <- list( c(), auc)
297 names(ans) <- c("x.values","y.values")
298 return(ans)
299 }
300
301 #' @importFrom stats uniroot approxfun
302 .performance.precision.recall.break.even.point <-
303 function(predictions, labels, cutoffs, fp, tp, fn, tn,
304 n.pos, n.neg, n.pos.pred, n.neg.pred) {
305
306 pred <- prediction( predictions, labels)
307 perf <- performance( pred, measure="prec", x.measure="rec")
308 x <- rev([email protected][[1]])
309 y <- rev([email protected][[1]])
310 alpha <- rev([email protected][[1]])
311
312 finite.bool <- is.finite(alpha) & is.finite(x) & is.finite(y)
313 x <- x[ finite.bool ]
314 y <- y[ finite.bool ]
315 alpha <- alpha[ finite.bool ]
316
317 if (length(x) < 2) {
318 stop(paste("Not enough distinct predictions to compute",
319 "precision/recall intersections."))
320 }
321 intersection.cutoff <- c()
322 intersection.pr <- c()
323
324 ## find all intersection points by looking at all intervals (i,i+1):
325 ## if the difference function between x and y has different signs at the
326 ## interval boundaries, then an intersection point is in the interval;
327 ## compute as the root of the difference function
328 if ( (x[1]-y[1]) == 0) {
329 intersection.cutoff <- c( alpha[1] )
330 intersection.pr <- c( x[1] )
331 }
332
333 for (i in (1:(length(alpha)-1))) {
334 if ((x[i+1]-y[i+1]) == 0) {
335 intersection.cutoff <- c( intersection.cutoff, alpha[i+1] )
336 intersection.pr <- c( intersection.pr, x[i+1] )
337 } else if ((x[i]-y[i])*(x[i+1]-y[i+1]) < 0 ) {
338 ans <- stats::uniroot(stats::approxfun(c(alpha[i], alpha[i+1] ),
339 c(x[i]-y[i], x[i+1]-y[i+1])),
340 c(alpha[i],alpha[i+1]))
341 intersection.cutoff <- c(intersection.cutoff, ans$root)
342 intersection.pr <- c(intersection.pr, ans$f.root)
343 }
344 }
345
346 list( rev(intersection.cutoff), rev(intersection.pr) )
347 }
348
349 #' @importFrom stats median
350 .performance.calibration.error <-
351 function(predictions, labels, cutoffs, fp, tp, fn, tn,
352 n.pos, n.neg, n.pos.pred, n.neg.pred, window.size) {
353
354 if (window.size > length(predictions)) {
355 stop("Window size exceeds number of predictions.")
356 }
357 if (min(predictions)<0 || max(predictions)>1) {
358 stop("Calibration error needs predictions between 0 and 1")
359 }
360
361 pos.label <- levels(labels)[2]
362 neg.label <- levels(labels)[1]
363
364 ordering <- rev(order( predictions ))
365 predictions <- predictions[ ordering ]
366 labels <- labels[ ordering ]
367
368 median.cutoffs <- c()
369 calibration.errors <- c()
370
371 for (left.index in 1 : (length(predictions) - window.size+1) ) {
372 right.index <- left.index + window.size - 1
373 pos.fraction <-
374 sum(labels[left.index : right.index] == pos.label) / window.size
375 mean.prediction <- mean( predictions[ left.index : right.index ] )
376
377 calibration.errors <- c(calibration.errors,
378 abs(pos.fraction - mean.prediction))
379 median.cutoffs <- c(median.cutoffs,
380 stats::median(predictions[left.index:right.index]))
381 }
382 list( median.cutoffs, calibration.errors )
383 }
384
385
386 .performance.mean.cross.entropy <-
387 function(predictions, labels, cutoffs, fp, tp, fn, tn,
388 n.pos, n.neg, n.pos.pred, n.neg.pred) {
389
390 if (! all(levels(labels)==c(0,1)) ||
391 any(predictions<0) || any(predictions>1) ) {
392 stop(paste("Class labels need to be 0 and 1 and predictions between",
393 "0 and 1 for mean cross entropy."))
394 }
395
396 pos.label <- levels(labels)[2]
397 neg.label <- levels(labels)[1]
398
399 list( c(), - 1/length(predictions) *
400 (sum( log( predictions[which(labels==pos.label)] )) +
401 sum( log( 1 - predictions[which(labels==neg.label)] ))) )
402 }
403
404
405 .performance.root.mean.squared.error <-
406 function(predictions, labels, cutoffs, fp, tp, fn, tn,
407 n.pos, n.neg, n.pos.pred, n.neg.pred) {
408 ## convert labels from factor to numeric values
409 labels <- as.numeric(levels(labels))[labels]
410 if (any(is.na(labels))) {
411 stop("For rmse predictions have to be numeric.")
412 }
413 list( c(), sqrt( 1/length(predictions) *
414 sum( (predictions - labels)^2 )) )
415 }
416
417 ## ----------------------------------------------------------------------------
418 ## Derived measures:
419 ## ----------------------------------------------------------------------------
420
421 .performance.sar <- function( predictions, labels, cutoffs, fp, tp, fn, tn,
422 n.pos, n.neg, n.pos.pred, n.neg.pred) {
423
424 pred <- prediction( predictions, labels)
425 perf.acc <- performance( pred, measure="acc")
426 perf.rmse <- performance( pred, measure="rmse")
427 perf.auc <- performance( pred, measure="auc")
428
429 list(cutoffs,
430 1/3 * ([email protected][[1]] +
431 (1 - [email protected][[1]]) +
432 [email protected][[1]]))
433 }
434
435 ## ----------------------------------------------------------------------------
436 ## Measures taking into account actual cost considerations
437 ## ----------------------------------------------------------------------------
438
439 .performance.expected.cost <-
440 function(predictions, labels, cutoffs, fp, tp, fn, tn,
441 n.pos, n.neg, n.pos.pred, n.neg.pred) {
442
443 ## kick out suboptimal values (i.e. fpr/tpr pair for which another one
444 ## with same fpr and higher tpr exists,
445 ## or one for which one with same tpr but lower fpr exists
446
447 if (n.neg==0 || n.pos==0) {
448 stop(paste("At least one positive and one negative sample are",
449 "needed to compute a cost curve."))
450 }
451 fpr <- fp / n.neg
452 tpr <- tp / n.pos
453
454 ## sort by fpr (ascending), in case of ties by descending tpr
455 ind <- order(fpr,-tpr)
456
457 fpr <- fpr[ind]
458 tpr <- tpr[ind]
459 ## for tied fprs, only the one with the highest tpr is kept
460 ind <- !duplicated(fpr)
461 fpr <- fpr[ind]
462 tpr <- tpr[ind]
463
464 ## for tied tprs, only keep the one with the lowest fpr
465 ind <- order(-tpr,fpr)
466 fpr <- fpr[ind]
467 tpr <- tpr[ind]
468 ind <- !duplicated(tpr)
469 fpr <- fpr[ind]
470 tpr <- tpr[ind]
471
472 if (!any(0==fpr & 0==tpr)) {
473 fpr <- c(0,fpr)
474 tpr <- c(0,tpr)
475 }
476 if (!any(1==fpr & 1==tpr)) {
477 fpr <- c(fpr,1)
478 tpr <- c(tpr,1)
479 }
480
481 ## compute all functions
482 f <- list()
483 for (i in 1:length(fpr)) {
484 f <- c(f, .construct.linefunct( 0, fpr[i], 1, 1-tpr[i] ))
485 }
486
487 ## compute all intersection points
488 x.values <- c()
489 y.values <- c()
490 for (i in 1:(length(fpr)-1)) {
491 for (j in (i+1):length(fpr)) {
492 ans <- .intersection.point( f[[i]], f[[j]] )
493 if (all(is.finite(ans))) {
494 y.values.at.current.x <- c()
495 for (k in 1:length(f)) {
496 y.values.at.current.x <- c(y.values.at.current.x,
497 f[[k]](ans[1]))
498 }
499 if (abs(ans[2] - min(y.values.at.current.x )) <
500 sqrt(.Machine$double.eps)) {
501
502 x.values <- c(x.values, ans[1])
503 y.values <- c(y.values, ans[2])
504 }
505 }
506 }
507 }
508
509 if (!any(0==x.values & 0==y.values)) {
510 x.values <- c(0,x.values)
511 y.values <- c(0,y.values)
512 }
513 if (!any(1==x.values & 0==y.values)) {
514 x.values <- c(x.values,1)
515 y.values <- c(y.values,0)
516 }
517
518 ind <- order( x.values)
519 list( x.values[ind], y.values[ind] )
520 }
521
522
523 .performance.cost <-
524 function(predictions, labels, cutoffs, fp, tp, fn, tn,
525 n.pos, n.neg, n.pos.pred, n.neg.pred, cost.fp, cost.fn) {
526
527 n.samples <- n.pos + n.neg
528 cost <- ((n.pos / n.samples) * (fn / n.pos) * cost.fn +
529 (n.neg / n.samples) * (fp / n.neg) * cost.fp)
530 list( cutoffs, cost )
531 }