utils.R 8.42 KB
Newer Older
1
lgb.is.Booster <- function(x) {
2
  return(lgb.check.r6.class(object = x, name = "lgb.Booster"))
3
}
4

5
lgb.is.Dataset <- function(x) {
6
  return(lgb.check.r6.class(object = x, name = "lgb.Dataset"))
7
}
8

9
lgb.is.null.handle <- function(x) {
10
11
12
13
14
15
  if (is.null(x)) {
    return(TRUE)
  }
  return(
    isTRUE(.Call(LGBM_HandleIsNull_R, x))
  )
16
}
Guolin Ke's avatar
Guolin Ke committed
17

18
19
# [description] Get the most recent error stored on the C++ side and raise it
#               as an R error.
20
21
lgb.last_error <- function() {
  err_msg <- .Call(
22
    LGBM_GetLastError_R
23
  )
24
  stop("api error: ", err_msg)
25
  return(invisible(NULL))
Guolin Ke's avatar
Guolin Ke committed
26
27
}
lgb.params2str <- function(params, ...) {
28

29
  # Check for a list as input
30
  if (!identical(class(params), "list")) {
31
32
    stop("params must be a list")
  }
33

34
  # Split parameter names
Guolin Ke's avatar
Guolin Ke committed
35
  names(params) <- gsub("\\.", "_", names(params))
36

37
  # Merge parameters from the params and the dots-expansion
Guolin Ke's avatar
Guolin Ke committed
38
39
  dot_params <- list(...)
  names(dot_params) <- gsub("\\.", "_", names(dot_params))
40

41
  # Check for identical parameters
42
  if (length(intersect(names(params), names(dot_params))) > 0L) {
43
44
45
46
47
48
49
    stop(
      "Same parameters in "
      , sQuote("params")
      , " and in the call are not allowed. Please check your "
      , sQuote("params")
      , " list"
    )
50
  }
51

52
  # Merge parameters
Guolin Ke's avatar
Guolin Ke committed
53
  params <- c(params, dot_params)
54

55
56
  # Setup temporary variable
  ret <- list()
57

58
  # Perform key value join
Guolin Ke's avatar
Guolin Ke committed
59
  for (key in names(params)) {
60

61
62
63
64
65
66
67
68
69
70
71
    # If a parameter has multiple values, join those values together with commas.
    # trimws() is necessary because format() will pad to make strings the same width
    val <- paste0(
      trimws(
        format(
          x = params[[key]]
          , scientific = FALSE
        )
      )
      , collapse = ","
    )
72
    if (nchar(val) <= 0L) next # Skip join
73

74
    # Join key value
Guolin Ke's avatar
Guolin Ke committed
75
    pair <- paste0(c(key, val), collapse = "=")
76
    ret <- c(ret, pair)
77

Guolin Ke's avatar
Guolin Ke committed
78
  }
79

80
  # Check ret length
81
  if (length(ret) == 0L) {
82
    return("")
Guolin Ke's avatar
Guolin Ke committed
83
  }
84

85
  return(paste0(ret, collapse = " "))
86

Guolin Ke's avatar
Guolin Ke committed
87
88
}

89
lgb.check_interaction_constraints <- function(interaction_constraints, column_names) {
90
91
92
93

  # Convert interaction constraints to feature numbers
  string_constraints <- list()

94
  if (!is.null(interaction_constraints)) {
95

96
    if (!methods::is(interaction_constraints, "list")) {
97
98
        stop("interaction_constraints must be a list")
    }
99
    if (!all(sapply(interaction_constraints, function(x) {is.character(x) || is.numeric(x)}))) {
100
101
102
        stop("every element in interaction_constraints must be a character vector or numeric vector")
    }

103
    for (constraint in interaction_constraints) {
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146

      # Check for character name
      if (is.character(constraint)) {

          constraint_indices <- as.integer(match(constraint, column_names) - 1L)

          # Provided indices, but some indices are not existing?
          if (sum(is.na(constraint_indices)) > 0L) {
            stop(
              "supplied an unknown feature in interaction_constraints "
              , sQuote(constraint[is.na(constraint_indices)])
            )
          }

        } else {

          # Check that constraint indices are at most number of features
          if (max(constraint) > length(column_names)) {
            stop(
              "supplied a too large value in interaction_constraints: "
              , max(constraint)
              , " but only "
              , length(column_names)
              , " features"
            )
          }

          # Store indices as [0, n-1] indexed instead of [1, n] indexed
          constraint_indices <- as.integer(constraint - 1L)

        }

        # Convert constraint to string
        constraint_string <- paste0("[", paste0(constraint_indices, collapse = ","), "]")
        string_constraints <- append(string_constraints, constraint_string)
    }

  }

  return(string_constraints)

}

Guolin Ke's avatar
Guolin Ke committed
147
148

lgb.check.r6.class <- function(object, name) {
149

150
  # Check for non-existence of R6 class or named class
151
  return(all(c("R6", name) %in% class(object)))
152

Guolin Ke's avatar
Guolin Ke committed
153
154
155
}

lgb.check.obj <- function(params, obj) {
156

157
  # List known objectives in a vector
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
  OBJECTIVES <- c(
    "regression"
    , "regression_l1"
    , "regression_l2"
    , "mean_squared_error"
    , "mse"
    , "l2_root"
    , "root_mean_squared_error"
    , "rmse"
    , "mean_absolute_error"
    , "mae"
    , "quantile"
    , "huber"
    , "fair"
    , "poisson"
    , "binary"
    , "lambdarank"
    , "multiclass"
    , "softmax"
    , "multiclassova"
    , "multiclass_ova"
    , "ova"
    , "ovr"
    , "xentropy"
    , "cross_entropy"
    , "xentlambda"
    , "cross_entropy_lambda"
    , "mean_absolute_percentage_error"
    , "mape"
    , "gamma"
    , "tweedie"
189
190
191
192
193
    , "rank_xendcg"
    , "xendcg"
    , "xe_ndcg"
    , "xe_ndcg_mart"
    , "xendcg_mart"
194
  )
195

196
  # Check whether the objective is empty or not, and take it from params if needed
197
198
199
  if (!is.null(obj)) {
    params$objective <- obj
  }
200

201
  # Check whether the objective is a character
202
  if (is.character(params$objective)) {
203

204
    # If the objective is a character, check if it is a known objective
205
    if (!(params$objective %in% OBJECTIVES)) {
206

207
      stop("lgb.check.obj: objective name error should be one of (", paste0(OBJECTIVES, collapse = ", "), ")")
208

Guolin Ke's avatar
Guolin Ke committed
209
    }
210

211
  } else if (!is.function(params$objective)) {
212

213
    stop("lgb.check.obj: objective should be a character or a function")
214

Guolin Ke's avatar
Guolin Ke committed
215
  }
216

217
  return(params)
218

Guolin Ke's avatar
Guolin Ke committed
219
220
}

221
# [description]
222
223
224
225
#     Take any character values from eval and store them in params$metric.
#     This has to account for the fact that `eval` could be a character vector,
#     a function, a list of functions, or a list with a mix of strings and
#     functions
Guolin Ke's avatar
Guolin Ke committed
226
lgb.check.eval <- function(params, eval) {
227

228
229
  if (is.null(params$metric)) {
    params$metric <- list()
230
231
  } else if (is.character(params$metric)) {
    params$metric <- as.list(params$metric)
232
  }
233

234
235
236
237
238
239
240
241
242
  # if 'eval' is a character vector or list, find the character
  # elements and add them to 'metric'
  if (!is.function(eval)) {
    for (i in seq_along(eval)) {
      element <- eval[[i]]
      if (is.character(element)) {
        params$metric <- append(params$metric, element)
      }
    }
243
  }
244

245
246
247
248
249
250
251
252
253
  # If more than one character metric was given, then "None" should
  # not be included
  if (length(params$metric) > 1L) {
    params$metric <- Filter(
        f = function(metric) {
          !(metric %in% .NO_METRIC_STRINGS())
        }
        , x = params$metric
    )
254
255
  }

256
257
258
  # duplicate metrics should be filtered out
  params$metric <- as.list(unique(unlist(params$metric)))

259
  return(params)
Guolin Ke's avatar
Guolin Ke committed
260
}
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319


# [description]
#
#     Resolve differences between passed-in keyword arguments, parameters,
#     and parameter aliases. This function exists because some functions in the
#     package take in parameters through their own keyword arguments other than
#     the `params` list.
#
#     If the same underlying parameter is provided multiple
#     ways, the first item in this list is used:
#
#         1. the main (non-alias) parameter found in `params`
#         2. the first alias of that parameter found in `params`
#         3. the keyword argument passed in
#
#     For example, "num_iterations" can also be provided to lgb.train()
#     via keyword "nrounds". lgb.train() will choose one value for this parameter
#     based on the first match in this list:
#
#         1. params[["num_iterations]]
#         2. the first alias of "num_iterations" found in params
#         3. the nrounds keyword argument
#
#     If multiple aliases are found in `params` for the same parameter, they are
#     all removed before returning `params`.
#
# [return]
#     params with num_iterations set to the chosen value, and other aliases
#     of num_iterations removed
lgb.check.wrapper_param <- function(main_param_name, params, alternative_kwarg_value) {

  aliases <- .PARAMETER_ALIASES()[[main_param_name]]
  aliases_provided <- names(params)[names(params) %in% aliases]
  aliases_provided <- aliases_provided[aliases_provided != main_param_name]

  # prefer the main parameter
  if (!is.null(params[[main_param_name]])) {
    for (param in aliases_provided) {
      params[[param]] <- NULL
    }
    return(params)
  }

  # if the main parameter wasn't proovided, prefer the first alias
  if (length(aliases_provided) > 0L) {
    first_param <- aliases_provided[1L]
    params[[main_param_name]] <- params[[first_param]]
    for (param in aliases_provided) {
      params[[param]] <- NULL
    }
    return(params)
  }

  # if not provided in params at all, use the alternative value provided
  # through a keyword argument from lgb.train(), lgb.cv(), etc.
  params[[main_param_name]] <- alternative_kwarg_value
  return(params)
}