lgb.Predictor.R 5.93 KB
Newer Older
James Lamb's avatar
James Lamb committed
1
2

#' @importFrom methods is
James Lamb's avatar
James Lamb committed
3
4
5
#' @importFrom R6 R6Class
Predictor <- R6::R6Class(

6
  classname = "lgb.Predictor",
7
  cloneable = FALSE,
Guolin Ke's avatar
Guolin Ke committed
8
  public = list(
James Lamb's avatar
James Lamb committed
9

10
    # Finalize will free up the handles
Guolin Ke's avatar
Guolin Ke committed
11
    finalize = function() {
James Lamb's avatar
James Lamb committed
12

13
      # Check the need for freeing handle
14
      if (private$need_free_handle && !lgb.is.null.handle(private$handle)) {
James Lamb's avatar
James Lamb committed
15

16
        # Freeing up handle
17
        lgb.call("LGBM_BoosterFree_R", ret = NULL, private$handle)
Guolin Ke's avatar
Guolin Ke committed
18
        private$handle <- NULL
James Lamb's avatar
James Lamb committed
19

Guolin Ke's avatar
Guolin Ke committed
20
      }
James Lamb's avatar
James Lamb committed
21

22
    },
James Lamb's avatar
James Lamb committed
23

24
    # Initialize will create a starter model
25
26
27
    initialize = function(modelfile, ...) {
      params <- list(...)
      private$params <- lgb.params2str(params)
28
      # Create new lgb handle
Guolin Ke's avatar
Guolin Ke committed
29
      handle <- 0.0
James Lamb's avatar
James Lamb committed
30

31
      # Check if handle is a character
32
      if (is.character(modelfile)) {
James Lamb's avatar
James Lamb committed
33

34
        # Create handle on it
35
36
        handle <- lgb.call("LGBM_BoosterCreateFromModelfile_R", ret = handle, lgb.c_str(modelfile))
        private$need_free_handle <- TRUE
James Lamb's avatar
James Lamb committed
37
38
39

      } else if (methods::is(modelfile, "lgb.Booster.handle")) {

40
        # Check if model file is a booster handle already
Guolin Ke's avatar
Guolin Ke committed
41
        handle <- modelfile
42
        private$need_free_handle <- FALSE
James Lamb's avatar
James Lamb committed
43

Guolin Ke's avatar
Guolin Ke committed
44
      } else {
James Lamb's avatar
James Lamb committed
45

46
        # Model file is unknown
47
        stop("lgb.Predictor: modelfile must be either a character filename or an lgb.Booster.handle")
James Lamb's avatar
James Lamb committed
48

Guolin Ke's avatar
Guolin Ke committed
49
      }
James Lamb's avatar
James Lamb committed
50

51
      # Override class and store it
Guolin Ke's avatar
Guolin Ke committed
52
53
      class(handle) <- "lgb.Booster.handle"
      private$handle <- handle
James Lamb's avatar
James Lamb committed
54

Guolin Ke's avatar
Guolin Ke committed
55
    },
James Lamb's avatar
James Lamb committed
56

57
    # Get current iteration
Guolin Ke's avatar
Guolin Ke committed
58
    current_iter = function() {
James Lamb's avatar
James Lamb committed
59

60
61
      cur_iter <- 0L
      lgb.call("LGBM_BoosterGetCurrentIteration_R",  ret = cur_iter, private$handle)
James Lamb's avatar
James Lamb committed
62

Guolin Ke's avatar
Guolin Ke committed
63
    },
James Lamb's avatar
James Lamb committed
64

65
66
67
68
69
    # Predict from data
    predict = function(data,
                       num_iteration = NULL,
                       rawscore = FALSE,
                       predleaf = FALSE,
70
                       predcontrib = FALSE,
71
72
                       header = FALSE,
                       reshape = FALSE) {
James Lamb's avatar
James Lamb committed
73

74
75
76
77
      # Check if number of iterations is existing - if not, then set it to -1 (use all)
      if (is.null(num_iteration)) {
        num_iteration <- -1
      }
James Lamb's avatar
James Lamb committed
78

79
      # Set temporary variable
80
      num_row <- 0L
James Lamb's avatar
James Lamb committed
81

82
      # Check if data is a file name
83
      if (is.character(data)) {
James Lamb's avatar
James Lamb committed
84

85
        # Data is a filename, create a temporary file with a "lightgbm_" pattern in it
Guolin Ke's avatar
Guolin Ke committed
86
        tmp_filename <- tempfile(pattern = "lightgbm_")
87
        on.exit(unlink(tmp_filename), add = TRUE)
James Lamb's avatar
James Lamb committed
88

89
        # Predict from temporary file
90
91
        lgb.call("LGBM_BoosterPredictForFile_R", ret = NULL, private$handle, data,
          as.integer(header),
Guolin Ke's avatar
Guolin Ke committed
92
93
          as.integer(rawscore),
          as.integer(predleaf),
94
          as.integer(predcontrib),
Guolin Ke's avatar
Guolin Ke committed
95
          as.integer(num_iteration),
96
          private$params,
Guolin Ke's avatar
Guolin Ke committed
97
          lgb.c_str(tmp_filename))
James Lamb's avatar
James Lamb committed
98

99
100
        # Get predictions from file
        preds <- read.delim(tmp_filename, header = FALSE, seq = "\t")
Guolin Ke's avatar
Guolin Ke committed
101
        num_row <- nrow(preds)
102
        preds <- as.vector(t(preds))
James Lamb's avatar
James Lamb committed
103

Guolin Ke's avatar
Guolin Ke committed
104
      } else {
James Lamb's avatar
James Lamb committed
105

106
        # Not a file, we need to predict from R object
Guolin Ke's avatar
Guolin Ke committed
107
        num_row <- nrow(data)
James Lamb's avatar
James Lamb committed
108

109
        npred <- 0L
James Lamb's avatar
James Lamb committed
110

111
112
113
114
115
116
117
        # Check number of predictions to do
        npred <- lgb.call("LGBM_BoosterCalcNumPredict_R",
                          ret = npred,
                          private$handle,
                          as.integer(num_row),
                          as.integer(rawscore),
                          as.integer(predleaf),
118
                          as.integer(predcontrib),
119
                          as.integer(num_iteration))
James Lamb's avatar
James Lamb committed
120

121
122
        # Pre-allocate empty vector
        preds <- numeric(npred)
James Lamb's avatar
James Lamb committed
123

124
        # Check if data is a matrix
Guolin Ke's avatar
Guolin Ke committed
125
        if (is.matrix(data)) {
126
127
128
129
130
131
132
133
          preds <- lgb.call("LGBM_BoosterPredictForMat_R",
                            ret = preds,
                            private$handle,
                            data,
                            as.integer(nrow(data)),
                            as.integer(ncol(data)),
                            as.integer(rawscore),
                            as.integer(predleaf),
134
                            as.integer(predcontrib),
135
136
                            as.integer(num_iteration),
                            private$params)
James Lamb's avatar
James Lamb committed
137
138

        } else if (methods::is(data, "dgCMatrix")) {
139
140
141
          if (length(data@p) > 2147483647) {
            stop("Cannot support large CSC matrix")
          }
142
143
144
145
146
147
148
149
150
151
152
153
          # Check if data is a dgCMatrix (sparse matrix, column compressed format)
          preds <- lgb.call("LGBM_BoosterPredictForCSC_R",
                            ret = preds,
                            private$handle,
                            data@p,
                            data@i,
                            data@x,
                            length(data@p),
                            length(data@x),
                            nrow(data),
                            as.integer(rawscore),
                            as.integer(predleaf),
154
                            as.integer(predcontrib),
155
156
                            as.integer(num_iteration),
                            private$params)
James Lamb's avatar
James Lamb committed
157

Guolin Ke's avatar
Guolin Ke committed
158
        } else {
James Lamb's avatar
James Lamb committed
159

160
161
          # Cannot predict on unknown class
          # to-do: predict from lgb.Dataset
162
          stop("predict: cannot predict on data of class ", sQuote(class(data)))
James Lamb's avatar
James Lamb committed
163

164
        }
Guolin Ke's avatar
Guolin Ke committed
165
      }
James Lamb's avatar
James Lamb committed
166

167
      # Check if number of rows is strange (not a multiple of the dataset rows)
Guolin Ke's avatar
Guolin Ke committed
168
      if (length(preds) %% num_row != 0) {
169
        stop("predict: prediction length ", sQuote(length(preds))," is not a multiple of nrows(data): ", sQuote(num_row))
Guolin Ke's avatar
Guolin Ke committed
170
      }
James Lamb's avatar
James Lamb committed
171

172
      # Get number of cases per row
Guolin Ke's avatar
Guolin Ke committed
173
      npred_per_case <- length(preds) / num_row
James Lamb's avatar
James Lamb committed
174
175


176
      # Data reshaping
James Lamb's avatar
James Lamb committed
177

178
      if (predleaf | predcontrib) {
James Lamb's avatar
James Lamb committed
179

180
        # Predict leaves only, reshaping is mandatory
181
        preds <- matrix(preds, ncol = npred_per_case, byrow = TRUE)
James Lamb's avatar
James Lamb committed
182

183
      } else if (reshape && npred_per_case > 1) {
James Lamb's avatar
James Lamb committed
184

185
        # Predict with data reshaping
186
        preds <- matrix(preds, ncol = npred_per_case, byrow = TRUE)
James Lamb's avatar
James Lamb committed
187

188
      }
James Lamb's avatar
James Lamb committed
189

190
191
      # Return predictions
      return(preds)
James Lamb's avatar
James Lamb committed
192

Guolin Ke's avatar
Guolin Ke committed
193
    }
James Lamb's avatar
James Lamb committed
194

195
  ),
196
  private = list(handle = NULL,
197
198
                 need_free_handle = FALSE,
                 params = "")
Guolin Ke's avatar
Guolin Ke committed
199
)