lgb.Predictor.R 5.82 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(private$handle)) {
James Lamb's avatar
James Lamb committed
15

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

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

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

28
    # Initialize will create a starter model
29
30
31
    initialize = function(modelfile, ...) {
      params <- list(...)
      private$params <- lgb.params2str(params)
32
      # Create new lgb handle
Guolin Ke's avatar
Guolin Ke committed
33
      handle <- 0.0
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
40
41
42
43
        handle <- lgb.call(
          "LGBM_BoosterCreateFromModelfile_R"
          , ret = handle
          , lgb.c_str(modelfile)
        )
44
        private$need_free_handle <- TRUE
James Lamb's avatar
James Lamb committed
45
46
47

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

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

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

54
        # Model file is unknown
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

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
73
      lgb.call(
        "LGBM_BoosterGetCurrentIteration_R"
        , ret = cur_iter
        , private$handle
      )
James Lamb's avatar
James Lamb committed
74

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

77
78
79
80
81
    # Predict from data
    predict = function(data,
                       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
      }
James Lamb's avatar
James Lamb committed
90

91
      # Set temporary variable
92
      num_row <- 0L
James Lamb's avatar
James Lamb committed
93

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

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

101
        # Predict from temporary file
102
103
104
105
106
107
108
109
110
111
112
113
114
        lgb.call(
          "LGBM_BoosterPredictForFile_R"
          , ret = NULL
          , private$handle
          , data
          , as.integer(header)
          , as.integer(rawscore)
          , as.integer(predleaf)
          , as.integer(predcontrib)
          , as.integer(num_iteration)
          , private$params
          , lgb.c_str(tmp_filename)
        )
James Lamb's avatar
James Lamb committed
115

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

Guolin Ke's avatar
Guolin Ke committed
121
      } else {
James Lamb's avatar
James Lamb committed
122

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

126
        npred <- 0L
James Lamb's avatar
James Lamb committed
127

128
        # Check number of predictions to do
129
130
131
132
133
134
135
136
137
138
        npred <- lgb.call(
          "LGBM_BoosterCalcNumPredict_R"
          , ret = npred
          , private$handle
          , as.integer(num_row)
          , as.integer(rawscore)
          , as.integer(predleaf)
          , as.integer(predcontrib)
          , as.integer(num_iteration)
        )
James Lamb's avatar
James Lamb committed
139

140
141
        # Pre-allocate empty vector
        preds <- numeric(npred)
James Lamb's avatar
James Lamb committed
142

143
        # Check if data is a matrix
Guolin Ke's avatar
Guolin Ke committed
144
        if (is.matrix(data)) {
145
146
147
148
149
150
151
152
153
154
155
156
157
          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)
            , as.integer(predcontrib)
            , as.integer(num_iteration)
            , private$params
          )
James Lamb's avatar
James Lamb committed
158
159

        } else if (methods::is(data, "dgCMatrix")) {
160
          if (length(data@p) > 2147483647L) {
161
162
            stop("Cannot support large CSC matrix")
          }
163
          # Check if data is a dgCMatrix (sparse matrix, column compressed format)
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
          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)
            , as.integer(predcontrib)
            , as.integer(num_iteration)
            , private$params
          )
James Lamb's avatar
James Lamb committed
180

Guolin Ke's avatar
Guolin Ke committed
181
        } else {
James Lamb's avatar
James Lamb committed
182

183
          # Cannot predict on unknown class
184
          stop("predict: cannot predict on data of class ", sQuote(class(data)))
James Lamb's avatar
James Lamb committed
185

186
        }
Guolin Ke's avatar
Guolin Ke committed
187
      }
James Lamb's avatar
James Lamb committed
188

189
      # Check if number of rows is strange (not a multiple of the dataset rows)
190
      if (length(preds) %% num_row != 0L) {
191
192
193
        stop(
          "predict: prediction length "
          , sQuote(length(preds))
194
          , " is not a multiple of nrows(data): "
195
196
          , sQuote(num_row)
        )
Guolin Ke's avatar
Guolin Ke committed
197
      }
James Lamb's avatar
James Lamb committed
198

199
      # Get number of cases per row
Guolin Ke's avatar
Guolin Ke committed
200
      npred_per_case <- length(preds) / num_row
James Lamb's avatar
James Lamb committed
201
202


203
      # Data reshaping
James Lamb's avatar
James Lamb committed
204

205
      if (predleaf | predcontrib) {
James Lamb's avatar
James Lamb committed
206

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

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

212
        # Predict with data reshaping
213
        preds <- matrix(preds, ncol = npred_per_case, byrow = TRUE)
James Lamb's avatar
James Lamb committed
214

215
      }
James Lamb's avatar
James Lamb committed
216

217
218
      # Return predictions
      return(preds)
James Lamb's avatar
James Lamb committed
219

Guolin Ke's avatar
Guolin Ke committed
220
    }
James Lamb's avatar
James Lamb committed
221

222
  ),
223
224
225
226
227
  private = list(
    handle = NULL
    , need_free_handle = FALSE
    , params = ""
  )
Guolin Ke's avatar
Guolin Ke committed
228
)