Debian Codegraph @

R/zzz.R

raw
1 #' @import methods
2 NULL
3
4 #' @name prediction-class
5 #' @aliases prediction-class
6 #'
7 #' @title Class \code{prediction}
8 #'
9 #' @description
10 #' Object to encapsulate numerical predictions together with the
11 #' corresponding true class labels, optionally collecting predictions and
12 #' labels for several cross-validation or bootstrapping runs.
13 #'
14 #' @section Objects from the Class:
15 #' Objects can be created by using the \code{prediction} function.
16 #'
17 #' @note
18 #' Every \code{prediction} object contains information about the 2x2
19 #' contingency table consisting of tp,tn,fp, and fn, along with the
20 #' marginal sums n.pos,n.neg,n.pos.pred,n.neg.pred, because these form
21 #' the basis for many derived performance measures.
22 #'
23 #' @slot predictions A list, in which each element is a vector of predictions
24 #' (the list has length > 1 for x-validation data.
25 #' @slot labels Analogously, a list in which each element is a vector of true
26 #' class labels.
27 #' @slot cutoffs A list in which each element is a vector of all necessary
28 #' cutoffs. Each cutoff vector consists of the predicted scores (duplicates
29 #' removed), in descending order.
30 #' @slot fp A list in which each element is a vector of the number (not the
31 #' rate!) of false positives induced by the cutoffs given in the corresponding
32 #' 'cutoffs' list entry.
33 #' @slot tp As fp, but for true positives.
34 #' @slot tn As fp, but for true negatives.
35 #' @slot fn As fp, but for false negatives.
36 #' @slot n.pos A list in which each element contains the number of positive
37 #' samples in the given x-validation run.
38 #' @slot n.neg As n.pos, but for negative samples.
39 #' @slot n.pos.pred A list in which each element is a vector of the number of
40 #' samples predicted as positive at the cutoffs given in the corresponding
41 #' 'cutoffs' entry.
42 #' @slot n.neg.pred As n.pos.pred, but for negatively predicted samples.
43 #'
44 #' @references
45 #' A detailed list of references can be found on the ROCR homepage at
46 #' \url{https://ipa-tys.github.io/ROCR/}.
47 #'
48 #' @author
49 #' Tobias Sing \email{[email protected]}, Oliver Sander
50 #' \email{[email protected]}
51 #'
52 #' @seealso
53 #' \code{\link{prediction}},
54 #' \code{\link{performance}},
55 #' \code{\link{performance-class}},
56 #' \code{\link{plot.performance}}
57 #'
58 #' @export
59 setClass("prediction",
60 representation(predictions = "list",
61 labels = "list",
62 cutoffs = "list",
63 fp = "list",
64 tp = "list",
65 tn = "list",
66 fn = "list",
67 n.pos = "list",
68 n.neg = "list",
69 n.pos.pred = "list",
70 n.neg.pred = "list"))
71
72 setMethod("show","prediction",
73 function(object){
74 cat("A ", class(object), " instance\n", sep = "")
75 if(length(object@predictions) > 1L){
76 cat(" with ", length(object@predictions)," cross ",
77 "validation runs ", sep = "")
78 if(length(unique(vapply(object@predictions,length,integer(1))))){
79 cat("(equal lengths)", sep = "")
80 } else {
81 cat("(different lengths)", sep = "")
82 }
83 } else {
84 cat(" with ", length(object@predictions[[1L]]),
85 " data points", sep = "")
86 }
87 })
88
89 #' @name performance-class
90 #' @aliases performance-class
91 #'
92 #' @title Class \code{performance}
93 #'
94 #' @description
95 #' Object to capture the result of a performance evaluation, optionally
96 #' collecting evaluations from several cross-validation or bootstrapping runs.
97 #'
98 #' @section Objects from the Class:
99 #' Objects can be created by using the \code{performance} function.
100 #'
101 #' @details
102 #' A \code{performance} object can capture information from four
103 #' different evaluation scenarios:
104 #' \itemize{
105 #' \item The behaviour of a cutoff-dependent performance measure across
106 #' the range of all cutoffs (e.g. \code{performance( predObj, 'acc' )} ). Here,
107 #' \code{x.values} contains the cutoffs, \code{y.values} the
108 #' corresponding values of the performance measure, and
109 #' \code{alpha.values} is empty.\cr
110 #' \item The trade-off between two performance measures across the
111 #' range of all cutoffs (e.g. \code{performance( predObj,
112 #' 'tpr', 'fpr' )} ). In this case, the cutoffs are stored in
113 #' \code{alpha.values}, while \code{x.values} and \code{y.values}
114 #' contain the corresponding values of the two performance measures.\cr
115 #' \item A performance measure that comes along with an obligatory
116 #' second axis (e.g. \code{performance( predObj, 'ecost' )} ). Here, the measure values are
117 #' stored in \code{y.values}, while the corresponding values of the
118 #' obligatory axis are stored in \code{x.values}, and \code{alpha.values}
119 #' is empty.\cr
120 #' \item A performance measure whose value is just a scalar
121 #' (e.g. \code{performance( predObj, 'auc' )} ). The value is then stored in
122 #' \code{y.values}, while \code{x.values} and \code{alpha.values} are
123 #' empty.
124 #' }
125 #'
126 #' @slot x.name Performance measure used for the x axis.
127 #' @slot y.name Performance measure used for the y axis.
128 #' @slot alpha.name Name of the unit that is used to create the parametrized
129 #' curve. Currently, curves can only be parametrized by cutoff, so
130 #' \code{alpha.name} is either \code{none} or \code{cutoff}.
131 #' @slot x.values A list in which each entry contains the x values of the curve
132 #' of this particular cross-validation run. \code{x.values[[i]]},
133 #' \code{y.values[[i]]}, and \code{alpha.values[[i]]} correspond to each
134 #' other.
135 #' @slot y.values A list in which each entry contains the y values of the curve
136 #' of this particular cross-validation run.
137 #' @slot alpha.values A list in which each entry contains the cutoff values of
138 #' the curve of this particular cross-validation run.
139 #'
140 #' @references
141 #' A detailed list of references can be found on the ROCR homepage at
142 #' \url{https://ipa-tys.github.io/ROCR/}.
143 #'
144 #' @author
145 #' Tobias Sing \email{[email protected]}, Oliver Sander
146 #' \email{[email protected]}
147 #'
148 #' @seealso
149 #' \code{\link{prediction}}
150 #' \code{\link{performance}},
151 #' \code{\link{prediction-class}},
152 #' \code{\link{plot.performance}}
153 #'
154 #' @export
155 setClass("performance",
156 representation(x.name = "character",
157 y.name = "character",
158 alpha.name = "character",
159 x.values = "list",
160 y.values = "list",
161 alpha.values = "list" ))
162
163 setMethod("show","performance",
164 function(object){
165 cat("A ", class(object), " instance\n", sep = "")
166 if(length([email protected][[1L]]) > 1L){
167 cat(" '", [email protected], "' vs. '", [email protected],
168 "' (alpha: '",[email protected],"')\n", sep = "")
169 } else {
170 cat(" '", [email protected], "'\n", sep = "")
171 }
172 if(length([email protected]) > 1L){
173 cat(" for ", length([email protected])," cross ",
174 "validation runs ", sep = "")
175 } else {
176 if(length([email protected][[1L]]) > 1L){
177 cat(" with ", length([email protected][[1L]])," data points",
178 sep = "")
179 }
180 }
181 })
182
183 #' @name plot-methods
184 #' @aliases plot,performance,missing-method plot.performance
185 #'
186 #' @title Plot method for performance objects
187 #'
188 #' @description
189 #' This is the method to plot all objects of class performance.
190 #'
191 #' @param x an object of class \code{performance}
192 #' @param y not used
193 #' @param ... Optional graphical parameters to adjust different components of
194 #' the performance plot. Parameters are directed to their target component by
195 #' prefixing them with the name of the component (\code{component.parameter},
196 #' e.g. \code{text.cex}). The following components are available:
197 #' \code{xaxis}, \code{yaxis}, \code{coloraxis}, \code{box} (around the
198 #' plotting region), \code{points}, \code{text}, \code{plotCI} (error bars),
199 #' \code{boxplot}. The names of these components are influenced by the R
200 #' functions that are used to create them. Thus, \code{par(component)} can be
201 #' used to see which parameters are available for a given component (with the
202 #' expection of the three axes; use \code{par(axis)} here). To adjust the
203 #' canvas or the performance curve(s), the standard \code{plot} parameters can
204 #' be used without any prefix.
205 #' @param avg If the performance object describes several curves (from
206 #' cross-validation runs or bootstrap evaluations of one particular method),
207 #' the curves from each of the runs can be averaged. Allowed values are
208 #' \code{none} (plot all curves separately), \code{horizontal} (horizontal
209 #' averaging), \code{vertical} (vertical averaging), and \code{threshold}
210 #' (threshold (=cutoff) averaging). Note that while threshold averaging is
211 #' always feasible, vertical and horizontal averaging are not well-defined if
212 #' the graph cannot be represented as a function x->y and y->x, respectively.
213 #' @param spread.estimate When curve averaging is enabled, the variation around
214 #' the average curve can be visualized as standard error bars
215 #' (\code{stderror}), standard deviation bars (\code{stddev}), or by using box
216 #' plots (\code{boxplot}). Note that the function \code{plotCI}, which is used
217 #' internally by ROCR to draw error bars, might raise a warning if the spread
218 #' of the curves at certain positions is 0.
219 #' @param spread.scale For \code{stderror} or \code{stddev}, this is a scalar
220 #' factor to be multiplied with the length of the standard error/deviation
221 #' bar. For example, under normal assumptions, \code{spread.scale=2} can be
222 #' used to get approximate 95\% confidence intervals.
223 #' @param show.spread.at For vertical averaging, this vector determines the x
224 #' positions for which the spread estimates should be visualized. In contrast,
225 #' for horizontal and threshold averaging, the y positions and cutoffs are
226 #' determined, respectively. By default, spread estimates are shown at 11
227 #' equally spaced positions.
228 #' @param colorize This logical determines whether the curve(s) should be
229 #' colorized according to cutoff.
230 #' @param colorize.palette If curve colorizing is enabled, this determines the
231 #' color palette onto which the cutoff range is mapped.
232 #' @param colorkey If true, a color key is drawn into the 4\% border
233 #' region (default of \code{par(xaxs)} and \code{par(yaxs)}) of the
234 #' plot. The color key visualizes the mapping from cutoffs to colors.
235 #' @param colorkey.relwidth Scalar between 0 and 1 that determines the
236 #' fraction of the 4\% border region that is occupied by the colorkey.
237 #' @param colorkey.pos Determines if the colorkey is drawn vertically at
238 #' the \code{right} side, or horizontally at the \code{top} of the
239 #' plot.
240 #' @param print.cutoffs.at This vector specifies the cutoffs which should
241 #' be printed as text along the curve at the corresponding curve positions.
242 #' @param cutoff.label.function By default, cutoff annotations along the curve
243 #' or at the color key are rounded to two decimal places before printing.
244 #' Using a custom \code{cutoff.label.function}, any other transformation can
245 #' be performed on the cutoffs instead (e.g. rounding with different precision
246 #' or taking the logarithm).
247 #' @param downsampling ROCR can efficiently compute most performance measures
248 #' even for data sets with millions of elements. However, plotting of large
249 #' data sets can be slow and lead to PS/PDF documents of considerable size. In
250 #' that case, performance curves that are indistinguishable from the original
251 #' can be obtained by using only a fraction of the computed performance
252 #' values. Values for downsampling between 0 and 1 indicate the fraction of
253 #' the original data set size to which the performance object should be
254 #' downsampled, integers above 1 are interpreted as the actual number of
255 #' performance values to which the curve(s) should be downsampled.
256 #' @param add If \code{TRUE}, the curve(s) is/are added to an already existing
257 #' plot; otherwise a new plot is drawn.
258 #'
259 #' @references
260 #' A detailed list of references can be found on the ROCR homepage at
261 #' \url{https://ipa-tys.github.io/ROCR/}.
262 #'
263 #' @author
264 #' Tobias Sing \email{[email protected]}, Oliver Sander
265 #' \email{[email protected]}
266 #'
267 #' @seealso
268 #' \code{\link{prediction}},
269 #' \code{\link{performance}},
270 #' \code{\link{prediction-class}},
271 #' \code{\link{performance-class}}
272 #'
273 #' @export
274 #'
275 #' @examples
276 #' # plotting a ROC curve:
277 #' library(ROCR)
278 #' data(ROCR.simple)
279 #' pred <- prediction( ROCR.simple$predictions, ROCR.simple$labels )
280 #' pred
281 #' perf <- performance( pred, "tpr", "fpr" )
282 #' perf
283 #' plot( perf )
284 #'
285 #' # To entertain your children, make your plots nicer
286 #' # using ROCR's flexible parameter passing mechanisms
287 #' # (much cheaper than a finger painting set)
288 #' par(bg="lightblue", mai=c(1.2,1.5,1,1))
289 #' plot(perf, main="ROCR fingerpainting toolkit", colorize=TRUE,
290 #' xlab="Mary's axis", ylab="", box.lty=7, box.lwd=5,
291 #' box.col="gold", lwd=17, colorkey.relwidth=0.5, xaxis.cex.axis=2,
292 #' xaxis.col='blue', xaxis.col.axis="blue", yaxis.col='green', yaxis.cex.axis=2,
293 #' yaxis.at=c(0,0.5,0.8,0.85,0.9,1), yaxis.las=1, xaxis.lwd=2, yaxis.lwd=3,
294 #' yaxis.col.axis="orange", cex.lab=2, cex.main=2)
295 setMethod("plot",
296 signature(x="performance",y="missing"),
297 function(x,
298 y,
299 ...,
300 avg = "none",
301 spread.estimate = "none",
302 spread.scale = 1,
303 show.spread.at = c(),
304 colorize = FALSE,
305 colorize.palette = rev(rainbow(256, start = 0, end = 4 / 6)),
306 colorkey = colorize,
307 colorkey.relwidth = 0.25,
308 colorkey.pos = "right",
309 print.cutoffs.at = c(),
310 cutoff.label.function = function(x) {
311 round(x, 2)
312 },
313 downsampling = 0,
314 add = FALSE ) {
315
316 .plot.performance(x,...,
317 avg = avg,
318 spread.estimate = spread.estimate,
319 spread.scale = spread.scale,
320 show.spread.at = show.spread.at,
321 colorize = colorize,
322 colorize.palette = colorize.palette,
323 colorkey = colorkey,
324 colorkey.relwidth = colorkey.relwidth,
325 colorkey.pos = colorkey.pos,
326 print.cutoffs.at = print.cutoffs.at,
327 cutoff.label.function = cutoff.label.function,
328 downsampling = downsampling,
329 add = add)
330 }
331 )
332
333 #' @rdname plot-methods
334 #' @method plot performance
335 #' @export
336 "plot.performance" <- function(...) plot(...)
337
338 #' @name ROCR.hiv
339 #'
340 #' @docType data
341 #' @keywords datasets
342 #'
343 #' @title Data set: Support vector machines and neural networks applied to the
344 #' prediction of HIV-1 coreceptor usage
345 #'
346 #' @description
347 #' Linear support vector machines (libsvm) and neural networks (R package
348 #' nnet) were applied to predict usage of the coreceptors CCR5 and CXCR4
349 #' based on sequence data of the third variable loop of the HIV envelope
350 #' protein.
351 #'
352 #' @format
353 #' A list consisting of the SVM (\code{ROCR.hiv$hiv.svm}) and NN
354 #' (\code{ROCR.hiv$hiv.nn}) classification data. Each of those is in turn a list
355 #' consisting of the two elements \code{$predictions} and \code{$labels} (10
356 #' element list representing cross-validation data).
357 #'
358 #' @references
359 #' Sing, T. & Beerenwinkel, N. & Lengauer, T. "Learning mixtures
360 #' of localized rules by maximizing the area under the ROC curve". 1st
361 #' International Workshop on ROC Analysis in AI, 89-96, 2004.
362 #'
363 #' @usage data(ROCR.hiv)
364 #'
365 #' @examples
366 #' library(ROCR)
367 #' data(ROCR.hiv)
368 #' attach(ROCR.hiv)
369 #' pred.svm <- prediction(hiv.svm$predictions, hiv.svm$labels)
370 #' pred.svm
371 #' perf.svm <- performance(pred.svm, 'tpr', 'fpr')
372 #' perf.svm
373 #' pred.nn <- prediction(hiv.nn$predictions, hiv.svm$labels)
374 #' pred.nn
375 #' perf.nn <- performance(pred.nn, 'tpr', 'fpr')
376 #' perf.nn
377 #' plot(perf.svm, lty=3, col="red",main="SVMs and NNs for prediction of
378 #' HIV-1 coreceptor usage")
379 #' plot(perf.nn, lty=3, col="blue",add=TRUE)
380 #' plot(perf.svm, avg="vertical", lwd=3, col="red",
381 #' spread.estimate="stderror",plotCI.lwd=2,add=TRUE)
382 #' plot(perf.nn, avg="vertical", lwd=3, col="blue",
383 #' spread.estimate="stderror",plotCI.lwd=2,add=TRUE)
384 #' legend(0.6,0.6,c('SVM','NN'),col=c('red','blue'),lwd=3)
385 "ROCR.hiv"
386
387
388 #' @name ROCR.simple
389 #'
390 #' @docType data
391 #' @keywords datasets
392 #'
393 #' @title Data set: Simple artificial prediction data for use with ROCR
394 #'
395 #' @description
396 #' A mock data set containing a simple set of predictions and corresponding
397 #' class labels.
398 #'
399 #' @format
400 #' A two element list. The first element, \code{ROCR.simple$predictions}, is a
401 #' vector of numerical predictions. The second element,
402 #' \code{ROCR.simple$labels}, is a vector of corresponding class labels.
403 #'
404 #' @usage data(ROCR.simple)
405 #'
406 #' @examples
407 #' # plot a ROC curve for a single prediction run
408 #' # and color the curve according to cutoff.
409 #' library(ROCR)
410 #' data(ROCR.simple)
411 #' pred <- prediction(ROCR.simple$predictions, ROCR.simple$labels)
412 #' pred
413 #' perf <- performance(pred,"tpr","fpr")
414 #' perf
415 #' plot(perf,colorize=TRUE)
416 "ROCR.simple"
417
418
419 #' @name ROCR.xval
420 #'
421 #' @docType data
422 #' @keywords datasets
423 #'
424 #' @title Data set: Artificial cross-validation data for use with ROCR
425 #'
426 #' @description
427 #' A mock data set containing 10 sets of predictions and corresponding labels as
428 #' would be obtained from 10-fold cross-validation.
429 #'
430 #' @format
431 #' A two element list. The first element, \code{ROCR.xval$predictions}, is
432 #' itself a 10 element list. Each of these 10 elements is a vector of numerical
433 #' predictions for each cross-validation run. Likewise, the second list entry,
434 #' \code{ROCR.xval$labels} is a 10 element list in which each element is a
435 #' vector of true class labels corresponding to the predictions.
436 #'
437 #' @usage data(ROCR.xval)
438 #'
439 #' @examples
440 #' # plot ROC curves for several cross-validation runs (dotted
441 #' # in grey), overlaid by the vertical average curve and boxplots
442 #' # showing the vertical spread around the average.
443 #' library(ROCR)
444 #' data(ROCR.xval)
445 #' pred <- prediction(ROCR.xval$predictions, ROCR.xval$labels)
446 #' pred
447 #' perf <- performance(pred,"tpr","fpr")
448 #' perf
449 #' plot(perf,col="grey82",lty=3)
450 #' plot(perf,lwd=3,avg="vertical",spread.estimate="boxplot",add=TRUE)
451 "ROCR.xval"