lgb.Predictor.R 5.63 KB
Newer Older
Guolin Ke's avatar
Guolin Ke committed
1
Predictor <- R6Class(
2
  classname = "lgb.Predictor",
3
  cloneable = FALSE,
Guolin Ke's avatar
Guolin Ke committed
4
  public = list(
5
6
    
    # Finalize will free up the handles
Guolin Ke's avatar
Guolin Ke committed
7
    finalize = function() {
8
9
      
      # Check the need for freeing handle
10
      if (private$need_free_handle && !lgb.is.null.handle(private$handle)) {
11
12
        
        # Freeing up handle
13
        lgb.call("LGBM_BoosterFree_R", ret = NULL, private$handle)
Guolin Ke's avatar
Guolin Ke committed
14
        private$handle <- NULL
15
        
Guolin Ke's avatar
Guolin Ke committed
16
      }
17
      
18
    },
19
20
    
    # Initialize will create a starter model
Guolin Ke's avatar
Guolin Ke committed
21
    initialize = function(modelfile) {
22
23
      
      # Create new lgb handle
Guolin Ke's avatar
Guolin Ke committed
24
      handle <- lgb.new.handle()
25
26
      
      # Check if handle is a character
27
      if (is.character(modelfile)) {
28
29
        
        # Create handle on it
30
31
        handle <- lgb.call("LGBM_BoosterCreateFromModelfile_R", ret = handle, lgb.c_str(modelfile))
        private$need_free_handle <- TRUE
32
        
33
      } else if (is(modelfile, "lgb.Booster.handle")) {
34
35
        
        # Check if model file is a booster handle already
Guolin Ke's avatar
Guolin Ke committed
36
        handle <- modelfile
37
        private$need_free_handle <- FALSE
38
        
Guolin Ke's avatar
Guolin Ke committed
39
      } else {
40
41
        
        # Model file is unknown
42
        stop("lgb.Predictor: modelfile must be either a character filename or an lgb.Booster.handle")
43
        
Guolin Ke's avatar
Guolin Ke committed
44
      }
45
46
      
      # Override class and store it
Guolin Ke's avatar
Guolin Ke committed
47
48
      class(handle) <- "lgb.Booster.handle"
      private$handle <- handle
49
      
Guolin Ke's avatar
Guolin Ke committed
50
    },
51
52
    
    # Get current iteration
Guolin Ke's avatar
Guolin Ke committed
53
    current_iter = function() {
54
      
55
56
      cur_iter <- 0L
      lgb.call("LGBM_BoosterGetCurrentIteration_R",  ret = cur_iter, private$handle)
57
      
Guolin Ke's avatar
Guolin Ke committed
58
    },
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
    
    # Predict from data
    predict = function(data,
                       num_iteration = NULL,
                       rawscore = FALSE,
                       predleaf = FALSE,
                       header = FALSE,
                       reshape = FALSE) {
      
      # Check if number of iterations is existing - if not, then set it to -1 (use all)
      if (is.null(num_iteration)) {
        num_iteration <- -1
      }
      
      # Set temporary variable
74
      num_row <- 0L
75
76
      
      # Check if data is a file name
77
      if (is.character(data)) {
78
79
        
        # Data is a filename, create a temporary file with a "lightgbm_" pattern in it
Guolin Ke's avatar
Guolin Ke committed
80
        tmp_filename <- tempfile(pattern = "lightgbm_")
81
        on.exit(unlink(tmp_filename), add = TRUE)
82
83
        
        # Predict from temporary file
84
85
        lgb.call("LGBM_BoosterPredictForFile_R", ret = NULL, private$handle, data,
          as.integer(header),
Guolin Ke's avatar
Guolin Ke committed
86
87
88
89
          as.integer(rawscore),
          as.integer(predleaf),
          as.integer(num_iteration),
          lgb.c_str(tmp_filename))
90
91
92
        
        # Get predictions from file
        preds <- read.delim(tmp_filename, header = FALSE, seq = "\t")
Guolin Ke's avatar
Guolin Ke committed
93
        num_row <- nrow(preds)
94
95
        preds <- as.vector(t(preds))
        
Guolin Ke's avatar
Guolin Ke committed
96
      } else {
97
98
        
        # Not a file, we need to predict from R object
Guolin Ke's avatar
Guolin Ke committed
99
        num_row <- nrow(data)
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
        npred <- 0L
        
        # 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),
                          as.integer(num_iteration))
        
        # Pre-allocate empty vector
        preds <- numeric(npred)
        
        # Check if data is a matrix
Guolin Ke's avatar
Guolin Ke committed
115
        if (is.matrix(data)) {
116
117
118
119
120
121
122
123
124
125
          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(num_iteration))
          
126
        } else if (is(data, "dgCMatrix")) {
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
          
          # 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),
                            as.integer(num_iteration))
          
Guolin Ke's avatar
Guolin Ke committed
142
        } else {
143
144
145
          
          # Cannot predict on unknown class
          # to-do: predict from lgb.Dataset
146
          stop("predict: cannot predict on data of class ", sQuote(class(data)))
147
          
148
        }
Guolin Ke's avatar
Guolin Ke committed
149
      }
150
151
      
      # Check if number of rows is strange (not a multiple of the dataset rows)
Guolin Ke's avatar
Guolin Ke committed
152
      if (length(preds) %% num_row != 0) {
153
        stop("predict: prediction length ", sQuote(length(preds))," is not a multiple of nrows(data): ", sQuote(num_row))
Guolin Ke's avatar
Guolin Ke committed
154
      }
155
156
      
      # Get number of cases per row
Guolin Ke's avatar
Guolin Ke committed
157
      npred_per_case <- length(preds) / num_row
158
159
160
161
      
      
      # Data reshaping
      
162
      if (predleaf) {
163
164
        
        # Predict leaves only, reshaping is mandatory
165
        preds <- matrix(preds, ncol = npred_per_case, byrow = TRUE)
166
        
167
      } else if (reshape && npred_per_case > 1) {
168
169
        
        # Predict with data reshaping
170
        preds <- matrix(preds, ncol = npred_per_case, byrow = TRUE)
171
        
172
      }
173
174
175
176
      
      # Return predictions
      return(preds)
      
Guolin Ke's avatar
Guolin Ke committed
177
    }
178
    
179
  ),
180
181
  private = list(handle = NULL,
                 need_free_handle = FALSE)
Guolin Ke's avatar
Guolin Ke committed
182
)