Debian Codegraph @

inst/doc/ROCR.Rmd

raw
1 ---
2 title: "ROCR: visualizing classifier performance in R"
3 output: rmarkdown::html_vignette
4 author: Tobias Sing, Oliver Sander, Niko Beerenwinkel, Thomas Lengauer
5 abstract:
6 ROCR is a package for evaluating and visualizing the performance of scoring
7 classifiers in the statistical language R. It features over 25 performance
8 measures that can be freely combined to create two-dimensional performance
9 curves. Standard methods for investigating trade-offs between specific
10 performance measures are available within a uniform framework, including
11 receiver operating characteristic (ROC) graphs, precision/recall plots, lift
12 charts and cost curves. ROCR integrates tightly with R's powerful graphics
13 capabilities, thus allowing for highly adjustable plots. Being equipped with
14 only three commands and reasonable default values for optional parameters,
15 ROCR combines flexibility with ease of usage.
16 vignette: >
17 %\VignetteIndexEntry{ROCR}
18 %\VignetteEngine{knitr::rmarkdown}
19 %\VignetteEncoding{UTF-8}
20 bibliography: references.bibtex
21 ---
22
23 ```{r, include = FALSE}
24 knitr::opts_chunk$set(
25 collapse = TRUE,
26 comment = "#>"
27 )
28 ```
29
30 # Introduction
31
32 ```{r setup}
33 library(ROCR)
34 ```
35
36 Pattern classification has become a central tool in bioinformatics, offering
37 rapid insights into large data sets [[@Baldi2001]](#References). While one area
38 of our work involves predicting phenotypic properties of HIV-1 from genotypic
39 information
40 [[@Beerenwinkel2002;@Beerenwinkel2003;@Sing04learningmixtures]](#References),
41 scoring or ranking predictors are also vital in a wide range of other biological
42 problems. Examples include microarray analysis (e.g. prediction of tissue
43 condition based on gene expression), protein structural and functional
44 characterization (remote homology detection, prediction of post-translational
45 modifications and molecular function annotation based on sequence or structural
46 motifs), genome annotation (gene finding and splice site identification),
47 protein–ligand interactions (virtual screening and molecular docking) and
48 structure–activity relationships (predicting bioavailability or toxicity of drug
49 compounds). In many of these cases, considerable class skew, class-specific
50 misclassification costs, and extensive noise due to variability in experimental
51 assays complicate predictive modelling. Thus, careful predictor validation is
52 compulsory.
53
54 ```{r, echo = FALSE, results = 'asis'}
55 table <- data.frame(group = c("Contingency ratios",
56 "Discrete covariation measures",
57 "Information retrieval measures",
58 "Performance in ROC space",
59 "Absolute scoring performance",
60 "Cost measures"),
61 measure = c("error rate, accuracy, sensitivity, specificity, true/false positive rate, fallout, miss, precision, recall, negative predictive value, prediction-conditioned fallout/miss.",
62 "Phi/Matthews correlation coefficient, mutual information, Chi-squared test statistic, odds ratio",
63 "F-measure, lift, precision-recall break-even point",
64 "ROC convex hull, area under the ROC curve",
65 "calibration error, mean cross-entropy, root mean-squared error",
66 "expected cost, explicit cost"))
67 knitr::kable(table,
68 caption = "***Table 1:**Performance measures in the ROCR package*",
69 col.names = c("",""),
70 align = "l")
71 ```
72
73 The real-valued output of scoring classifiers is turned into a binary class
74 decision by choosing a cutoff. As no cutoff is optimal according to all possible
75 performance criteria, cutoff choice involves a trade-off among different
76 measures. Typically, a trade-off between a pair of criteria (e.g. sensitivity
77 versus specificity) is visualized as a cutoff-parametrized curve in the plane
78 spanned by the two measures. Popular examples of such trade-off visualizations
79 include receiver operating characteristic (ROC) graphs, sensitivity/specificity
80 curves, lift charts and precision/recall plots. [@Fawcett2004](#References)
81 provides a general introduction into evaluating scoring classifiers with a focus
82 on ROC graphs.
83
84 Although functions for drawing ROC graphs are provided by the Bioconductor
85 project (https://www.bioconductor.org) or by the machine learning package Weka
86 (https://www.cs.waikato.ac.nz/ml), for example, no comprehensive evaluation suite
87 is available to date. ROCR is a flexible evaluation package for R
88 (https://www.r-project.org), a statistical language that is widely used in
89 biomedical data analysis. Our tool allows for creating cutoff-parametrized
90 performance curves by freely combining two out of more than 25 performance
91 measures (Table 1). Curves from different cross-validation or bootstrapping runs
92 can be averaged by various methods. Standard deviations, standard errors and box
93 plots are available to summarize the variability across the runs. The
94 parametrization can be visualized by printing cutoff values at the corresponding
95 curve positions, or by coloring the curve according to the cutoff. All
96 components of a performance plot are adjustable using a flexible mechanism for
97 dispatching optional arguments. Despite this flexibility, ROCR is easy to use,
98 with only three commands and reasonable default values for all optional
99 parameters.
100
101 In the example below, we will briefly introduce ROCR's three
102 commands—prediction, performance and plot—applied to a 10-fold cross-validation
103 set of predictions and corresponding class labels from a study on predicting HIV
104 coreceptor usage from the sequence of the viral envelope protein. After loading
105 the dataset, a prediction object is created from the raw predictions and class
106 labels.
107
108 ```{r}
109 data(ROCR.hiv)
110 predictions <- ROCR.hiv$hiv.svm$predictions
111 labels <- ROCR.hiv$hiv.svm$labels
112 pred <- prediction(predictions, labels)
113 pred
114 ```
115
116 Performance measures or combinations thereof are computed by invoking the
117 performance method on this prediction object. The resulting performance object
118 can be visualized using the method plot. For example, an ROC curve that trades
119 off the rate of true positives against the rate of false positives is obtained
120 as follows:
121
122 ```{r, fig.asp=1, fig.width=5, fig.align='center'}
123 perf <- performance(pred, "tpr", "fpr")
124 perf
125 plot(perf,
126 avg="threshold",
127 spread.estimate="boxplot")
128 ```
129
130 The optional parameter avg selects a particular form of performance curve
131 averaging across the validation runs; the visualization of curve variability is
132 determined with the parameter spread.estimate.
133
134 ```{r, echo=FALSE, results='asis', fig.asp=0.35, fig.width=7, fig.align='center',fig.cap="***Fig 1:** Visualizations of classifier performance (HIV coreceptor usage data): (a) receiver operating characteristic (ROC) curve; (b) peak accuracy across a range of cutoffs; (c) absolute difference between empirical and predicted rate of positives for windowed cutoff ranges, in order to evaluate how well the scores are calibrated as probability estimates. Owing to the probabilistic interpretation, cutoffs need to be in the interval [0,1], in contrast to other performance plots. (d) Score density estimates for the negative (solid) and positive (dotted) class.*"}
135 data(ROCR.hiv)
136 pp.unnorm <- ROCR.hiv$hiv.svm$predictions
137 ll <- ROCR.hiv$hiv.svm$labels
138
139 # normalize predictions to 0..1
140 v <- unlist(pp.unnorm)
141 pp <- lapply(pp.unnorm, function(run) {approxfun(c(min(v), max(v)), c(0,1))(run)})
142
143 par(mfrow=c(1,4))
144 pred<- prediction(pp, ll)
145 perf <- performance(pred, "tpr", "fpr")
146
147 plot(perf, avg= "threshold", colorize=TRUE, lwd= 3,
148 coloraxis.at=seq(0,1,by=0.2),)
149 plot(perf, col="gray78", add=TRUE)
150 plot(perf, avg= "threshold", colorize=TRUE, colorkey=FALSE,lwd= 3,,add=TRUE)
151 mtext(paste0("(a)"), side = 3, adj = 0.01,line = 1)
152
153 perf <- performance(pred, "acc")
154 plot(perf, avg= "vertical", spread.estimate="boxplot", lwd=3,col='blue',
155 show.spread.at= seq(0.1, 0.9, by=0.1),)
156 mtext(paste0("(b)"), side = 3, adj = 0.01,line = 1)
157
158
159 plot(performance(pred, "cal", window.size= 10),
160 avg="vertical",)
161 mtext(paste0("(c)"), side = 3, adj = 0.01,line = 1)
162
163 plot(0,0,type="n", xlim= c(0,1), ylim=c(0,7),
164 xlab="Cutoff", ylab="Density",)
165 mtext(paste0("(d)"), side = 3, adj = 0.01,line = 1)
166 for (runi in 1:length(pred@predictions)) {
167 lines(density(pred@predictions[[runi]][pred@labels[[runi]]=="-1"]), col= "red")
168 lines(density(pred@predictions[[runi]][pred@labels[[runi]]=="1"]), col="green")
169 }
170 ```
171
172 Issuing `demo(ROCR)` starts a demonstration of further graphical capabilities of
173 ROCR. The command `help(package=ROCR)` points to the available help pages. In
174 particular, a complete list of available performance measures can be obtained
175 via help(performance). A reference manual can be downloaded from the ROCR
176 website.
177
178 In conclusion, ROCR is a comprehensive tool for evaluating scoring classifiers
179 and producing publication-quality figures. It allows for studying the
180 intricacies inherent to many biological datasets and their implications on
181 classifier performance.
182
183 ## Additional examples
184
185 Below you can find many additional examples of ROCR's features of performance
186 measurement and the possibilites in plotting. However, this only a first
187 taste. For more examples, please run `demo(ROCR)` and make sure the plotting
188 deminsions are big enough.
189
190 ### ROC curves, Precision/Recall graphs and more ...
191
192 ```{r, fig.asp=1, fig.width=5, fig.align='center'}
193 perf <- performance(pred, "tpr", "fpr")
194 plot(perf,
195 avg= "threshold",
196 colorize=TRUE,
197 lwd= 3,
198 main= "With ROCR you can produce standard plots\nlike ROC curves ...")
199 plot(perf,
200 lty=3,
201 col="grey78",
202 add=TRUE)
203 ```
204
205
206 ```{r, fig.asp=1, fig.width=5, fig.align='center'}
207 perf <- performance(pred, "prec", "rec")
208 plot(perf,
209 avg= "threshold",
210 colorize=TRUE,
211 lwd= 3,
212 main= "... Precision/Recall graphs ...")
213 plot(perf,
214 lty=3,
215 col="grey78",
216 add=TRUE)
217 ```
218
219
220 ```{r, fig.asp=1, fig.width=5, fig.align='center'}
221 perf <- performance(pred, "sens", "spec")
222 plot(perf,
223 avg= "threshold",
224 colorize=TRUE,
225 lwd= 3,
226 main="... Sensitivity/Specificity plots ...")
227 plot(perf,
228 lty=3,
229 col="grey78",
230 add=TRUE)
231 ```
232
233
234 ```{r, fig.asp=1, fig.width=5, fig.align='center'}
235 perf <- performance(pred, "lift", "rpp")
236 plot(perf,
237 avg= "threshold",
238 colorize=TRUE,
239 lwd= 3,
240 main= "... and Lift charts.")
241 plot(perf,
242 lty=3,
243 col="grey78",
244 add=TRUE)
245 ```
246
247 ### Averaging over multiple predictions
248
249 Multiple batches of predictions can be analyzed at the same time.
250
251 ```{r}
252 data(ROCR.xval)
253 predictions <- ROCR.xval$predictions
254 labels <- ROCR.xval$labels
255 length(predictions)
256 ```
257
258 ```{r}
259 pred <- prediction(predictions, labels)
260 perf <- performance(pred,'tpr','fpr')
261 ```
262
263 This can be used for plotting averages using the `avg` argument.
264
265 ```{r, fig.asp=1, fig.width=5, fig.align='center'}
266 plot(perf,
267 colorize=TRUE,
268 lwd=2,
269 main='ROC curves from 10-fold cross-validation')
270 ```
271
272 ```{r, fig.asp=1, fig.width=5, fig.align='center'}
273 plot(perf,
274 avg='vertical',
275 spread.estimate='stderror',
276 lwd=3,main='Vertical averaging + 1 standard error',
277 col='blue')
278 ```
279
280 ```{r, fig.asp=1, fig.width=5, fig.align='center'}
281 plot(perf,
282 avg='horizontal',
283 spread.estimate='boxplot',
284 lwd=3,
285 main='Horizontal averaging + boxplots',
286 col='blue')
287 ```
288
289 ```{r, fig.asp=1, fig.width=5, fig.align='center'}
290 plot(perf,
291 avg='threshold',
292 spread.estimate='stddev',
293 lwd=2,
294 main='Threshold averaging + 1 standard deviation',
295 colorize=TRUE)
296 ```
297
298 ### Cutoff stacking
299
300 ```{r, fig.asp=1, fig.width=6, fig.align='center'}
301 plot(perf,
302 print.cutoffs.at=seq(0,1,by=0.2),
303 text.cex=0.8,
304 text.y=lapply(as.list(seq(0,0.5,by=0.05)), function(x) { rep(x,length([email protected][[1]])) } ),
305 col= as.list(terrain.colors(10)),
306 text.col= as.list(terrain.colors(10)),
307 points.col= as.list(terrain.colors(10)),
308 main= "Cutoff stability")
309 ```
310
311 ### Combination of performance measures
312
313 Performance measures can be combined freely.
314
315 ```{r}
316 perf <- performance(pred,"pcmiss","lift")
317 ```
318
319 ```{r, fig.asp=1, fig.width=5, fig.align='center'}
320 plot(perf,
321 colorize=TRUE,
322 print.cutoffs.at=seq(0,1,by=0.1),
323 text.adj=c(1.2,1.2),
324 avg="threshold",
325 lwd=3,
326 main= "You can freely combine performance measures ...")
327 ```
328
329
330 # Acknowledgement
331
332 Work at MPI supported by EU NoE BioSapiens (LSHG-CT-2003-503265).
333
334 <a name="References"></a>
335
336 # References