1 #' @title R6 class representing a (generic) model.
4 #' "Model" class, containing a (generic) learning function, which from
5 #' data + target [+ params] returns a prediction function X --> y.
6 #' Parameters for cross-validation are either provided or estimated.
7 #' Model family can be chosen among "rf", "tree", "ppr" and "knn" for now.
9 #' @importFrom FNN knn.reg
10 #' @importFrom class knn
11 #' @importFrom stats ppr
12 #' @importFrom randomForest randomForest
13 #' @importFrom rpart rpart
14 #' @importFrom caret var_seq
17 Model <- R6::R6Class("Model",
19 #' @field nmodels Number of parameters (= number of [predictive] models)
21 #' @description Create a new generic model.
22 #' @param data Matrix or data.frame
23 #' @param target Vector of targets (generally numeric or factor)
24 #' @param task "regression" or "classification"
25 #' @param gmodel Generic model returning a predictive function; chosen
26 #' automatically given data and target nature if not provided.
27 #' @param params List of parameters for cross-validation (each defining a model)
28 initialize = function(data, target, task, gmodel = NULL, params = NULL) {
29 if (is.null(gmodel)) {
30 # (Generic) model not provided
31 all_numeric <- is.numeric(as.matrix(data))
33 # At least one non-numeric column: use random forests or trees
34 # TODO: 4 = arbitrary magic number...
35 gmodel = ifelse(ncol(data) >= 4, "rf", "tree")
38 gmodel = ifelse(task == "regression", "ppr", "knn")
41 # Here, gmodel is a string (= its family),
42 # because a custom model must be given with its parameters.
43 params <- as.list(private$getParams(gmodel, data, target))
44 private$params <- params
45 if (is.character(gmodel))
46 gmodel <- private$getGmodel(gmodel, task)
47 private$gmodel <- gmodel
48 self$nmodels <- length(private$params)
51 #' Returns the model at index "index", trained on dataHO/targetHO.
52 #' @param dataHO Matrix or data.frame
53 #' @param targetHO Vector of targets (generally numeric or factor)
54 #' @param index Index of the model in 1...nmodels
55 get = function(dataHO, targetHO, index) {
56 private$gmodel(dataHO, targetHO, private$params[[index]])
59 #' Returns the parameter at index "index".
60 #' @param index Index of the model in 1...nmodels
61 getParam = function(index) {
62 private$params[[index]]
66 # No need to expose model or parameters list
69 # Main function: given a family, return a generic model, which in turn
70 # will output a predictive model from data + target + params.
71 getGmodel = function(family, task) {
72 if (family == "tree") {
73 function(dataHO, targetHO, param) {
75 method <- ifelse(task == "classification", "class", "anova")
76 if (is.null(colnames(dataHO)))
77 colnames(dataHO) <- paste0("V", 1:ncol(dataHO))
78 df <- data.frame(cbind(dataHO, target=targetHO))
79 model <- rpart::rpart(target ~ ., df, method=method, control=list(cp=param))
81 if (is.null(colnames(X)))
82 colnames(X) <- paste0("V", 1:ncol(X))
83 predict(model, as.data.frame(X))
87 else if (family == "rf") {
88 function(dataHO, targetHO, param) {
90 if (task == "classification" && !is.factor(targetHO))
91 targetHO <- as.factor(targetHO)
92 model <- randomForest::randomForest(dataHO, targetHO, mtry=param)
93 function(X) predict(model, X)
96 else if (family == "ppr") {
97 function(dataHO, targetHO, param) {
98 model <- stats::ppr(dataHO, targetHO, nterms=param)
99 function(X) predict(model, X)
102 else if (family == "knn") {
103 if (task == "classification") {
104 function(dataHO, targetHO, param) {
106 function(X) class::knn(dataHO, X, cl=targetHO, k=param)
110 function(dataHO, targetHO, param) {
112 function(X) FNN::knn.reg(dataHO, X, y=targetHO, k=param)$pred
117 # Return a default list of parameters, given a gmodel family
118 getParams = function(family, data, target) {
119 if (family == "tree") {
120 # Run rpart once to obtain a CV grid for parameter cp
122 df <- data.frame(cbind(data, target=target))
128 r <- rpart(target ~ ., df, method="class", control=ctrl)
129 cps <- r$cptable[-1,1]
130 if (length(cps) <= 11) {
131 if (length(cps == 0))
132 stop("No cross-validation possible: select another model")
135 step <- (length(cps) - 1) / 10
136 cps[unique(round(seq(1, length(cps), step)))]
138 else if (family == "rf") {
140 # Use caret package to obtain the CV grid of mtry values
142 caret::var_seq(p, classification = (task == "classificaton"),
145 else if (family == "ppr")
146 # This is nterms in ppr() function
148 else if (family == "knn") {
150 # Choose ~10 NN values
151 K <- length(unique(target))
155 step <- (2*sqrt_n - 1) / 10
156 grid <- unique(round(seq(1, 2*sqrt_n, step)))
158 # Common binary classification case: odd number of neighbors
160 if (grid[i] %% 2 == 0)
161 grid[i] <- grid[i] + 1 #arbitrary choice