lgb.Predictor.R 6.28 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
      # Create new lgb handle
34
      handle <- lgb.null.handle()
James Lamb's avatar
James Lamb committed
35

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

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

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

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

Guolin Ke's avatar
Guolin Ke committed
53
      } else {
James Lamb's avatar
James Lamb committed
54

55
        stop("lgb.Predictor: modelfile must be either a character filename or an lgb.Booster.handle")
James Lamb's avatar
James Lamb committed
56

Guolin Ke's avatar
Guolin Ke committed
57
      }
James Lamb's avatar
James Lamb committed
58

59
      # Override class and store it
Guolin Ke's avatar
Guolin Ke committed
60
61
      class(handle) <- "lgb.Booster.handle"
      private$handle <- handle
James Lamb's avatar
James Lamb committed
62

63
64
      return(invisible(NULL))

Guolin Ke's avatar
Guolin Ke committed
65
    },
James Lamb's avatar
James Lamb committed
66

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

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

Guolin Ke's avatar
Guolin Ke committed
78
    },
James Lamb's avatar
James Lamb committed
79

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

90
91
      # Check if number of iterations is existing - if not, then set it to -1 (use all)
      if (is.null(num_iteration)) {
92
        num_iteration <- -1L
93
      }
94
95
96
97
      # 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
98

99
      num_row <- 0L
James Lamb's avatar
James Lamb committed
100

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

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

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

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

Guolin Ke's avatar
Guolin Ke committed
128
      } else {
James Lamb's avatar
James Lamb committed
129

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

133
        npred <- 0L
James Lamb's avatar
James Lamb committed
134

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

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

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

        } else if (methods::is(data, "dgCMatrix")) {
174
          if (length(data@p) > 2147483647L) {
175
176
            stop("Cannot support large CSC matrix")
          }
177
          # Check if data is a dgCMatrix (sparse matrix, column compressed format)
178
179
          .Call(
            LGBM_BoosterPredictForCSC_R
180
181
182
183
184
185
186
187
188
189
            , 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)
190
            , as.integer(start_iteration)
191
192
            , as.integer(num_iteration)
            , private$params
193
            , preds
194
          )
James Lamb's avatar
James Lamb committed
195

Guolin Ke's avatar
Guolin Ke committed
196
        } else {
James Lamb's avatar
James Lamb committed
197

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

200
        }
Guolin Ke's avatar
Guolin Ke committed
201
      }
James Lamb's avatar
James Lamb committed
202

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

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


217
      # Data reshaping
James Lamb's avatar
James Lamb committed
218

219
      if (predleaf | predcontrib) {
James Lamb's avatar
James Lamb committed
220

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

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

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

229
      }
James Lamb's avatar
James Lamb committed
230

231
      return(preds)
James Lamb's avatar
James Lamb committed
232

Guolin Ke's avatar
Guolin Ke committed
233
    }
James Lamb's avatar
James Lamb committed
234

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