lgb.Predictor.R 6.12 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
      # Check if handle is a character
34
      if (is.character(modelfile)) {
James Lamb's avatar
James Lamb committed
35

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

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

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

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

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

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

55
      # Override class and store it
Guolin Ke's avatar
Guolin Ke committed
56
57
      class(handle) <- "lgb.Booster.handle"
      private$handle <- handle
James Lamb's avatar
James Lamb committed
58

59
60
      return(invisible(NULL))

Guolin Ke's avatar
Guolin Ke committed
61
    },
James Lamb's avatar
James Lamb committed
62

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

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

Guolin Ke's avatar
Guolin Ke committed
74
    },
James Lamb's avatar
James Lamb committed
75

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

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

95
      num_row <- 0L
James Lamb's avatar
James Lamb committed
96

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

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

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

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

Guolin Ke's avatar
Guolin Ke committed
124
      } else {
James Lamb's avatar
James Lamb committed
125

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

129
        npred <- 0L
James Lamb's avatar
James Lamb committed
130

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

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

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

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

Guolin Ke's avatar
Guolin Ke committed
192
        } else {
James Lamb's avatar
James Lamb committed
193

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

196
        }
Guolin Ke's avatar
Guolin Ke committed
197
      }
James Lamb's avatar
James Lamb committed
198

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

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


213
      # Data reshaping
James Lamb's avatar
James Lamb committed
214

215
      if (predleaf | predcontrib) {
James Lamb's avatar
James Lamb committed
216

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

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

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

225
      }
James Lamb's avatar
James Lamb committed
226

227
      return(preds)
James Lamb's avatar
James Lamb committed
228

Guolin Ke's avatar
Guolin Ke committed
229
    }
James Lamb's avatar
James Lamb committed
230

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