lgb.Predictor.R 5.9 KB
Newer Older
James Lamb's avatar
James Lamb committed
1
2

#' @importFrom methods is
Guolin Ke's avatar
Guolin Ke committed
3
Predictor <- R6Class(
4
  classname = "lgb.Predictor",
5
  cloneable = FALSE,
Guolin Ke's avatar
Guolin Ke committed
6
  public = list(
James Lamb's avatar
James Lamb committed
7

8
    # Finalize will free up the handles
Guolin Ke's avatar
Guolin Ke committed
9
    finalize = function() {
James Lamb's avatar
James Lamb committed
10

11
      # Check the need for freeing handle
12
      if (private$need_free_handle && !lgb.is.null.handle(private$handle)) {
James Lamb's avatar
James Lamb committed
13

14
        # Freeing up handle
15
        lgb.call("LGBM_BoosterFree_R", ret = NULL, private$handle)
Guolin Ke's avatar
Guolin Ke committed
16
        private$handle <- NULL
James Lamb's avatar
James Lamb committed
17

Guolin Ke's avatar
Guolin Ke committed
18
      }
James Lamb's avatar
James Lamb committed
19

20
    },
James Lamb's avatar
James Lamb committed
21

22
    # Initialize will create a starter model
23
24
25
    initialize = function(modelfile, ...) {
      params <- list(...)
      private$params <- lgb.params2str(params)
26
      # Create new lgb handle
Guolin Ke's avatar
Guolin Ke committed
27
      handle <- 0.0
James Lamb's avatar
James Lamb committed
28

29
      # Check if handle is a character
30
      if (is.character(modelfile)) {
James Lamb's avatar
James Lamb committed
31

32
        # Create handle on it
33
34
        handle <- lgb.call("LGBM_BoosterCreateFromModelfile_R", ret = handle, lgb.c_str(modelfile))
        private$need_free_handle <- TRUE
James Lamb's avatar
James Lamb committed
35
36
37

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

38
        # Check if model file is a booster handle already
Guolin Ke's avatar
Guolin Ke committed
39
        handle <- modelfile
40
        private$need_free_handle <- FALSE
James Lamb's avatar
James Lamb committed
41

Guolin Ke's avatar
Guolin Ke committed
42
      } else {
James Lamb's avatar
James Lamb committed
43

44
        # Model file is unknown
45
        stop("lgb.Predictor: modelfile must be either a character filename or an lgb.Booster.handle")
James Lamb's avatar
James Lamb committed
46

Guolin Ke's avatar
Guolin Ke committed
47
      }
James Lamb's avatar
James Lamb committed
48

49
      # Override class and store it
Guolin Ke's avatar
Guolin Ke committed
50
51
      class(handle) <- "lgb.Booster.handle"
      private$handle <- 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
    # Get current iteration
Guolin Ke's avatar
Guolin Ke committed
56
    current_iter = function() {
James Lamb's avatar
James Lamb committed
57

58
59
      cur_iter <- 0L
      lgb.call("LGBM_BoosterGetCurrentIteration_R",  ret = cur_iter, private$handle)
James Lamb's avatar
James Lamb committed
60

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

63
64
65
66
67
    # Predict from data
    predict = function(data,
                       num_iteration = NULL,
                       rawscore = FALSE,
                       predleaf = FALSE,
68
                       predcontrib = FALSE,
69
70
                       header = FALSE,
                       reshape = FALSE) {
James Lamb's avatar
James Lamb committed
71

72
73
74
75
      # Check if number of iterations is existing - if not, then set it to -1 (use all)
      if (is.null(num_iteration)) {
        num_iteration <- -1
      }
James Lamb's avatar
James Lamb committed
76

77
      # Set temporary variable
78
      num_row <- 0L
James Lamb's avatar
James Lamb committed
79

80
      # Check if data is a file name
81
      if (is.character(data)) {
James Lamb's avatar
James Lamb committed
82

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

87
        # Predict from temporary file
88
89
        lgb.call("LGBM_BoosterPredictForFile_R", ret = NULL, private$handle, data,
          as.integer(header),
Guolin Ke's avatar
Guolin Ke committed
90
91
          as.integer(rawscore),
          as.integer(predleaf),
92
          as.integer(predcontrib),
Guolin Ke's avatar
Guolin Ke committed
93
          as.integer(num_iteration),
94
          private$params,
Guolin Ke's avatar
Guolin Ke committed
95
          lgb.c_str(tmp_filename))
James Lamb's avatar
James Lamb committed
96

97
98
        # Get predictions from file
        preds <- read.delim(tmp_filename, header = FALSE, seq = "\t")
Guolin Ke's avatar
Guolin Ke committed
99
        num_row <- nrow(preds)
100
        preds <- as.vector(t(preds))
James Lamb's avatar
James Lamb committed
101

Guolin Ke's avatar
Guolin Ke committed
102
      } else {
James Lamb's avatar
James Lamb committed
103

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

107
        npred <- 0L
James Lamb's avatar
James Lamb committed
108

109
110
111
112
113
114
115
        # Check number of predictions to do
        npred <- lgb.call("LGBM_BoosterCalcNumPredict_R",
                          ret = npred,
                          private$handle,
                          as.integer(num_row),
                          as.integer(rawscore),
                          as.integer(predleaf),
116
                          as.integer(predcontrib),
117
                          as.integer(num_iteration))
James Lamb's avatar
James Lamb committed
118

119
120
        # Pre-allocate empty vector
        preds <- numeric(npred)
James Lamb's avatar
James Lamb committed
121

122
        # Check if data is a matrix
Guolin Ke's avatar
Guolin Ke committed
123
        if (is.matrix(data)) {
124
125
126
127
128
129
130
131
          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),
132
                            as.integer(predcontrib),
133
134
                            as.integer(num_iteration),
                            private$params)
James Lamb's avatar
James Lamb committed
135
136

        } else if (methods::is(data, "dgCMatrix")) {
137
138
139
          if (length(data@p) > 2147483647) {
            stop("Cannot support large CSC matrix")
          }
140
141
142
143
144
145
146
147
148
149
150
151
          # Check if data is a dgCMatrix (sparse matrix, column compressed format)
          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),
152
                            as.integer(predcontrib),
153
154
                            as.integer(num_iteration),
                            private$params)
James Lamb's avatar
James Lamb committed
155

Guolin Ke's avatar
Guolin Ke committed
156
        } else {
James Lamb's avatar
James Lamb committed
157

158
159
          # Cannot predict on unknown class
          # to-do: predict from lgb.Dataset
160
          stop("predict: cannot predict on data of class ", sQuote(class(data)))
James Lamb's avatar
James Lamb committed
161

162
        }
Guolin Ke's avatar
Guolin Ke committed
163
      }
James Lamb's avatar
James Lamb committed
164

165
      # Check if number of rows is strange (not a multiple of the dataset rows)
Guolin Ke's avatar
Guolin Ke committed
166
      if (length(preds) %% num_row != 0) {
167
        stop("predict: prediction length ", sQuote(length(preds))," is not a multiple of nrows(data): ", sQuote(num_row))
Guolin Ke's avatar
Guolin Ke committed
168
      }
James Lamb's avatar
James Lamb committed
169

170
      # Get number of cases per row
Guolin Ke's avatar
Guolin Ke committed
171
      npred_per_case <- length(preds) / num_row
James Lamb's avatar
James Lamb committed
172
173


174
      # Data reshaping
James Lamb's avatar
James Lamb committed
175

176
      if (predleaf | predcontrib) {
James Lamb's avatar
James Lamb committed
177

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

181
      } else if (reshape && npred_per_case > 1) {
James Lamb's avatar
James Lamb committed
182

183
        # Predict with data reshaping
184
        preds <- matrix(preds, ncol = npred_per_case, byrow = TRUE)
James Lamb's avatar
James Lamb committed
185

186
      }
James Lamb's avatar
James Lamb committed
187

188
189
      # Return predictions
      return(preds)
James Lamb's avatar
James Lamb committed
190

Guolin Ke's avatar
Guolin Ke committed
191
    }
James Lamb's avatar
James Lamb committed
192

193
  ),
194
  private = list(handle = NULL,
195
196
                 need_free_handle = FALSE,
                 params = "")
Guolin Ke's avatar
Guolin Ke committed
197
)