lgb.Predictor.R 6.29 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) {
James Lamb's avatar
James Lamb committed
15

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

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

24
25
      return(invisible(NULL))

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

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

33
      if (is.character(modelfile)) {
James Lamb's avatar
James Lamb committed
34

35
        # Create handle on it
36
        handle <- .Call(
37
          LGBM_BoosterCreateFromModelfile_R
38
          , path.expand(modelfile)
39
        )
40
        private$need_free_handle <- TRUE
James Lamb's avatar
James Lamb committed
41

42
      } else if (methods::is(modelfile, "lgb.Booster.handle") || inherits(modelfile, "externalptr")) {
James Lamb's avatar
James Lamb committed
43

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

48
49
50
51
52
      } else if (lgb.is.Booster(modelfile)) {

        handle <- modelfile$get_handle()
        private$need_free_handle <- FALSE

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
105
        data <- path.expand(data)

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

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

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

Guolin Ke's avatar
Guolin Ke committed
130
      } else {
James Lamb's avatar
James Lamb committed
131

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

135
        npred <- 0L
James Lamb's avatar
James Lamb committed
136

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

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

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

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

Guolin Ke's avatar
Guolin Ke committed
198
        } else {
James Lamb's avatar
James Lamb committed
199

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

202
        }
Guolin Ke's avatar
Guolin Ke committed
203
      }
James Lamb's avatar
James Lamb committed
204

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

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


219
      # Data reshaping
James Lamb's avatar
James Lamb committed
220

221
      if (predleaf | predcontrib) {
James Lamb's avatar
James Lamb committed
222

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

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

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

231
      }
James Lamb's avatar
James Lamb committed
232

233
      return(preds)
James Lamb's avatar
James Lamb committed
234

Guolin Ke's avatar
Guolin Ke committed
235
    }
James Lamb's avatar
James Lamb committed
236

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