lgb.Predictor.R 6.2 KB
Newer Older
James Lamb's avatar
James Lamb committed
1
#' @importFrom methods is
James Lamb's avatar
James Lamb committed
2
#' @importFrom R6 R6Class
3
#' @importFrom utils read.delim
James Lamb's avatar
James Lamb committed
4
5
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(x = private$handle)) {
James Lamb's avatar
James Lamb committed
15

16
        # Freeing up handle
17
18
        .Call(
          LGBM_BoosterFree_R
19
20
          , private$handle
        )
Guolin Ke's avatar
Guolin Ke committed
21
        private$handle <- NULL
James Lamb's avatar
James Lamb committed
22

Guolin Ke's avatar
Guolin Ke committed
23
      }
James Lamb's avatar
James Lamb committed
24

25
26
      return(invisible(NULL))

27
    },
James Lamb's avatar
James Lamb committed
28

29
    # Initialize will create a starter model
30
31
    initialize = function(modelfile, ...) {
      params <- list(...)
32
      private$params <- lgb.params2str(params = params)
33
      handle <- NULL
James Lamb's avatar
James Lamb committed
34

35
      # Check if handle is a character
36
      if (is.character(modelfile)) {
James Lamb's avatar
James Lamb committed
37

38
        # Create handle on it
39
        handle <- .Call(
40
          LGBM_BoosterCreateFromModelfile_R
41
          , modelfile
42
        )
43
        private$need_free_handle <- TRUE
James Lamb's avatar
James Lamb committed
44
45
46

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

47
        # Check if model file is a booster handle already
Guolin Ke's avatar
Guolin Ke committed
48
        handle <- modelfile
49
        private$need_free_handle <- FALSE
James Lamb's avatar
James Lamb committed
50

Guolin Ke's avatar
Guolin Ke committed
51
      } else {
James Lamb's avatar
James Lamb committed
52

53
        stop("lgb.Predictor: modelfile must be either a character filename or an lgb.Booster.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
      # Override class and store it
Guolin Ke's avatar
Guolin Ke committed
58
59
      class(handle) <- "lgb.Booster.handle"
      private$handle <- handle
James Lamb's avatar
James Lamb committed
60

61
62
      return(invisible(NULL))

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

65
    # Get current iteration
Guolin Ke's avatar
Guolin Ke committed
66
    current_iter = function() {
James Lamb's avatar
James Lamb committed
67

68
      cur_iter <- 0L
69
70
71
72
      .Call(
        LGBM_BoosterGetCurrentIteration_R
        , private$handle
        , cur_iter
73
      )
74
      return(cur_iter)
James Lamb's avatar
James Lamb committed
75

Guolin Ke's avatar
Guolin Ke committed
76
    },
James Lamb's avatar
James Lamb committed
77

78
79
    # Predict from data
    predict = function(data,
80
                       start_iteration = NULL,
81
82
83
                       num_iteration = NULL,
                       rawscore = FALSE,
                       predleaf = FALSE,
84
                       predcontrib = FALSE,
85
86
                       header = FALSE,
                       reshape = FALSE) {
James Lamb's avatar
James Lamb committed
87

88
89
      # Check if number of iterations is existing - if not, then set it to -1 (use all)
      if (is.null(num_iteration)) {
90
        num_iteration <- -1L
91
      }
92
93
94
95
      # Check if start iterations is existing - if not, then set it to 0 (start from the first iteration)
      if (is.null(start_iteration)) {
        start_iteration <- 0L
      }
James Lamb's avatar
James Lamb committed
96

97
      num_row <- 0L
James Lamb's avatar
James Lamb committed
98

Laurae's avatar
Laurae committed
99
      # Check if data is a file name and not a matrix
100
      if (identical(class(data), "character") && length(data) == 1L) {
James Lamb's avatar
James Lamb committed
101

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

106
        # Predict from temporary file
107
108
        .Call(
          LGBM_BoosterPredictForFile_R
109
110
111
112
113
114
          , private$handle
          , data
          , as.integer(header)
          , as.integer(rawscore)
          , as.integer(predleaf)
          , as.integer(predcontrib)
115
          , as.integer(start_iteration)
116
117
          , as.integer(num_iteration)
          , private$params
118
          , tmp_filename
119
        )
James Lamb's avatar
James Lamb committed
120

121
        # Get predictions from file
122
        preds <- utils::read.delim(tmp_filename, header = FALSE, sep = "\t")
Guolin Ke's avatar
Guolin Ke committed
123
        num_row <- nrow(preds)
124
        preds <- as.vector(t(preds))
James Lamb's avatar
James Lamb committed
125

Guolin Ke's avatar
Guolin Ke committed
126
      } else {
James Lamb's avatar
James Lamb committed
127

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

131
        npred <- 0L
James Lamb's avatar
James Lamb committed
132

133
        # Check number of predictions to do
134
135
        .Call(
          LGBM_BoosterCalcNumPredict_R
136
137
138
139
140
          , private$handle
          , as.integer(num_row)
          , as.integer(rawscore)
          , as.integer(predleaf)
          , as.integer(predcontrib)
141
          , as.integer(start_iteration)
142
          , as.integer(num_iteration)
143
          , npred
144
        )
James Lamb's avatar
James Lamb committed
145

146
147
        # Pre-allocate empty vector
        preds <- numeric(npred)
James Lamb's avatar
James Lamb committed
148

149
        # Check if data is a matrix
Guolin Ke's avatar
Guolin Ke committed
150
        if (is.matrix(data)) {
151
152
          # this if() prevents the memory and computational costs
          # of converting something that is already "double" to "double"
153
154
155
          if (storage.mode(data) != "double") {
            storage.mode(data) <- "double"
          }
156
157
          .Call(
            LGBM_BoosterPredictForMat_R
158
159
160
161
162
163
164
            , private$handle
            , data
            , as.integer(nrow(data))
            , as.integer(ncol(data))
            , as.integer(rawscore)
            , as.integer(predleaf)
            , as.integer(predcontrib)
165
            , as.integer(start_iteration)
166
167
            , as.integer(num_iteration)
            , private$params
168
            , preds
169
          )
James Lamb's avatar
James Lamb committed
170
171

        } else if (methods::is(data, "dgCMatrix")) {
172
          if (length(data@p) > 2147483647L) {
173
174
            stop("Cannot support large CSC matrix")
          }
175
          # Check if data is a dgCMatrix (sparse matrix, column compressed format)
176
177
          .Call(
            LGBM_BoosterPredictForCSC_R
178
179
180
181
182
183
184
185
186
187
            , private$handle
            , data@p
            , data@i
            , data@x
            , length(data@p)
            , length(data@x)
            , nrow(data)
            , as.integer(rawscore)
            , as.integer(predleaf)
            , as.integer(predcontrib)
188
            , as.integer(start_iteration)
189
190
            , as.integer(num_iteration)
            , private$params
191
            , preds
192
          )
James Lamb's avatar
James Lamb committed
193

Guolin Ke's avatar
Guolin Ke committed
194
        } else {
James Lamb's avatar
James Lamb committed
195

196
          stop("predict: cannot predict on data of class ", sQuote(class(data)))
James Lamb's avatar
James Lamb committed
197

198
        }
Guolin Ke's avatar
Guolin Ke committed
199
      }
James Lamb's avatar
James Lamb committed
200

201
      # Check if number of rows is strange (not a multiple of the dataset rows)
202
      if (length(preds) %% num_row != 0L) {
203
204
205
        stop(
          "predict: prediction length "
          , sQuote(length(preds))
206
          , " is not a multiple of nrows(data): "
207
208
          , sQuote(num_row)
        )
Guolin Ke's avatar
Guolin Ke committed
209
      }
James Lamb's avatar
James Lamb committed
210

211
      # Get number of cases per row
Guolin Ke's avatar
Guolin Ke committed
212
      npred_per_case <- length(preds) / num_row
James Lamb's avatar
James Lamb committed
213
214


215
      # Data reshaping
James Lamb's avatar
James Lamb committed
216

217
      if (predleaf | predcontrib) {
James Lamb's avatar
James Lamb committed
218

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

222
      } else if (reshape && npred_per_case > 1L) {
James Lamb's avatar
James Lamb committed
223

224
        # Predict with data reshaping
225
        preds <- matrix(preds, ncol = npred_per_case, byrow = TRUE)
James Lamb's avatar
James Lamb committed
226

227
      }
James Lamb's avatar
James Lamb committed
228

229
      return(preds)
James Lamb's avatar
James Lamb committed
230

Guolin Ke's avatar
Guolin Ke committed
231
    }
James Lamb's avatar
James Lamb committed
232

233
  ),
234
235
236
237
238
  private = list(
    handle = NULL
    , need_free_handle = FALSE
    , params = ""
  )
Guolin Ke's avatar
Guolin Ke committed
239
)