test_basic.R 109 KB
Newer Older
1
2
data(agaricus.train, package = "lightgbm")
data(agaricus.test, package = "lightgbm")
Guolin Ke's avatar
Guolin Ke committed
3
4
5
train <- agaricus.train
test <- agaricus.test

6
7
8
9
10
11
12
set.seed(708L)

# [description] Every time this function is called, it adds 0.1
#               to an accumulator then returns the current value.
#               This is used to mock the situation where an evaluation
#               metric increases every iteration
ACCUMULATOR_NAME <- "INCREASING_METRIC_ACUMULATOR"
13
assign(x = ACCUMULATOR_NAME, value = 0.0, envir = .GlobalEnv)
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

.increasing_metric <- function(preds, dtrain) {
  if (!exists(ACCUMULATOR_NAME, envir = .GlobalEnv)) {
    assign(ACCUMULATOR_NAME, 0.0, envir = .GlobalEnv)
  }
  assign(
    x = ACCUMULATOR_NAME
    , value = get(ACCUMULATOR_NAME, envir = .GlobalEnv) + 0.1
    , envir = .GlobalEnv
  )
  return(list(
    name = "increasing_metric"
    , value = get(ACCUMULATOR_NAME, envir = .GlobalEnv)
    , higher_better = TRUE
  ))
}

# [description] Evaluation function that always returns the
#               same value
CONSTANT_METRIC_VALUE <- 0.2
.constant_metric <- function(preds, dtrain) {
  return(list(
    name = "constant_metric"
    , value = CONSTANT_METRIC_VALUE
    , higher_better = FALSE
  ))
}

# sample datasets to test early stopping
DTRAIN_RANDOM_REGRESSION <- lgb.Dataset(
  data = as.matrix(rnorm(100L), ncol = 1L, drop = FALSE)
  , label = rnorm(100L)
46
  , params = list(num_threads = .LGB_MAX_THREADS)
47
48
49
50
)
DVALID_RANDOM_REGRESSION <- lgb.Dataset(
  data = as.matrix(rnorm(50L), ncol = 1L, drop = FALSE)
  , label = rnorm(50L)
51
  , params = list(num_threads = .LGB_MAX_THREADS)
52
53
54
55
)
DTRAIN_RANDOM_CLASSIFICATION <- lgb.Dataset(
  data = as.matrix(rnorm(120L), ncol = 1L, drop = FALSE)
  , label = sample(c(0L, 1L), size = 120L, replace = TRUE)
56
  , params = list(num_threads = .LGB_MAX_THREADS)
57
58
59
60
)
DVALID_RANDOM_CLASSIFICATION <- lgb.Dataset(
  data = as.matrix(rnorm(37L), ncol = 1L, drop = FALSE)
  , label = sample(c(0L, 1L), size = 37L, replace = TRUE)
61
  , params = list(num_threads = .LGB_MAX_THREADS)
62
)
63

Guolin Ke's avatar
Guolin Ke committed
64
test_that("train and predict binary classification", {
65
  nrounds <- 10L
66
67
68
  bst <- lightgbm(
    data = train$data
    , label = train$label
69
70
71
72
    , params = list(
        num_leaves = 5L
        , objective = "binary"
        , metric = "binary_error"
73
        , verbose = .LGB_VERBOSITY
74
        , num_threads = .LGB_MAX_THREADS
75
    )
76
    , nrounds = nrounds
77
78
79
80
81
82
    , valids = list(
      "train" = lgb.Dataset(
        data = train$data
        , label = train$label
      )
    )
83
  )
Guolin Ke's avatar
Guolin Ke committed
84
85
86
87
88
  expect_false(is.null(bst$record_evals))
  record_results <- lgb.get.eval.result(bst, "train", "binary_error")
  expect_lt(min(record_results), 0.02)

  pred <- predict(bst, test$data)
89
  expect_equal(length(pred), 1611L)
90

91
92
93
94
  pred1 <- predict(bst, train$data, num_iteration = 1L)
  expect_equal(length(pred1), 6513L)
  err_pred1 <- sum((pred1 > 0.5) != train$label) / length(train$label)
  err_log <- record_results[1L]
95
  expect_lt(abs(err_pred1 - err_log), .LGB_NUMERIC_TOLERANCE)
Guolin Ke's avatar
Guolin Ke committed
96
97
98
99
})


test_that("train and predict softmax", {
100
  set.seed(708L)
101
  X_mat <- as.matrix(iris[, -5L])
102
  lb <- as.numeric(iris$Species) - 1L
Guolin Ke's avatar
Guolin Ke committed
103

104
  bst <- lightgbm(
105
    data = X_mat
106
    , label = lb
107
108
109
110
111
112
113
114
    , params = list(
        num_leaves = 4L
        , learning_rate = 0.05
        , min_data = 20L
        , min_hessian = 10.0
        , objective = "multiclass"
        , metric = "multi_error"
        , num_class = 3L
115
        , verbose = .LGB_VERBOSITY
116
        , num_threads = .LGB_MAX_THREADS
117
    )
118
    , nrounds = 20L
119
120
121
122
123
124
    , valids = list(
      "train" = lgb.Dataset(
        data = X_mat
        , label = lb
      )
    )
125
  )
Guolin Ke's avatar
Guolin Ke committed
126
127
128

  expect_false(is.null(bst$record_evals))
  record_results <- lgb.get.eval.result(bst, "train", "multi_error")
129
  expect_lt(min(record_results), 0.06)
Guolin Ke's avatar
Guolin Ke committed
130

131
132
  pred <- predict(bst, as.matrix(iris[, -5L]))
  expect_equal(length(pred), nrow(iris) * 3L)
Guolin Ke's avatar
Guolin Ke committed
133
134
135
136
})


test_that("use of multiple eval metrics works", {
137
  metrics <- list("binary_error", "auc", "binary_logloss")
138
139
140
  bst <- lightgbm(
    data = train$data
    , label = train$label
141
142
143
144
145
    , params = list(
        num_leaves = 4L
        , learning_rate = 1.0
        , objective = "binary"
        , metric = metrics
146
        , verbose = .LGB_VERBOSITY
147
        , num_threads = .LGB_MAX_THREADS
148
    )
149
    , nrounds = 10L
150
151
152
153
    , valids = list(
      "train" = lgb.Dataset(
        data = train$data
        , label = train$label
154
        , params = list(num_threads = .LGB_MAX_THREADS)
155
156
      )
    )
157
  )
Guolin Ke's avatar
Guolin Ke committed
158
  expect_false(is.null(bst$record_evals))
159
160
161
162
163
164
  expect_named(
    bst$record_evals[["train"]]
    , unlist(metrics)
    , ignore.order = FALSE
    , ignore.case = FALSE
  )
Guolin Ke's avatar
Guolin Ke committed
165
166
})

167
168
169
170
171
172
test_that("lgb.Booster.upper_bound() and lgb.Booster.lower_bound() work as expected for binary classification", {
  set.seed(708L)
  nrounds <- 10L
  bst <- lightgbm(
    data = train$data
    , label = train$label
173
174
175
176
    , params = list(
        num_leaves = 5L
        , objective = "binary"
        , metric = "binary_error"
177
        , verbose = .LGB_VERBOSITY
178
        , num_threads = .LGB_MAX_THREADS
179
    )
180
181
    , nrounds = nrounds
  )
182
183
  expect_true(abs(bst$lower_bound() - -1.590853) < .LGB_NUMERIC_TOLERANCE)
  expect_true(abs(bst$upper_bound() - 1.871015) <  .LGB_NUMERIC_TOLERANCE)
184
185
186
187
188
189
190
191
})

test_that("lgb.Booster.upper_bound() and lgb.Booster.lower_bound() work as expected for regression", {
  set.seed(708L)
  nrounds <- 10L
  bst <- lightgbm(
    data = train$data
    , label = train$label
192
193
194
195
    , params = list(
        num_leaves = 5L
        , objective = "regression"
        , metric = "l2"
196
        , verbose = .LGB_VERBOSITY
197
        , num_threads = .LGB_MAX_THREADS
198
    )
199
200
    , nrounds = nrounds
  )
201
202
  expect_true(abs(bst$lower_bound() - 0.1513859) < .LGB_NUMERIC_TOLERANCE)
  expect_true(abs(bst$upper_bound() - 0.9080349) < .LGB_NUMERIC_TOLERANCE)
203
204
})

205
206
test_that("lightgbm() rejects negative or 0 value passed to nrounds", {
  dtrain <- lgb.Dataset(train$data, label = train$label)
207
  params <- list(objective = "regression", metric = "l2,l1", num_threads = .LGB_MAX_THREADS)
208
209
210
211
212
213
214
215
216
217
218
  for (nround_value in c(-10L, 0L)) {
    expect_error({
      bst <- lightgbm(
        data = dtrain
        , params = params
        , nrounds = nround_value
      )
    }, "nrounds should be greater than zero")
  }
})

219
220
221
222
223
224
225
226
227
228
229
230
test_that("lightgbm() accepts nrounds as either a top-level argument or parameter", {
  nrounds <- 15L

  set.seed(708L)
  top_level_bst <- lightgbm(
    data = train$data
    , label = train$label
    , nrounds = nrounds
    , params = list(
      objective = "regression"
      , metric = "l2"
      , num_leaves = 5L
231
      , verbose = .LGB_VERBOSITY
232
      , num_threads = .LGB_MAX_THREADS
233
234
235
236
237
238
239
240
241
242
243
244
    )
  )

  set.seed(708L)
  param_bst <- lightgbm(
    data = train$data
    , label = train$label
    , params = list(
      objective = "regression"
      , metric = "l2"
      , num_leaves = 5L
      , nrounds = nrounds
245
      , verbose = .LGB_VERBOSITY
246
      , num_threads = .LGB_MAX_THREADS
247
248
249
250
251
252
253
254
255
256
257
258
259
    )
  )

  set.seed(708L)
  both_customized <- lightgbm(
    data = train$data
    , label = train$label
    , nrounds = 20L
    , params = list(
      objective = "regression"
      , metric = "l2"
      , num_leaves = 5L
      , nrounds = nrounds
260
      , verbose = .LGB_VERBOSITY
261
      , num_threads = .LGB_MAX_THREADS
262
263
264
265
    )
  )

  top_level_l2 <- top_level_bst$eval_train()[[1L]][["value"]]
266
267
  params_l2 <- param_bst$eval_train()[[1L]][["value"]]
  both_l2 <- both_customized$eval_train()[[1L]][["value"]]
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283

  # check type just to be sure the subsetting didn't return a NULL
  expect_true(is.numeric(top_level_l2))
  expect_true(is.numeric(params_l2))
  expect_true(is.numeric(both_l2))

  # check that model produces identical performance
  expect_identical(top_level_l2, params_l2)
  expect_identical(both_l2, params_l2)

  expect_identical(param_bst$current_iter(), top_level_bst$current_iter())
  expect_identical(param_bst$current_iter(), both_customized$current_iter())
  expect_identical(param_bst$current_iter(), nrounds)

})

284
285
286
287
test_that("lightgbm() performs evaluation on validation sets if they are provided", {
  set.seed(708L)
  dvalid1 <- lgb.Dataset(
    data = train$data
288
    , label = train$label
289
    , params = list(num_threads = .LGB_MAX_THREADS)
290
291
292
  )
  dvalid2 <- lgb.Dataset(
    data = train$data
293
    , label = train$label
294
    , params = list(num_threads = .LGB_MAX_THREADS)
295
296
297
298
299
  )
  nrounds <- 10L
  bst <- lightgbm(
    data = train$data
    , label = train$label
300
301
302
303
304
305
306
    , params = list(
        num_leaves = 5L
        , objective = "binary"
        , metric = c(
            "binary_error"
            , "auc"
        )
307
        , verbose = .LGB_VERBOSITY
308
        , num_threads = .LGB_MAX_THREADS
309
    )
310
    , nrounds = nrounds
311
312
313
    , valids = list(
      "valid1" = dvalid1
      , "valid2" = dvalid2
314
315
316
      , "train" = lgb.Dataset(
        data = train$data
        , label = train$label
317
        , params = list(num_threads = .LGB_MAX_THREADS)
318
      )
319
320
321
322
323
324
325
326
327
328
329
330
331
    )
  )

  expect_named(
    bst$record_evals
    , c("train", "valid1", "valid2", "start_iter")
    , ignore.order = TRUE
    , ignore.case = FALSE
  )
  for (valid_name in c("train", "valid1", "valid2")) {
    eval_results <- bst$record_evals[[valid_name]][["binary_error"]]
    expect_length(eval_results[["eval"]], nrounds)
  }
332
333
334
  expect_true(abs(bst$record_evals[["train"]][["binary_error"]][["eval"]][[1L]] - 0.02226317) < .LGB_NUMERIC_TOLERANCE)
  expect_true(abs(bst$record_evals[["valid1"]][["binary_error"]][["eval"]][[1L]] - 0.02226317) < .LGB_NUMERIC_TOLERANCE)
  expect_true(abs(bst$record_evals[["valid2"]][["binary_error"]][["eval"]][[1L]] - 0.02226317) < .LGB_NUMERIC_TOLERANCE)
335
336
})

Guolin Ke's avatar
Guolin Ke committed
337
test_that("training continuation works", {
338
339
340
341
  dtrain <- lgb.Dataset(
    train$data
    , label = train$label
    , free_raw_data = FALSE
342
    , params = list(num_threads = .LGB_MAX_THREADS)
343
  )
344
  watchlist <- list(train = dtrain)
345
346
347
  param <- list(
    objective = "binary"
    , metric = "binary_logloss"
348
349
    , num_leaves = 5L
    , learning_rate = 1.0
350
    , verbose = .LGB_VERBOSITY
351
    , num_threads = .LGB_MAX_THREADS
352
  )
Guolin Ke's avatar
Guolin Ke committed
353

354
  # train for 10 consecutive iterations
355
356
  bst <- lgb.train(param, dtrain, nrounds = 10L, watchlist)
  err_bst <- lgb.get.eval.result(bst, "train", "binary_logloss", 10L)
357
358

  #  train for 5 iterations, save, load, train for 5 more
359
  bst1 <- lgb.train(param, dtrain, nrounds = 5L, watchlist)
360
361
  model_file <- tempfile(fileext = ".model")
  lgb.save(bst1, model_file)
362
363
  bst2 <- lgb.train(param, dtrain, nrounds = 5L, watchlist, init_model = bst1)
  err_bst2 <- lgb.get.eval.result(bst2, "train", "binary_logloss", 10L)
Guolin Ke's avatar
Guolin Ke committed
364

365
366
  # evaluation metrics should be nearly identical for the model trained in 10 coonsecutive
  # iterations and the one trained in 5-then-5.
Guolin Ke's avatar
Guolin Ke committed
367
368
369
  expect_lt(abs(err_bst - err_bst2), 0.01)
})

Guolin Ke's avatar
Guolin Ke committed
370
test_that("cv works", {
371
  dtrain <- lgb.Dataset(train$data, label = train$label)
372
373
374
375
376
  params <- list(
    objective = "regression"
    , metric = "l2,l1"
    , min_data = 1L
    , learning_rate = 1.0
377
    , verbose = .LGB_VERBOSITY
378
    , num_threads = .LGB_MAX_THREADS
379
  )
380
381
382
  bst <- lgb.cv(
    params
    , dtrain
383
384
385
    , 10L
    , nfold = 5L
    , early_stopping_rounds = 10L
386
  )
Guolin Ke's avatar
Guolin Ke committed
387
388
  expect_false(is.null(bst$record_evals))
})
389

390
391
392
393
394
395
396
397
test_that("CVBooster$reset_parameter() works as expected", {
  dtrain <- lgb.Dataset(train$data, label = train$label)
  n_folds <- 2L
  cv_bst <- lgb.cv(
    params = list(
      objective = "regression"
      , min_data = 1L
      , num_leaves = 7L
398
      , verbose = .LGB_VERBOSITY
399
      , num_threads = .LGB_MAX_THREADS
400
401
402
403
404
    )
    , data = dtrain
    , nrounds = 3L
    , nfold = n_folds
  )
405
  expect_true(methods::is(cv_bst, "lgb.CVBooster"))
406
407
408
409
410
411
412
413
414
415
  expect_length(cv_bst$boosters, n_folds)
  for (bst in cv_bst$boosters) {
    expect_equal(bst[["booster"]]$params[["num_leaves"]], 7L)
  }
  cv_bst$reset_parameter(list(num_leaves = 11L))
  for (bst in cv_bst$boosters) {
    expect_equal(bst[["booster"]]$params[["num_leaves"]], 11L)
  }
})

416
test_that("lgb.cv() rejects negative or 0 value passed to nrounds", {
417
  dtrain <- lgb.Dataset(train$data, label = train$label, params = list(num_threads = 2L))
418
419
420
421
  params <- list(
    objective = "regression"
    , metric = "l2,l1"
    , min_data = 1L
422
    , num_threads = .LGB_MAX_THREADS
423
  )
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
  for (nround_value in c(-10L, 0L)) {
    expect_error({
      bst <- lgb.cv(
        params
        , dtrain
        , nround_value
        , nfold = 5L
      )
    }, "nrounds should be greater than zero")
  }
})

test_that("lgb.cv() throws an informative error is 'data' is not an lgb.Dataset and labels are not given", {
  bad_values <- list(
    4L
    , "hello"
    , list(a = TRUE, b = seq_len(10L))
    , data.frame(x = seq_len(5L), y = seq_len(5L))
    , data.table::data.table(x = seq_len(5L),  y = seq_len(5L))
    , matrix(data = seq_len(10L), 2L, 5L)
  )
  for (val in bad_values) {
    expect_error({
      bst <- lgb.cv(
448
449
450
451
452
        params = list(
            objective = "regression"
            , metric = "l2,l1"
            , min_data = 1L
        )
453
454
455
456
457
458
459
460
        , data = val
        , 10L
        , nfold = 5L
      )
    }, regexp = "'label' must be provided for lgb.cv if 'data' is not an 'lgb.Dataset'", fixed = TRUE)
  }
})

461
462
463
464
465
test_that("lightgbm.cv() gives the correct best_score and best_iter for a metric where higher values are better", {
  set.seed(708L)
  dtrain <- lgb.Dataset(
    data = as.matrix(runif(n = 500L, min = 0.0, max = 15.0), drop = FALSE)
    , label = rep(c(0L, 1L), 250L)
466
    , params = list(num_threads = .LGB_MAX_THREADS)
467
468
469
470
471
472
473
474
475
476
  )
  nrounds <- 10L
  cv_bst <- lgb.cv(
    data = dtrain
    , nfold = 5L
    , nrounds = nrounds
    , params = list(
      objective = "binary"
      , metric = "auc,binary_error"
      , learning_rate = 1.5
477
      , num_leaves = 5L
478
      , verbose = .LGB_VERBOSITY
479
      , num_threads = .LGB_MAX_THREADS
480
481
    )
  )
482
  expect_true(methods::is(cv_bst, "lgb.CVBooster"))
483
484
485
486
487
488
489
490
491
492
493
494
  expect_named(
    cv_bst$record_evals
    , c("start_iter", "valid")
    , ignore.order = FALSE
    , ignore.case = FALSE
  )
  auc_scores <- unlist(cv_bst$record_evals[["valid"]][["auc"]][["eval"]])
  expect_length(auc_scores, nrounds)
  expect_identical(cv_bst$best_iter, which.max(auc_scores))
  expect_identical(cv_bst$best_score, auc_scores[which.max(auc_scores)])
})

495
496
497
498
499
500
501
test_that("lgb.cv() fit on linearly-relatead data improves when using linear learners", {
  set.seed(708L)
  .new_dataset <- function() {
    X <- matrix(rnorm(1000L), ncol = 1L)
    return(lgb.Dataset(
      data = X
      , label = 2L * X + runif(nrow(X), 0L, 0.1)
502
      , params = list(num_threads = .LGB_MAX_THREADS)
503
504
505
506
507
508
509
510
511
    ))
  }

  params <- list(
    objective = "regression"
    , verbose = -1L
    , metric = "mse"
    , seed = 0L
    , num_leaves = 2L
512
    , num_threads = .LGB_MAX_THREADS
513
514
515
516
517
518
519
520
521
  )

  dtrain <- .new_dataset()
  cv_bst <- lgb.cv(
    data = dtrain
    , nrounds = 10L
    , params = params
    , nfold = 5L
  )
522
  expect_true(methods::is(cv_bst, "lgb.CVBooster"))
523
524
525
526
527

  dtrain <- .new_dataset()
  cv_bst_linear <- lgb.cv(
    data = dtrain
    , nrounds = 10L
528
    , params = utils::modifyList(params, list(linear_tree = TRUE))
529
530
    , nfold = 5L
  )
531
  expect_true(methods::is(cv_bst_linear, "lgb.CVBooster"))
532
533
534
535

  expect_true(cv_bst_linear$best_score < cv_bst$best_score)
})

536
test_that("lgb.cv() respects showsd argument", {
537
  dtrain <- lgb.Dataset(train$data, label = train$label, params = list(num_threads = .LGB_MAX_THREADS))
538
539
540
541
  params <- list(
    objective = "regression"
    , metric = "l2"
    , min_data = 1L
542
    , verbose = .LGB_VERBOSITY
543
    , num_threads = .LGB_MAX_THREADS
544
  )
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
  nrounds <- 5L
  set.seed(708L)
  bst_showsd <- lgb.cv(
    params = params
    , data = dtrain
    , nrounds = nrounds
    , nfold = 3L
    , showsd = TRUE
  )
  evals_showsd <- bst_showsd$record_evals[["valid"]][["l2"]]
  set.seed(708L)
  bst_no_showsd <- lgb.cv(
    params = params
    , data = dtrain
    , nrounds = nrounds
    , nfold = 3L
    , showsd = FALSE
  )
  evals_no_showsd <- bst_no_showsd$record_evals[["valid"]][["l2"]]
  expect_equal(
    evals_showsd[["eval"]]
    , evals_no_showsd[["eval"]]
  )
568
  expect_true(methods::is(evals_showsd[["eval_err"]], "list"))
569
570
571
572
  expect_equal(length(evals_showsd[["eval_err"]]), nrounds)
  expect_identical(evals_no_showsd[["eval_err"]], list())
})

573
574
575
576
test_that("lgb.cv() raises an informative error for unrecognized objectives", {
  dtrain <- lgb.Dataset(
    data = train$data
    , label = train$label
577
    , params = list(num_threads = .LGB_MAX_THREADS)
578
579
  )
  expect_error({
580
581
582
583
584
    capture.output({
      bst <- lgb.cv(
        data = dtrain
        , params = list(
          objective_type = "not_a_real_objective"
585
          , verbosity = .LGB_VERBOSITY
586
          , num_threads = .LGB_MAX_THREADS
587
        )
588
      )
589
    }, type = "message")
590
591
592
  }, regexp = "Unknown objective type name: not_a_real_objective")
})

593
594
595
596
597
598
test_that("lgb.cv() respects parameter aliases for objective", {
  nrounds <- 3L
  nfold <- 4L
  dtrain <- lgb.Dataset(
    data = train$data
    , label = train$label
599
    , params = list(num_threads = .LGB_MAX_THREADS)
600
601
602
603
604
605
606
  )
  cv_bst <- lgb.cv(
    data = dtrain
    , params = list(
      num_leaves = 5L
      , application = "binary"
      , num_iterations = nrounds
607
      , verbose = .LGB_VERBOSITY
608
      , num_threads = .LGB_MAX_THREADS
609
610
611
612
613
614
615
616
617
    )
    , nfold = nfold
  )
  expect_equal(cv_bst$best_iter, nrounds)
  expect_named(cv_bst$record_evals[["valid"]], "binary_logloss")
  expect_length(cv_bst$record_evals[["valid"]][["binary_logloss"]][["eval"]], nrounds)
  expect_length(cv_bst$boosters, nfold)
})

618
619
620
621
622
623
test_that("lgb.cv() prefers objective in params to keyword argument", {
  data("EuStockMarkets")
  cv_bst <- lgb.cv(
    data = lgb.Dataset(
      data = EuStockMarkets[, c("SMI", "CAC", "FTSE")]
      , label = EuStockMarkets[, "DAX"]
624
      , params = list(num_threads = .LGB_MAX_THREADS)
625
626
627
    )
    , params = list(
      application = "regression_l1"
628
      , verbosity = .LGB_VERBOSITY
629
      , num_threads = .LGB_MAX_THREADS
630
631
632
633
634
635
636
637
638
639
640
641
    )
    , nrounds = 5L
    , obj = "regression_l2"
  )
  for (bst_list in cv_bst$boosters) {
    bst <- bst_list[["booster"]]
    expect_equal(bst$params$objective, "regression_l1")
    # NOTE: using save_model_to_string() since that is the simplest public API in the R package
    #       allowing access to the "objective" attribute of the Booster object on the C++ side
    model_txt_lines <- strsplit(
      x = bst$save_model_to_string()
      , split = "\n"
642
      , fixed = TRUE
643
644
645
646
647
648
    )[[1L]]
    expect_true(any(model_txt_lines == "objective=regression_l1"))
    expect_false(any(model_txt_lines == "objective=regression_l2"))
  }
})

649
650
651
652
653
654
test_that("lgb.cv() respects parameter aliases for metric", {
  nrounds <- 3L
  nfold <- 4L
  dtrain <- lgb.Dataset(
    data = train$data
    , label = train$label
655
    , params = list(num_threads = .LGB_MAX_THREADS)
656
657
658
659
660
661
662
663
  )
  cv_bst <- lgb.cv(
    data = dtrain
    , params = list(
      num_leaves = 5L
      , objective = "binary"
      , num_iterations = nrounds
      , metric_types = c("auc", "binary_logloss")
664
      , verbose = .LGB_VERBOSITY
665
      , num_threads = .LGB_MAX_THREADS
666
667
668
669
670
671
672
673
674
675
    )
    , nfold = nfold
  )
  expect_equal(cv_bst$best_iter, nrounds)
  expect_named(cv_bst$record_evals[["valid"]], c("auc", "binary_logloss"))
  expect_length(cv_bst$record_evals[["valid"]][["binary_logloss"]][["eval"]], nrounds)
  expect_length(cv_bst$record_evals[["valid"]][["auc"]][["eval"]], nrounds)
  expect_length(cv_bst$boosters, nfold)
})

676
677
678
679
680
681
test_that("lgb.cv() respects eval_train_metric argument", {
  dtrain <- lgb.Dataset(train$data, label = train$label)
  params <- list(
    objective = "regression"
    , metric = "l2"
    , min_data = 1L
682
    , verbose = .LGB_VERBOSITY
683
    , num_threads = .LGB_MAX_THREADS
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
  )
  nrounds <- 5L
  set.seed(708L)
  bst_train <- lgb.cv(
    params = params
    , data = dtrain
    , nrounds = nrounds
    , nfold = 3L
    , showsd = FALSE
    , eval_train_metric = TRUE
  )
  set.seed(708L)
  bst_no_train <- lgb.cv(
    params = params
    , data = dtrain
    , nrounds = nrounds
    , nfold = 3L
    , showsd = FALSE
    , eval_train_metric = FALSE
  )
  expect_equal(
    bst_train$record_evals[["valid"]][["l2"]]
    , bst_no_train$record_evals[["valid"]][["l2"]]
  )
  expect_true("train" %in% names(bst_train$record_evals))
  expect_false("train" %in% names(bst_no_train$record_evals))
  expect_true(methods::is(bst_train$record_evals[["train"]][["l2"]][["eval"]], "list"))
  expect_equal(
    length(bst_train$record_evals[["train"]][["l2"]][["eval"]])
    , nrounds
  )
})

717
718
719
720
721
722
test_that("lgb.train() works as expected with multiple eval metrics", {
  metrics <- c("binary_error", "auc", "binary_logloss")
  bst <- lgb.train(
    data = lgb.Dataset(
      train$data
      , label = train$label
723
      , params = list(num_threads = .LGB_MAX_THREADS)
724
725
726
727
728
    )
    , nrounds = 10L
    , params = list(
      objective = "binary"
      , metric = metrics
729
      , learning_rate = 1.0
730
      , verbose = .LGB_VERBOSITY
731
      , num_threads = .LGB_MAX_THREADS
732
733
734
735
736
    )
    , valids = list(
      "train" = lgb.Dataset(
        train$data
        , label = train$label
737
        , params = list(num_threads = .LGB_MAX_THREADS)
738
739
740
741
742
743
744
745
746
747
748
749
      )
    )
  )
  expect_false(is.null(bst$record_evals))
  expect_named(
    bst$record_evals[["train"]]
    , unlist(metrics)
    , ignore.order = FALSE
    , ignore.case = FALSE
  )
})

750
751
752
753
754
755
test_that("lgb.train() raises an informative error for unrecognized objectives", {
  dtrain <- lgb.Dataset(
    data = train$data
    , label = train$label
  )
  expect_error({
756
757
758
759
760
    capture.output({
      bst <- lgb.train(
        data = dtrain
        , params = list(
          objective_type = "not_a_real_objective"
761
          , verbosity = .LGB_VERBOSITY
762
        )
763
      )
764
    }, type = "message")
765
766
767
  }, regexp = "Unknown objective type name: not_a_real_objective")
})

768
769
770
771
772
test_that("lgb.train() respects parameter aliases for objective", {
  nrounds <- 3L
  dtrain <- lgb.Dataset(
    data = train$data
    , label = train$label
773
    , params = list(num_threads = .LGB_MAX_THREADS)
774
775
776
777
778
779
780
  )
  bst <- lgb.train(
    data = dtrain
    , params = list(
      num_leaves = 5L
      , application = "binary"
      , num_iterations = nrounds
781
      , verbose = .LGB_VERBOSITY
782
      , num_threads = .LGB_MAX_THREADS
783
784
785
786
787
788
789
790
791
792
    )
    , valids = list(
      "the_training_data" = dtrain
    )
  )
  expect_named(bst$record_evals[["the_training_data"]], "binary_logloss")
  expect_length(bst$record_evals[["the_training_data"]][["binary_logloss"]][["eval"]], nrounds)
  expect_equal(bst$params[["objective"]], "binary")
})

793
794
795
796
797
798
test_that("lgb.train() prefers objective in params to keyword argument", {
  data("EuStockMarkets")
  bst <- lgb.train(
    data = lgb.Dataset(
      data = EuStockMarkets[, c("SMI", "CAC", "FTSE")]
      , label = EuStockMarkets[, "DAX"]
799
      , params = list(num_threads = .LGB_MAX_THREADS)
800
801
802
    )
    , params = list(
        loss = "regression_l1"
803
        , verbosity = .LGB_VERBOSITY
804
        , num_threads = .LGB_MAX_THREADS
805
806
807
808
809
810
811
812
813
814
    )
    , nrounds = 5L
    , obj = "regression_l2"
  )
  expect_equal(bst$params$objective, "regression_l1")
  # NOTE: using save_model_to_string() since that is the simplest public API in the R package
  #       allowing access to the "objective" attribute of the Booster object on the C++ side
  model_txt_lines <- strsplit(
    x = bst$save_model_to_string()
    , split = "\n"
815
    , fixed = TRUE
816
817
818
819
820
  )[[1L]]
  expect_true(any(model_txt_lines == "objective=regression_l1"))
  expect_false(any(model_txt_lines == "objective=regression_l2"))
})

821
822
823
824
825
test_that("lgb.train() respects parameter aliases for metric", {
  nrounds <- 3L
  dtrain <- lgb.Dataset(
    data = train$data
    , label = train$label
826
    , params = list(num_threads = .LGB_MAX_THREADS)
827
828
829
830
831
832
833
834
  )
  bst <- lgb.train(
    data = dtrain
    , params = list(
      num_leaves = 5L
      , objective = "binary"
      , num_iterations = nrounds
      , metric_types = c("auc", "binary_logloss")
835
      , verbose = .LGB_VERBOSITY
836
      , num_threads = .LGB_MAX_THREADS
837
838
839
840
841
842
843
844
845
846
847
848
    )
    , valids = list(
      "train" = dtrain
    )
  )
  record_results <- bst$record_evals[["train"]]
  expect_equal(sort(names(record_results)), c("auc", "binary_logloss"))
  expect_length(record_results[["auc"]][["eval"]], nrounds)
  expect_length(record_results[["binary_logloss"]][["eval"]], nrounds)
  expect_equal(bst$params[["metric"]], list("auc", "binary_logloss"))
})

849
test_that("lgb.train() rejects negative or 0 value passed to nrounds", {
850
  dtrain <- lgb.Dataset(train$data, label = train$label, params = list(num_threads = .LGB_MAX_THREADS))
851
852
853
  params <- list(
    objective = "regression"
    , metric = "l2,l1"
854
    , verbose = .LGB_VERBOSITY
855
    , num_threads = .LGB_MAX_THREADS
856
  )
857
858
859
860
861
862
863
864
865
866
867
  for (nround_value in c(-10L, 0L)) {
    expect_error({
      bst <- lgb.train(
        params
        , dtrain
        , nround_value
      )
    }, "nrounds should be greater than zero")
  }
})

868
869
870
871
872
873
874
875
876

test_that("lgb.train() accepts nrounds as either a top-level argument or parameter", {
  nrounds <- 15L

  set.seed(708L)
  top_level_bst <- lgb.train(
    data = lgb.Dataset(
      train$data
      , label = train$label
877
      , params = list(num_threads = .LGB_MAX_THREADS)
878
879
880
881
882
883
    )
    , nrounds = nrounds
    , params = list(
      objective = "regression"
      , metric = "l2"
      , num_leaves = 5L
884
      , verbose = .LGB_VERBOSITY
885
      , num_threads = .LGB_MAX_THREADS
886
887
888
889
890
891
892
893
    )
  )

  set.seed(708L)
  param_bst <- lgb.train(
    data = lgb.Dataset(
      train$data
      , label = train$label
894
      , params = list(num_threads = .LGB_MAX_THREADS)
895
896
897
898
899
900
    )
    , params = list(
      objective = "regression"
      , metric = "l2"
      , num_leaves = 5L
      , nrounds = nrounds
901
      , verbose = .LGB_VERBOSITY
902
903
904
905
906
907
908
909
    )
  )

  set.seed(708L)
  both_customized <- lgb.train(
    data = lgb.Dataset(
      train$data
      , label = train$label
910
      , params = list(num_threads = .LGB_MAX_THREADS)
911
912
913
914
915
916
917
    )
    , nrounds = 20L
    , params = list(
      objective = "regression"
      , metric = "l2"
      , num_leaves = 5L
      , nrounds = nrounds
918
      , verbose = .LGB_VERBOSITY
919
      , num_threads = .LGB_MAX_THREADS
920
921
922
923
    )
  )

  top_level_l2 <- top_level_bst$eval_train()[[1L]][["value"]]
924
925
  params_l2 <- param_bst$eval_train()[[1L]][["value"]]
  both_l2 <- both_customized$eval_train()[[1L]][["value"]]
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942

  # check type just to be sure the subsetting didn't return a NULL
  expect_true(is.numeric(top_level_l2))
  expect_true(is.numeric(params_l2))
  expect_true(is.numeric(both_l2))

  # check that model produces identical performance
  expect_identical(top_level_l2, params_l2)
  expect_identical(both_l2, params_l2)

  expect_identical(param_bst$current_iter(), top_level_bst$current_iter())
  expect_identical(param_bst$current_iter(), both_customized$current_iter())
  expect_identical(param_bst$current_iter(), nrounds)

})


943
944
945
946
947
948
949
950
951
952
953
954
test_that("lgb.train() throws an informative error if 'data' is not an lgb.Dataset", {
  bad_values <- list(
    4L
    , "hello"
    , list(a = TRUE, b = seq_len(10L))
    , data.frame(x = seq_len(5L), y = seq_len(5L))
    , data.table::data.table(x = seq_len(5L),  y = seq_len(5L))
    , matrix(data = seq_len(10L), 2L, 5L)
  )
  for (val in bad_values) {
    expect_error({
      bst <- lgb.train(
955
956
957
        params = list(
            objective = "regression"
            , metric = "l2,l1"
958
            , verbose = .LGB_VERBOSITY
959
        )
960
961
962
963
964
965
966
967
968
969
970
971
972
973
        , data = val
        , 10L
      )
    }, regexp = "data must be an lgb.Dataset instance", fixed = TRUE)
  }
})

test_that("lgb.train() throws an informative error if 'valids' is not a list of lgb.Dataset objects", {
  valids <- list(
    "valid1" = data.frame(x = rnorm(5L), y = rnorm(5L))
    , "valid2" = data.frame(x = rnorm(5L), y = rnorm(5L))
  )
  expect_error({
    bst <- lgb.train(
974
975
976
      params = list(
        objective = "regression"
        , metric = "l2,l1"
977
        , verbose = .LGB_VERBOSITY
978
      )
979
980
981
982
983
984
985
986
987
988
989
990
991
992
      , data = lgb.Dataset(train$data, label = train$label)
      , 10L
      , valids = valids
    )
  }, regexp = "valids must be a list of lgb.Dataset elements")
})

test_that("lgb.train() errors if 'valids' is a list of lgb.Dataset objects but some do not have names", {
  valids <- list(
    "valid1" = lgb.Dataset(matrix(rnorm(10L), 5L, 2L))
    , lgb.Dataset(matrix(rnorm(10L), 2L, 5L))
  )
  expect_error({
    bst <- lgb.train(
993
994
995
      params = list(
        objective = "regression"
        , metric = "l2,l1"
996
        , verbose = .LGB_VERBOSITY
997
      )
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
      , data = lgb.Dataset(train$data, label = train$label)
      , 10L
      , valids = valids
    )
  }, regexp = "each element of valids must have a name")
})

test_that("lgb.train() throws an informative error if 'valids' contains lgb.Dataset objects but none have names", {
  valids <- list(
    lgb.Dataset(matrix(rnorm(10L), 5L, 2L))
    , lgb.Dataset(matrix(rnorm(10L), 2L, 5L))
  )
  expect_error({
    bst <- lgb.train(
1012
1013
1014
      params = list(
        objective = "regression"
        , metric = "l2,l1"
1015
        , verbose = .LGB_VERBOSITY
1016
    )
1017
1018
1019
1020
1021
1022
      , data = lgb.Dataset(train$data, label = train$label)
      , 10L
      , valids = valids
    )
  }, regexp = "each element of valids must have a name")
})
1023
1024
1025
1026
1027
1028
1029

test_that("lgb.train() works with force_col_wise and force_row_wise", {
  set.seed(1234L)
  nrounds <- 10L
  dtrain <- lgb.Dataset(
    train$data
    , label = train$label
1030
    , params = list(num_threads = .LGB_MAX_THREADS)
1031
1032
1033
1034
1035
  )
  params <- list(
    objective = "binary"
    , metric = "binary_error"
    , force_col_wise = TRUE
1036
    , verbose = .LGB_VERBOSITY
1037
    , num_threads = .LGB_MAX_THREADS
1038
  )
1039
  bst_col_wise <- lgb.train(
1040
1041
1042
1043
1044
1045
1046
1047
1048
    params = params
    , data = dtrain
    , nrounds = nrounds
  )

  params <- list(
    objective = "binary"
    , metric = "binary_error"
    , force_row_wise = TRUE
1049
    , verbose = .LGB_VERBOSITY
1050
    , num_threads = .LGB_MAX_THREADS
1051
1052
1053
1054
1055
1056
1057
1058
  )
  bst_row_wise <- lgb.train(
    params = params
    , data = dtrain
    , nrounds = nrounds
  )

  expected_error <- 0.003070782
1059
  expect_equal(bst_col_wise$eval_train()[[1L]][["value"]], expected_error)
1060
1061
1062
1063
  expect_equal(bst_row_wise$eval_train()[[1L]][["value"]], expected_error)

  # check some basic details of the boosters just to be sure force_col_wise
  # and force_row_wise are not causing any weird side effects
1064
  for (bst in list(bst_row_wise, bst_col_wise)) {
1065
1066
1067
1068
1069
1070
    expect_equal(bst$current_iter(), nrounds)
    parsed_model <- jsonlite::fromJSON(bst$dump_model())
    expect_equal(parsed_model$objective, "binary sigmoid:1")
    expect_false(parsed_model$average_output)
  }
})
1071
1072
1073
1074
1075
1076

test_that("lgb.train() works as expected with sparse features", {
  set.seed(708L)
  num_obs <- 70000L
  trainDF <- data.frame(
    y = sample(c(0L, 1L), size = num_obs, replace = TRUE)
Nikita Titov's avatar
Nikita Titov committed
1077
    , x = sample(c(1.0:10.0, rep(NA_real_, 50L)), size = num_obs, replace = TRUE)
1078
1079
1080
1081
  )
  dtrain <- lgb.Dataset(
    data = as.matrix(trainDF[["x"]], drop = FALSE)
    , label = trainDF[["y"]]
1082
    , params = list(num_threads = .LGB_MAX_THREADS)
1083
1084
1085
1086
1087
1088
1089
  )
  nrounds <- 1L
  bst <- lgb.train(
    params = list(
      objective = "binary"
      , min_data = 1L
      , min_data_in_bin = 1L
1090
      , verbose = .LGB_VERBOSITY
1091
      , num_threads = .LGB_MAX_THREADS
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
    )
    , data = dtrain
    , nrounds = nrounds
  )

  expect_true(lgb.is.Booster(bst))
  expect_equal(bst$current_iter(), nrounds)
  parsed_model <- jsonlite::fromJSON(bst$dump_model())
  expect_equal(parsed_model$objective, "binary sigmoid:1")
  expect_false(parsed_model$average_output)
  expected_error <- 0.6931268
1103
  expect_true(abs(bst$eval_train()[[1L]][["value"]] - expected_error) < .LGB_NUMERIC_TOLERANCE)
1104
})
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117

test_that("lgb.train() works with early stopping for classification", {
  trainDF <- data.frame(
    "feat1" = rep(c(5.0, 10.0), 500L)
    , "target" = rep(c(0L, 1L), 500L)
  )
  validDF <- data.frame(
    "feat1" = rep(c(5.0, 10.0), 50L)
    , "target" = rep(c(0L, 1L), 50L)
  )
  dtrain <- lgb.Dataset(
    data = as.matrix(trainDF[["feat1"]], drop = FALSE)
    , label = trainDF[["target"]]
1118
    , params = list(num_threads = .LGB_MAX_THREADS)
1119
1120
1121
1122
  )
  dvalid <- lgb.Dataset(
    data = as.matrix(validDF[["feat1"]], drop = FALSE)
    , label = validDF[["target"]]
1123
    , params = list(num_threads = .LGB_MAX_THREADS)
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
  )
  nrounds <- 10L

  ################################
  # train with no early stopping #
  ################################
  bst <- lgb.train(
    params = list(
      objective = "binary"
      , metric = "binary_error"
1134
      , verbose = .LGB_VERBOSITY
1135
      , num_threads = .LGB_MAX_THREADS
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
    )
    , data = dtrain
    , nrounds = nrounds
    , valids = list(
      "valid1" = dvalid
    )
  )

  # a perfect model should be trivial to obtain, but all 10 rounds
  # should happen
  expect_equal(bst$best_score, 0.0)
  expect_equal(bst$best_iter, 1L)
  expect_equal(length(bst$record_evals[["valid1"]][["binary_error"]][["eval"]]), nrounds)

  #############################
  # train with early stopping #
  #############################
  early_stopping_rounds <- 5L
1154
  bst <- lgb.train(
1155
1156
1157
1158
    params = list(
      objective = "binary"
      , metric = "binary_error"
      , early_stopping_rounds = early_stopping_rounds
1159
      , verbose = .LGB_VERBOSITY
1160
      , num_threads = .LGB_MAX_THREADS
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
    )
    , data = dtrain
    , nrounds = nrounds
    , valids = list(
      "valid1" = dvalid
    )
  )

  # a perfect model should be trivial to obtain, and only 6 rounds
  # should have happen (1 with improvement, 5 consecutive with no improvement)
  expect_equal(bst$best_score, 0.0)
  expect_equal(bst$best_iter, 1L)
  expect_equal(
    length(bst$record_evals[["valid1"]][["binary_error"]][["eval"]])
    , early_stopping_rounds + 1L
  )

})

1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
test_that("lgb.train() treats early_stopping_rounds<=0 as disabling early stopping", {
  set.seed(708L)
  trainDF <- data.frame(
    "feat1" = rep(c(5.0, 10.0), 500L)
    , "target" = rep(c(0L, 1L), 500L)
  )
  validDF <- data.frame(
    "feat1" = rep(c(5.0, 10.0), 50L)
    , "target" = rep(c(0L, 1L), 50L)
  )
  dtrain <- lgb.Dataset(
    data = as.matrix(trainDF[["feat1"]], drop = FALSE)
    , label = trainDF[["target"]]
1193
    , params = list(num_threads = .LGB_MAX_THREADS)
1194
1195
1196
1197
  )
  dvalid <- lgb.Dataset(
    data = as.matrix(validDF[["feat1"]], drop = FALSE)
    , label = validDF[["target"]]
1198
    , params = list(num_threads = .LGB_MAX_THREADS)
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
  )
  nrounds <- 5L

  for (value in c(-5L, 0L)) {

    #----------------------------#
    # passed as keyword argument #
    #----------------------------#
    bst <- lgb.train(
      params = list(
        objective = "binary"
        , metric = "binary_error"
1211
        , verbose = .LGB_VERBOSITY
1212
        , num_threads = .LGB_MAX_THREADS
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
      )
      , data = dtrain
      , nrounds = nrounds
      , valids = list(
        "valid1" = dvalid
      )
      , early_stopping_rounds = value
    )

    # a perfect model should be trivial to obtain, but all 10 rounds
    # should happen
    expect_equal(bst$best_score, 0.0)
    expect_equal(bst$best_iter, 1L)
    expect_equal(length(bst$record_evals[["valid1"]][["binary_error"]][["eval"]]), nrounds)

    #---------------------------#
    # passed as parameter alias #
    #---------------------------#
    bst <- lgb.train(
      params = list(
        objective = "binary"
        , metric = "binary_error"
        , n_iter_no_change = value
1236
        , verbose = .LGB_VERBOSITY
1237
        , num_threads = .LGB_MAX_THREADS
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
      )
      , data = dtrain
      , nrounds = nrounds
      , valids = list(
        "valid1" = dvalid
      )
    )

    # a perfect model should be trivial to obtain, but all 10 rounds
    # should happen
    expect_equal(bst$best_score, 0.0)
    expect_equal(bst$best_iter, 1L)
    expect_equal(length(bst$record_evals[["valid1"]][["binary_error"]][["eval"]]), nrounds)
  }
})

1254
1255
1256
1257
1258
test_that("lgb.train() works with early stopping for classification with a metric that should be maximized", {
  set.seed(708L)
  dtrain <- lgb.Dataset(
    data = train$data
    , label = train$label
1259
    , params = list(num_threads = .LGB_MAX_THREADS)
1260
1261
1262
1263
  )
  dvalid <- lgb.Dataset(
    data = test$data
    , label = test$label
1264
    , params = list(num_threads = .LGB_MAX_THREADS)
1265
1266
1267
1268
1269
1270
1271
1272
  )
  nrounds <- 10L

  #############################
  # train with early stopping #
  #############################
  early_stopping_rounds <- 5L
  # the harsh max_depth guarantees that AUC improves over at least the first few iterations
1273
  bst_auc <- lgb.train(
1274
1275
1276
1277
1278
    params = list(
      objective = "binary"
      , metric = "auc"
      , max_depth = 3L
      , early_stopping_rounds = early_stopping_rounds
1279
      , verbose = .LGB_VERBOSITY
1280
      , num_threads = .LGB_MAX_THREADS
1281
1282
1283
1284
1285
1286
1287
    )
    , data = dtrain
    , nrounds = nrounds
    , valids = list(
      "valid1" = dvalid
    )
  )
1288
  bst_binary_error <- lgb.train(
1289
1290
1291
1292
1293
    params = list(
      objective = "binary"
      , metric = "binary_error"
      , max_depth = 3L
      , early_stopping_rounds = early_stopping_rounds
1294
      , verbose = .LGB_VERBOSITY
1295
      , num_threads = .LGB_MAX_THREADS
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
    )
    , data = dtrain
    , nrounds = nrounds
    , valids = list(
      "valid1" = dvalid
    )
  )

  # early stopping should have been hit for binary_error (higher_better = FALSE)
  eval_info <- bst_binary_error$.__enclos_env__$private$get_eval_info()
  expect_identical(eval_info, "binary_error")
  expect_identical(
    unname(bst_binary_error$.__enclos_env__$private$higher_better_inner_eval)
    , FALSE
  )
  expect_identical(bst_binary_error$best_iter, 1L)
  expect_identical(bst_binary_error$current_iter(), early_stopping_rounds + 1L)
1313
  expect_true(abs(bst_binary_error$best_score - 0.01613904) < .LGB_NUMERIC_TOLERANCE)
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323

  # early stopping should not have been hit for AUC (higher_better = TRUE)
  eval_info <- bst_auc$.__enclos_env__$private$get_eval_info()
  expect_identical(eval_info, "auc")
  expect_identical(
    unname(bst_auc$.__enclos_env__$private$higher_better_inner_eval)
    , TRUE
  )
  expect_identical(bst_auc$best_iter, 9L)
  expect_identical(bst_auc$current_iter(), nrounds)
1324
  expect_true(abs(bst_auc$best_score - 0.9999969) < .LGB_NUMERIC_TOLERANCE)
1325
1326
})

1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
test_that("lgb.train() works with early stopping for regression", {
  set.seed(708L)
  trainDF <- data.frame(
    "feat1" = rep(c(10.0, 100.0), 500L)
    , "target" = rep(c(-50.0, 50.0), 500L)
  )
  validDF <- data.frame(
    "feat1" = rep(50.0, 4L)
    , "target" = rep(50.0, 4L)
  )
  dtrain <- lgb.Dataset(
    data = as.matrix(trainDF[["feat1"]], drop = FALSE)
    , label = trainDF[["target"]]
1340
    , params = list(num_threads = .LGB_MAX_THREADS)
1341
1342
1343
1344
  )
  dvalid <- lgb.Dataset(
    data = as.matrix(validDF[["feat1"]], drop = FALSE)
    , label = validDF[["target"]]
1345
    , params = list(num_threads = .LGB_MAX_THREADS)
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
  )
  nrounds <- 10L

  ################################
  # train with no early stopping #
  ################################
  bst <- lgb.train(
    params = list(
      objective = "regression"
      , metric = "rmse"
1356
      , verbose = .LGB_VERBOSITY
1357
      , num_threads = .LGB_MAX_THREADS
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
    )
    , data = dtrain
    , nrounds = nrounds
    , valids = list(
      "valid1" = dvalid
    )
  )

  # the best possible model should come from the first iteration, but
  # all 10 training iterations should happen
  expect_equal(bst$best_score, 55.0)
  expect_equal(bst$best_iter, 1L)
  expect_equal(length(bst$record_evals[["valid1"]][["rmse"]][["eval"]]), nrounds)

  #############################
  # train with early stopping #
  #############################
  early_stopping_rounds <- 5L
1376
  bst <- lgb.train(
1377
1378
1379
1380
    params = list(
      objective = "regression"
      , metric = "rmse"
      , early_stopping_rounds = early_stopping_rounds
1381
      , verbose = .LGB_VERBOSITY
1382
      , num_threads = .LGB_MAX_THREADS
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
    )
    , data = dtrain
    , nrounds = nrounds
    , valids = list(
      "valid1" = dvalid
    )
  )

  # the best model should be from the first iteration, and only 6 rounds
  # should have happen (1 with improvement, 5 consecutive with no improvement)
  expect_equal(bst$best_score, 55.0)
  expect_equal(bst$best_iter, 1L)
  expect_equal(
    length(bst$record_evals[["valid1"]][["rmse"]][["eval"]])
    , early_stopping_rounds + 1L
  )
})
1400

1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
test_that("lgb.train() does not stop early if early_stopping_rounds is not given", {
  set.seed(708L)

  increasing_metric_starting_value <- get(
    ACCUMULATOR_NAME
    , envir = .GlobalEnv
  )
  nrounds <- 10L
  metrics <- list(
    .constant_metric
    , .increasing_metric
  )
  bst <- lgb.train(
    params = list(
      objective = "regression"
      , metric = "None"
1417
      , verbose = .LGB_VERBOSITY
1418
      , num_threads = .LGB_MAX_THREADS
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
    )
    , data = DTRAIN_RANDOM_REGRESSION
    , nrounds = nrounds
    , valids = list("valid1" = DVALID_RANDOM_REGRESSION)
    , eval = metrics
  )

  # Only the two functions provided to "eval" should have been evaluated
  expect_equal(length(bst$record_evals[["valid1"]]), 2L)

  # all 10 iterations should have happen, and the best_iter should be
  # the first one (based on constant_metric)
  best_iter <- 1L
  expect_equal(bst$best_iter, best_iter)

  # best_score should be taken from the first metric
  expect_equal(
    bst$best_score
    , bst$record_evals[["valid1"]][["constant_metric"]][["eval"]][[best_iter]]
  )

  # early stopping should not have happened. Even though constant_metric
  # had 9 consecutive iterations with no improvement, it is ignored because of
  # first_metric_only = TRUE
  expect_equal(
    length(bst$record_evals[["valid1"]][["constant_metric"]][["eval"]])
    , nrounds
  )
  expect_equal(
    length(bst$record_evals[["valid1"]][["increasing_metric"]][["eval"]])
    , nrounds
  )
})

test_that("If first_metric_only is not given or is FALSE, lgb.train() decides to stop early based on all metrics", {
  set.seed(708L)

  early_stopping_rounds <- 3L
  param_variations <- list(
    list(
      objective = "regression"
      , metric = "None"
      , early_stopping_rounds = early_stopping_rounds
1462
      , verbose = .LGB_VERBOSITY
1463
      , num_threads = .LGB_MAX_THREADS
1464
1465
1466
1467
1468
1469
    )
    , list(
      objective = "regression"
      , metric = "None"
      , early_stopping_rounds = early_stopping_rounds
      , first_metric_only = FALSE
1470
      , verbose = .LGB_VERBOSITY
1471
      , num_threads = .LGB_MAX_THREADS
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
    )
  )

  for (params in param_variations) {

    nrounds <- 10L
    bst <- lgb.train(
      params = params
      , data = DTRAIN_RANDOM_REGRESSION
      , nrounds = nrounds
      , valids = list(
        "valid1" = DVALID_RANDOM_REGRESSION
      )
      , eval = list(
        .increasing_metric
        , .constant_metric
      )
    )

    # Only the two functions provided to "eval" should have been evaluated
    expect_equal(length(bst$record_evals[["valid1"]]), 2L)

    # early stopping should have happened, and should have stopped early_stopping_rounds + 1 rounds in
    # because constant_metric never improves
    #
    # the best iteration should be the last one, because increasing_metric was first
    # and gets better every iteration
    best_iter <- early_stopping_rounds + 1L
    expect_equal(bst$best_iter, best_iter)

    # best_score should be taken from "increasing_metric" because it was first
    expect_equal(
      bst$best_score
      , bst$record_evals[["valid1"]][["increasing_metric"]][["eval"]][[best_iter]]
    )

    # early stopping should not have happened. even though increasing_metric kept
    # getting better, early stopping should have happened because "constant_metric"
    # did not improve
    expect_equal(
      length(bst$record_evals[["valid1"]][["constant_metric"]][["eval"]])
      , early_stopping_rounds + 1L
    )
    expect_equal(
      length(bst$record_evals[["valid1"]][["increasing_metric"]][["eval"]])
      , early_stopping_rounds + 1L
    )
  }

})

test_that("If first_metric_only is TRUE, lgb.train() decides to stop early based on only the first metric", {
  set.seed(708L)
  nrounds <- 10L
  early_stopping_rounds <- 3L
  increasing_metric_starting_value <- get(ACCUMULATOR_NAME, envir = .GlobalEnv)
  bst <- lgb.train(
    params = list(
      objective = "regression"
      , metric = "None"
      , early_stopping_rounds = early_stopping_rounds
      , first_metric_only = TRUE
1534
      , verbose = .LGB_VERBOSITY
1535
      , num_threads = .LGB_MAX_THREADS
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
    )
    , data = DTRAIN_RANDOM_REGRESSION
    , nrounds = nrounds
    , valids = list(
      "valid1" = DVALID_RANDOM_REGRESSION
    )
    , eval = list(
      .increasing_metric
      , .constant_metric
    )
  )

  # Only the two functions provided to "eval" should have been evaluated
  expect_equal(length(bst$record_evals[["valid1"]]), 2L)

  # all 10 iterations should happen, and the best_iter should be the final one
  expect_equal(bst$best_iter, nrounds)

  # best_score should be taken from "increasing_metric"
  expect_equal(
    bst$best_score
    , increasing_metric_starting_value + 0.1 * nrounds
  )

  # early stopping should not have happened. Even though constant_metric
  # had 9 consecutive iterations with no improvement, it is ignored because of
  # first_metric_only = TRUE
  expect_equal(
    length(bst$record_evals[["valid1"]][["constant_metric"]][["eval"]])
    , nrounds
  )
  expect_equal(
    length(bst$record_evals[["valid1"]][["increasing_metric"]][["eval"]])
    , nrounds
  )
})

test_that("lgb.train() works when a mixture of functions and strings are passed to eval", {
  set.seed(708L)
  nrounds <- 10L
  increasing_metric_starting_value <- get(ACCUMULATOR_NAME, envir = .GlobalEnv)
  bst <- lgb.train(
    params = list(
      objective = "regression"
      , metric = "None"
1581
      , verbose = .LGB_VERBOSITY
1582
      , num_threads = .LGB_MAX_THREADS
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
    )
    , data = DTRAIN_RANDOM_REGRESSION
    , nrounds = nrounds
    , valids = list(
      "valid1" = DVALID_RANDOM_REGRESSION
    )
    , eval = list(
      .increasing_metric
      , "rmse"
      , .constant_metric
      , "l2"
    )
  )

  # all 4 metrics should have been used
  expect_named(
    bst$record_evals[["valid1"]]
    , expected = c("rmse", "l2", "increasing_metric", "constant_metric")
    , ignore.order = TRUE
    , ignore.case = FALSE
  )

  # the difference metrics shouldn't have been mixed up with each other
  results <- bst$record_evals[["valid1"]]
1607
1608
  expect_true(abs(results[["rmse"]][["eval"]][[1L]] - 1.105012) < .LGB_NUMERIC_TOLERANCE)
  expect_true(abs(results[["l2"]][["eval"]][[1L]] - 1.221051) < .LGB_NUMERIC_TOLERANCE)
1609
1610
1611
1612
  expected_increasing_metric <- increasing_metric_starting_value + 0.1
  expect_true(
    abs(
      results[["increasing_metric"]][["eval"]][[1L]] - expected_increasing_metric
1613
    ) < .LGB_NUMERIC_TOLERANCE
1614
  )
1615
  expect_true(abs(results[["constant_metric"]][["eval"]][[1L]] - CONSTANT_METRIC_VALUE) < .LGB_NUMERIC_TOLERANCE)
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637

})

test_that("lgb.train() works when a list of strings or a character vector is passed to eval", {

  # testing list and character vector, as well as length-1 and length-2
  eval_variations <- list(
    c("binary_error", "binary_logloss")
    , "binary_logloss"
    , list("binary_error", "binary_logloss")
    , list("binary_logloss")
  )

  for (eval_variation in eval_variations) {

    set.seed(708L)
    nrounds <- 10L
    increasing_metric_starting_value <- get(ACCUMULATOR_NAME, envir = .GlobalEnv)
    bst <- lgb.train(
      params = list(
        objective = "binary"
        , metric = "None"
1638
        , verbose = .LGB_VERBOSITY
1639
        , num_threads = .LGB_MAX_THREADS
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
      )
      , data = DTRAIN_RANDOM_CLASSIFICATION
      , nrounds = nrounds
      , valids = list(
        "valid1" = DVALID_RANDOM_CLASSIFICATION
      )
      , eval = eval_variation
    )

    # both metrics should have been used
    expect_named(
      bst$record_evals[["valid1"]]
      , expected = unlist(eval_variation)
      , ignore.order = TRUE
      , ignore.case = FALSE
    )

    # the difference metrics shouldn't have been mixed up with each other
    results <- bst$record_evals[["valid1"]]
    if ("binary_error" %in% unlist(eval_variation)) {
1660
      expect_true(abs(results[["binary_error"]][["eval"]][[1L]] - 0.4864865) < .LGB_NUMERIC_TOLERANCE)
1661
1662
    }
    if ("binary_logloss" %in% unlist(eval_variation)) {
1663
      expect_true(abs(results[["binary_logloss"]][["eval"]][[1L]] - 0.6932548) < .LGB_NUMERIC_TOLERANCE)
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
    }
  }
})

test_that("lgb.train() works when you specify both 'metric' and 'eval' with strings", {
  set.seed(708L)
  nrounds <- 10L
  increasing_metric_starting_value <- get(ACCUMULATOR_NAME, envir = .GlobalEnv)
  bst <- lgb.train(
    params = list(
      objective = "binary"
      , metric = "binary_error"
1676
      , verbose = .LGB_VERBOSITY
1677
      , num_threads = .LGB_MAX_THREADS
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
    )
    , data = DTRAIN_RANDOM_CLASSIFICATION
    , nrounds = nrounds
    , valids = list(
      "valid1" = DVALID_RANDOM_CLASSIFICATION
    )
    , eval = "binary_logloss"
  )

  # both metrics should have been used
  expect_named(
    bst$record_evals[["valid1"]]
    , expected = c("binary_error", "binary_logloss")
    , ignore.order = TRUE
    , ignore.case = FALSE
  )

  # the difference metrics shouldn't have been mixed up with each other
  results <- bst$record_evals[["valid1"]]
1697
1698
  expect_true(abs(results[["binary_error"]][["eval"]][[1L]] - 0.4864865) < .LGB_NUMERIC_TOLERANCE)
  expect_true(abs(results[["binary_logloss"]][["eval"]][[1L]] - 0.6932548) < .LGB_NUMERIC_TOLERANCE)
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
})

test_that("lgb.train() works when you give a function for eval", {
  set.seed(708L)
  nrounds <- 10L
  increasing_metric_starting_value <- get(ACCUMULATOR_NAME, envir = .GlobalEnv)
  bst <- lgb.train(
    params = list(
      objective = "binary"
      , metric = "None"
1709
      , verbose = .LGB_VERBOSITY
1710
      , num_threads = .LGB_MAX_THREADS
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
    )
    , data = DTRAIN_RANDOM_CLASSIFICATION
    , nrounds = nrounds
    , valids = list(
      "valid1" = DVALID_RANDOM_CLASSIFICATION
    )
    , eval = .constant_metric
  )

  # the difference metrics shouldn't have been mixed up with each other
  results <- bst$record_evals[["valid1"]]
1722
  expect_true(abs(results[["constant_metric"]][["eval"]][[1L]] - CONSTANT_METRIC_VALUE) < .LGB_NUMERIC_TOLERANCE)
1723
1724
})

1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
test_that("lgb.train() works with early stopping for regression with a metric that should be minimized", {
  set.seed(708L)
  trainDF <- data.frame(
    "feat1" = rep(c(10.0, 100.0), 500L)
    , "target" = rep(c(-50.0, 50.0), 500L)
  )
  validDF <- data.frame(
    "feat1" = rep(50.0, 4L)
    , "target" = rep(50.0, 4L)
  )
  dtrain <- lgb.Dataset(
    data = as.matrix(trainDF[["feat1"]], drop = FALSE)
    , label = trainDF[["target"]]
1738
    , params = list(num_threads = .LGB_MAX_THREADS)
1739
1740
1741
1742
  )
  dvalid <- lgb.Dataset(
    data = as.matrix(validDF[["feat1"]], drop = FALSE)
    , label = validDF[["target"]]
1743
    , params = list(num_threads = .LGB_MAX_THREADS)
1744
1745
1746
1747
1748
1749
1750
  )
  nrounds <- 10L

  #############################
  # train with early stopping #
  #############################
  early_stopping_rounds <- 5L
1751
  bst <- lgb.train(
1752
1753
1754
1755
1756
1757
1758
1759
1760
    params = list(
      objective = "regression"
      , metric = c(
          "mape"
          , "rmse"
          , "mae"
      )
      , min_data_in_bin = 5L
      , early_stopping_rounds = early_stopping_rounds
1761
      , verbose = .LGB_VERBOSITY
1762
      , num_threads = .LGB_MAX_THREADS
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
    )
    , data = dtrain
    , nrounds = nrounds
    , valids = list(
      "valid1" = dvalid
    )
  )

  # the best model should be from the first iteration, and only 6 rounds
  # should have happened (1 with improvement, 5 consecutive with no improvement)
  expect_equal(bst$best_score, 1.1)
  expect_equal(bst$best_iter, 1L)
  expect_equal(
    length(bst$record_evals[["valid1"]][["mape"]][["eval"]])
    , early_stopping_rounds + 1L
  )

  # Booster should understand thatt all three of these metrics should be minimized
  eval_info <- bst$.__enclos_env__$private$get_eval_info()
  expect_identical(eval_info, c("mape", "rmse", "l1"))
  expect_identical(
    unname(bst$.__enclos_env__$private$higher_better_inner_eval)
    , rep(FALSE, 3L)
  )
})


1790
1791
1792
1793
test_that("lgb.train() supports non-ASCII feature names", {
  dtrain <- lgb.Dataset(
    data = matrix(rnorm(400L), ncol =  4L)
    , label = rnorm(100L)
1794
    , params = list(num_threads = .LGB_MAX_THREADS)
1795
  )
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
  # content below is equivalent to
  #
  #  feature_names <- c("F_零", "F_一", "F_二", "F_三")
  #
  # but using rawToChar() to avoid weird issues when {testthat}
  # sources files and converts their encodings prior to evaluating the code
  feature_names <- c(
    rawToChar(as.raw(c(0x46, 0x5f, 0xe9, 0x9b, 0xb6)))
    , rawToChar(as.raw(c(0x46, 0x5f, 0xe4, 0xb8, 0x80)))
    , rawToChar(as.raw(c(0x46, 0x5f, 0xe4, 0xba, 0x8c)))
    , rawToChar(as.raw(c(0x46, 0x5f, 0xe4, 0xb8, 0x89)))
  )
1808
1809
1810
1811
1812
1813
  bst <- lgb.train(
    data = dtrain
    , nrounds = 5L
    , obj = "regression"
    , params = list(
      metric = "rmse"
1814
      , verbose = .LGB_VERBOSITY
1815
      , num_threads = .LGB_MAX_THREADS
1816
1817
1818
1819
1820
    )
    , colnames = feature_names
  )
  expect_true(lgb.is.Booster(bst))
  dumped_model <- jsonlite::fromJSON(bst$dump_model())
1821
1822
1823
1824

  # UTF-8 strings are not well-supported on Windows
  # * https://developer.r-project.org/Blog/public/2020/05/02/utf-8-support-on-windows/
  # * https://developer.r-project.org/Blog/public/2020/07/30/windows/utf-8-build-of-r-and-cran-packages/index.html
1825
  if (.LGB_UTF8_LOCALE && !.LGB_ON_WINDOWS) {
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
    expect_identical(
      dumped_model[["feature_names"]]
      , feature_names
    )
  } else {
    expect_identical(
      dumped_model[["feature_names"]]
      , iconv(feature_names, to = "UTF-8")
    )
  }
1836
})
1837

1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
test_that("lgb.train() works with integer, double, and numeric data", {
  data(mtcars)
  X <- as.matrix(mtcars[, -1L])
  y <- mtcars[, 1L, drop = TRUE]
  expected_mae <- 4.263667
  for (data_mode in c("numeric", "double", "integer")) {
    mode(X) <- data_mode
    nrounds <- 10L
    bst <- lightgbm(
      data = X
      , label = y
      , params = list(
        objective = "regression"
1851
1852
        , min_data_in_bin = 1L
        , min_data_in_leaf = 1L
1853
1854
        , learning_rate = 0.01
        , seed = 708L
1855
        , verbose = .LGB_VERBOSITY
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
      )
      , nrounds = nrounds
    )

    # should have trained for 10 iterations and found splits
    modelDT <- lgb.model.dt.tree(bst)
    expect_equal(modelDT[, max(tree_index)], nrounds - 1L)
    expect_gt(nrow(modelDT), nrounds * 3L)

    # should have achieved expected performance
    preds <- predict(bst, X)
    mae <- mean(abs(y - preds))
1868
    expect_true(abs(mae - expected_mae) < .LGB_NUMERIC_TOLERANCE)
1869
1870
1871
  }
})

1872
1873
1874
1875
test_that("lgb.train() updates params based on keyword arguments", {
  dtrain <- lgb.Dataset(
    data = matrix(rnorm(400L), ncol =  4L)
    , label = rnorm(100L)
1876
    , params = list(num_threads = .LGB_MAX_THREADS)
1877
1878
1879
1880
1881
1882
1883
1884
  )

  # defaults from keyword arguments should be used if not specified in params
  invisible(
    capture.output({
      bst <- lgb.train(
        data = dtrain
        , obj = "regression"
1885
        , params = list(num_threads = .LGB_MAX_THREADS)
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
      )
    })
  )
  expect_equal(bst$params[["verbosity"]], 1L)
  expect_equal(bst$params[["num_iterations"]], 100L)

  # main param names should be preferred to keyword arguments
  invisible(
    capture.output({
      bst <- lgb.train(
        data = dtrain
        , obj = "regression"
        , params = list(
          "verbosity" = 5L
          , "num_iterations" = 2L
1901
          , num_threads = .LGB_MAX_THREADS
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
        )
      )
    })
  )
  expect_equal(bst$params[["verbosity"]], 5L)
  expect_equal(bst$params[["num_iterations"]], 2L)

  # aliases should be preferred to keyword arguments, and converted to main parameter name
  invisible(
    capture.output({
      bst <- lgb.train(
        data = dtrain
        , obj = "regression"
        , params = list(
          "verbose" = 5L
          , "num_boost_round" = 2L
1918
          , num_threads = .LGB_MAX_THREADS
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
        )
      )
    })
  )
  expect_equal(bst$params[["verbosity"]], 5L)
  expect_false("verbose" %in% bst$params)
  expect_equal(bst$params[["num_iterations"]], 2L)
  expect_false("num_boost_round" %in% bst$params)
})

1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
test_that("when early stopping is not activated, best_iter and best_score come from valids and not training data", {
  set.seed(708L)
  trainDF <- data.frame(
    "feat1" = rep(c(10.0, 100.0), 500L)
    , "target" = rep(c(-50.0, 50.0), 500L)
  )
  validDF <- data.frame(
    "feat1" = rep(50.0, 4L)
    , "target" = rep(50.0, 4L)
  )
  dtrain <- lgb.Dataset(
    data = as.matrix(trainDF[["feat1"]], drop = FALSE)
    , label = trainDF[["target"]]
1942
    , params = list(num_threads = .LGB_MAX_THREADS)
1943
1944
1945
1946
  )
  dvalid1 <- lgb.Dataset(
    data = as.matrix(validDF[["feat1"]], drop = FALSE)
    , label = validDF[["target"]]
1947
    , params = list(num_threads = .LGB_MAX_THREADS)
1948
1949
1950
1951
  )
  dvalid2 <- lgb.Dataset(
    data = as.matrix(validDF[1L:10L, "feat1"], drop = FALSE)
    , label = validDF[1L:10L, "target"]
1952
    , params = list(num_threads = .LGB_MAX_THREADS)
1953
1954
1955
1956
1957
1958
  )
  nrounds <- 10L
  train_params <- list(
    objective = "regression"
    , metric = "rmse"
    , learning_rate = 1.5
1959
    , num_leaves = 5L
1960
    , verbose = .LGB_VERBOSITY
1961
    , num_threads = .LGB_MAX_THREADS
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
  )

  # example 1: two valids, neither are the training data
  bst <- lgb.train(
    data = dtrain
    , nrounds = nrounds
    , valids = list(
      "valid1" = dvalid1
      , "valid2" = dvalid2
    )
    , params = train_params
  )
  expect_named(
    bst$record_evals
    , c("start_iter", "valid1", "valid2")
    , ignore.order = FALSE
    , ignore.case = FALSE
  )
  rmse_scores <- unlist(bst$record_evals[["valid1"]][["rmse"]][["eval"]])
  expect_length(rmse_scores, nrounds)
  expect_identical(bst$best_iter, which.min(rmse_scores))
  expect_identical(bst$best_score, rmse_scores[which.min(rmse_scores)])

  # example 2: train first (called "train") and two valids
  bst <- lgb.train(
    data = dtrain
    , nrounds = nrounds
    , valids = list(
      "train" = dtrain
      , "valid1" = dvalid1
      , "valid2" = dvalid2
    )
    , params = train_params
  )
  expect_named(
    bst$record_evals
    , c("start_iter", "train", "valid1", "valid2")
    , ignore.order = FALSE
    , ignore.case = FALSE
  )
  rmse_scores <- unlist(bst$record_evals[["valid1"]][["rmse"]][["eval"]])
  expect_length(rmse_scores, nrounds)
  expect_identical(bst$best_iter, which.min(rmse_scores))
  expect_identical(bst$best_score, rmse_scores[which.min(rmse_scores)])

  # example 3: train second (called "train") and two valids
  bst <- lgb.train(
    data = dtrain
    , nrounds = nrounds
    , valids = list(
      "valid1" = dvalid1
      , "train" = dtrain
      , "valid2" = dvalid2
    )
    , params = train_params
  )
  # note that "train" still ends up as the first one
  expect_named(
    bst$record_evals
    , c("start_iter", "train", "valid1", "valid2")
    , ignore.order = FALSE
    , ignore.case = FALSE
  )
  rmse_scores <- unlist(bst$record_evals[["valid1"]][["rmse"]][["eval"]])
  expect_length(rmse_scores, nrounds)
  expect_identical(bst$best_iter, which.min(rmse_scores))
  expect_identical(bst$best_score, rmse_scores[which.min(rmse_scores)])

  # example 4: train third (called "train") and two valids
  bst <- lgb.train(
    data = dtrain
    , nrounds = nrounds
    , valids = list(
      "valid1" = dvalid1
      , "valid2" = dvalid2
      , "train" = dtrain
    )
    , params = train_params
  )
  # note that "train" still ends up as the first one
  expect_named(
    bst$record_evals
    , c("start_iter", "train", "valid1", "valid2")
    , ignore.order = FALSE
    , ignore.case = FALSE
  )
  rmse_scores <- unlist(bst$record_evals[["valid1"]][["rmse"]][["eval"]])
  expect_length(rmse_scores, nrounds)
  expect_identical(bst$best_iter, which.min(rmse_scores))
  expect_identical(bst$best_score, rmse_scores[which.min(rmse_scores)])

  # example 5: train second (called "something-random-we-would-not-hardcode") and two valids
  bst <- lgb.train(
    data = dtrain
    , nrounds = nrounds
    , valids = list(
      "valid1" = dvalid1
      , "something-random-we-would-not-hardcode" = dtrain
      , "valid2" = dvalid2
    )
    , params = train_params
  )
  # note that "something-random-we-would-not-hardcode" was recognized as the training
  # data even though it isn't named "train"
  expect_named(
    bst$record_evals
    , c("start_iter", "something-random-we-would-not-hardcode", "valid1", "valid2")
    , ignore.order = FALSE
    , ignore.case = FALSE
  )
  rmse_scores <- unlist(bst$record_evals[["valid1"]][["rmse"]][["eval"]])
  expect_length(rmse_scores, nrounds)
  expect_identical(bst$best_iter, which.min(rmse_scores))
  expect_identical(bst$best_score, rmse_scores[which.min(rmse_scores)])

  # example 6: the only valid supplied is the training data
  bst <- lgb.train(
    data = dtrain
    , nrounds = nrounds
    , valids = list(
      "train" = dtrain
    )
    , params = train_params
  )
  expect_identical(bst$best_iter, -1L)
  expect_identical(bst$best_score, NA_real_)
})

test_that("lightgbm.train() gives the correct best_score and best_iter for a metric where higher values are better", {
  set.seed(708L)
  trainDF <- data.frame(
    "feat1" = runif(n = 500L, min = 0.0, max = 15.0)
    , "target" = rep(c(0L, 1L), 500L)
  )
  validDF <- data.frame(
    "feat1" = runif(n = 50L, min = 0.0, max = 15.0)
    , "target" = rep(c(0L, 1L), 50L)
  )
  dtrain <- lgb.Dataset(
    data = as.matrix(trainDF[["feat1"]], drop = FALSE)
    , label = trainDF[["target"]]
2103
    , params = list(num_threads = .LGB_MAX_THREADS)
2104
2105
2106
2107
  )
  dvalid1 <- lgb.Dataset(
    data = as.matrix(validDF[1L:25L, "feat1"], drop = FALSE)
    , label = validDF[1L:25L, "target"]
2108
    , params = list(num_threads = .LGB_MAX_THREADS)
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
  )
  nrounds <- 10L
  bst <- lgb.train(
    data = dtrain
    , nrounds = nrounds
    , valids = list(
      "valid1" = dvalid1
      , "something-random-we-would-not-hardcode" = dtrain
    )
    , params = list(
      objective = "binary"
      , metric = "auc"
      , learning_rate = 1.5
2122
      , num_leaves = 5L
2123
      , verbose = .LGB_VERBOSITY
2124
      , num_threads = .LGB_MAX_THREADS
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
    )
  )
  # note that "something-random-we-would-not-hardcode" was recognized as the training
  # data even though it isn't named "train"
  expect_named(
    bst$record_evals
    , c("start_iter", "something-random-we-would-not-hardcode", "valid1")
    , ignore.order = FALSE
    , ignore.case = FALSE
  )
  auc_scores <- unlist(bst$record_evals[["valid1"]][["auc"]][["eval"]])
  expect_length(auc_scores, nrounds)
  expect_identical(bst$best_iter, which.max(auc_scores))
  expect_identical(bst$best_score, auc_scores[which.max(auc_scores)])
})

test_that("using lightgbm() without early stopping, best_iter and best_score come from valids and not training data", {
  set.seed(708L)
  # example: train second (called "something-random-we-would-not-hardcode"), two valids,
  #          and a metric where higher values are better ("auc")
  trainDF <- data.frame(
    "feat1" = runif(n = 500L, min = 0.0, max = 15.0)
    , "target" = rep(c(0L, 1L), 500L)
  )
  validDF <- data.frame(
    "feat1" = runif(n = 50L, min = 0.0, max = 15.0)
    , "target" = rep(c(0L, 1L), 50L)
  )
  dtrain <- lgb.Dataset(
    data = as.matrix(trainDF[["feat1"]], drop = FALSE)
    , label = trainDF[["target"]]
2156
    , params = list(num_threads = .LGB_MAX_THREADS)
2157
2158
2159
2160
  )
  dvalid1 <- lgb.Dataset(
    data = as.matrix(validDF[1L:25L, "feat1"], drop = FALSE)
    , label = validDF[1L:25L, "target"]
2161
    , params = list(num_threads = .LGB_MAX_THREADS)
2162
2163
2164
2165
  )
  dvalid2 <- lgb.Dataset(
    data = as.matrix(validDF[26L:50L, "feat1"], drop = FALSE)
    , label = validDF[26L:50L, "target"]
2166
    , params = list(num_threads = .LGB_MAX_THREADS)
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
  )
  nrounds <- 10L
  bst <- lightgbm(
    data = dtrain
    , nrounds = nrounds
    , valids = list(
      "valid1" = dvalid1
      , "something-random-we-would-not-hardcode" = dtrain
      , "valid2" = dvalid2
    )
    , params = list(
      objective = "binary"
      , metric = "auc"
      , learning_rate = 1.5
2181
      , num_leaves = 5L
2182
      , num_threads = .LGB_MAX_THREADS
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
    )
    , verbose = -7L
  )
  # when verbose <= 0 is passed to lightgbm(), 'valids' is passed through to lgb.train()
  # untouched. If you set verbose to > 0, the training data will still be first but called "train"
  expect_named(
    bst$record_evals
    , c("start_iter", "something-random-we-would-not-hardcode", "valid1", "valid2")
    , ignore.order = FALSE
    , ignore.case = FALSE
  )
  auc_scores <- unlist(bst$record_evals[["valid1"]][["auc"]][["eval"]])
  expect_length(auc_scores, nrounds)
  expect_identical(bst$best_iter, which.max(auc_scores))
  expect_identical(bst$best_score, auc_scores[which.max(auc_scores)])
})
2199

2200
2201
2202
2203
2204
2205
2206
2207
2208
test_that("lgb.cv() works when you specify both 'metric' and 'eval' with strings", {
  set.seed(708L)
  nrounds <- 10L
  nfolds <- 4L
  increasing_metric_starting_value <- get(ACCUMULATOR_NAME, envir = .GlobalEnv)
  bst <- lgb.cv(
    params = list(
      objective = "binary"
      , metric = "binary_error"
2209
      , verbose = .LGB_VERBOSITY
2210
      , num_threads = .LGB_MAX_THREADS
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
    )
    , data = DTRAIN_RANDOM_CLASSIFICATION
    , nrounds = nrounds
    , nfold = nfolds
    , eval = "binary_logloss"
  )

  # both metrics should have been used
  expect_named(
    bst$record_evals[["valid"]]
    , expected = c("binary_error", "binary_logloss")
    , ignore.order = TRUE
    , ignore.case = FALSE
  )

  # the difference metrics shouldn't have been mixed up with each other
  results <- bst$record_evals[["valid"]]
2228
2229
  expect_true(abs(results[["binary_error"]][["eval"]][[1L]] - 0.5005654) < .LGB_NUMERIC_TOLERANCE)
  expect_true(abs(results[["binary_logloss"]][["eval"]][[1L]] - 0.7011232) < .LGB_NUMERIC_TOLERANCE)
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243

  # all boosters should have been created
  expect_length(bst$boosters, nfolds)
})

test_that("lgb.cv() works when you give a function for eval", {
  set.seed(708L)
  nrounds <- 10L
  nfolds <- 3L
  increasing_metric_starting_value <- get(ACCUMULATOR_NAME, envir = .GlobalEnv)
  bst <- lgb.cv(
    params = list(
      objective = "binary"
      , metric = "None"
2244
      , verbose = .LGB_VERBOSITY
2245
      , num_threads = .LGB_MAX_THREADS
2246
2247
2248
2249
2250
2251
2252
2253
2254
    )
    , data = DTRAIN_RANDOM_CLASSIFICATION
    , nfold = nfolds
    , nrounds = nrounds
    , eval = .constant_metric
  )

  # the difference metrics shouldn't have been mixed up with each other
  results <- bst$record_evals[["valid"]]
2255
  expect_true(abs(results[["constant_metric"]][["eval"]][[1L]] - CONSTANT_METRIC_VALUE) < .LGB_NUMERIC_TOLERANCE)
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
  expect_named(results, "constant_metric")
})

test_that("If first_metric_only is TRUE, lgb.cv() decides to stop early based on only the first metric", {
  set.seed(708L)
  nrounds <- 10L
  nfolds <- 5L
  early_stopping_rounds <- 3L
  increasing_metric_starting_value <- get(ACCUMULATOR_NAME, envir = .GlobalEnv)
  bst <- lgb.cv(
    params = list(
      objective = "regression"
      , metric = "None"
      , early_stopping_rounds = early_stopping_rounds
      , first_metric_only = TRUE
2271
      , verbose = .LGB_VERBOSITY
2272
      , num_threads = .LGB_MAX_THREADS
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
    )
    , data = DTRAIN_RANDOM_REGRESSION
    , nfold = nfolds
    , nrounds = nrounds
    , eval = list(
      .increasing_metric
      , .constant_metric
    )
  )

  # Only the two functions provided to "eval" should have been evaluated
  expect_named(bst$record_evals[["valid"]], c("increasing_metric", "constant_metric"))

  # all 10 iterations should happen, and the best_iter should be the final one
  expect_equal(bst$best_iter, nrounds)

  # best_score should be taken from "increasing_metric"
  #
  # this expected value looks magical and confusing, but it's because
  # evaluation metrics are averaged over all folds.
  #
  # consider 5-fold CV with a metric that adds 0.1 to a global accumulator
  # each time it's called
  #
  # * iter 1: [0.1, 0.2, 0.3, 0.4, 0.5] (mean = 0.3)
  # * iter 2: [0.6, 0.7, 0.8, 0.9, 1.0] (mean = 1.3)
  # * iter 3: [1.1, 1.2, 1.3, 1.4, 1.5] (mean = 1.8)
  #
  cv_value <- increasing_metric_starting_value + mean(seq_len(nfolds) / 10.0) + (nrounds  - 1L) * 0.1 * nfolds
  expect_equal(bst$best_score, cv_value)

  # early stopping should not have happened. Even though constant_metric
  # had 9 consecutive iterations with no improvement, it is ignored because of
  # first_metric_only = TRUE
  expect_equal(
    length(bst$record_evals[["valid"]][["constant_metric"]][["eval"]])
    , nrounds
  )
  expect_equal(
    length(bst$record_evals[["valid"]][["increasing_metric"]][["eval"]])
    , nrounds
  )
})

test_that("early stopping works with lgb.cv()", {
  set.seed(708L)
  nrounds <- 10L
  nfolds <- 5L
  early_stopping_rounds <- 3L
  increasing_metric_starting_value <- get(ACCUMULATOR_NAME, envir = .GlobalEnv)
  bst <- lgb.cv(
    params = list(
      objective = "regression"
      , metric = "None"
      , early_stopping_rounds = early_stopping_rounds
      , first_metric_only = TRUE
2329
      , verbose = .LGB_VERBOSITY
2330
      , num_threads = .LGB_MAX_THREADS
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
    )
    , data = DTRAIN_RANDOM_REGRESSION
    , nfold = nfolds
    , nrounds = nrounds
    , eval = list(
      .constant_metric
      , .increasing_metric
    )
  )

  # only the two functions provided to "eval" should have been evaluated
  expect_named(bst$record_evals[["valid"]], c("constant_metric", "increasing_metric"))

  # best_iter should be based on the first metric. Since constant_metric
  # never changes, its first iteration was the best oone
  expect_equal(bst$best_iter, 1L)

  # best_score should be taken from the first metri
  expect_equal(bst$best_score, 0.2)

  # early stopping should have happened, since constant_metric was the first
  # one passed to eval and it will not improve over consecutive iterations
  #
  # note that this test is identical to the previous one, but with the
  # order of the eval metrics switched
  expect_equal(
    length(bst$record_evals[["valid"]][["constant_metric"]][["eval"]])
    , early_stopping_rounds + 1L
  )
  expect_equal(
    length(bst$record_evals[["valid"]][["increasing_metric"]][["eval"]])
    , early_stopping_rounds + 1L
  )
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373

  # every booster's predict method should use best_iter as num_iteration in predict
  random_data <- as.matrix(rnorm(10L), ncol = 1L, drop = FALSE)
  for (x in bst$boosters) {
    expect_equal(x$booster$best_iter, bst$best_iter)
    expect_gt(x$booster$current_iter(), bst$best_iter)
    preds_iter <- predict(x$booster, random_data, num_iteration = bst$best_iter)
    preds_no_iter <- predict(x$booster, random_data)
    expect_equal(preds_iter, preds_no_iter)
  }
2374
2375
})

2376
2377
2378
2379
test_that("lgb.cv() respects changes to logging verbosity", {
  dtrain <- lgb.Dataset(
    data = train$data
    , label = train$label
2380
    , params = list(num_threads = .LGB_MAX_THREADS)
2381
2382
2383
2384
  )
  # (verbose = 1) should be INFO and WARNING level logs
  lgb_cv_logs <- capture.output({
    cv_bst <- lgb.cv(
2385
      params = list(num_threads = .LGB_MAX_THREADS)
2386
2387
2388
2389
2390
2391
2392
      , nfold = 2L
      , nrounds = 5L
      , data = dtrain
      , obj = "binary"
      , verbose = 1L
    )
  })
2393
2394
  expect_true(any(grepl("[LightGBM] [Info]", lgb_cv_logs, fixed = TRUE)))
  expect_true(any(grepl("[LightGBM] [Warning]", lgb_cv_logs, fixed = TRUE)))
2395
2396
2397
2398

  # (verbose = 0) should be WARNING level logs only
  lgb_cv_logs <- capture.output({
    cv_bst <- lgb.cv(
2399
      params = list(num_threads = .LGB_MAX_THREADS)
2400
2401
2402
2403
2404
2405
2406
      , nfold = 2L
      , nrounds = 5L
      , data = dtrain
      , obj = "binary"
      , verbose = 0L
    )
  })
2407
2408
  expect_false(any(grepl("[LightGBM] [Info]", lgb_cv_logs, fixed = TRUE)))
  expect_true(any(grepl("[LightGBM] [Warning]", lgb_cv_logs, fixed = TRUE)))
2409
2410
2411
2412

  # (verbose = -1) no logs
  lgb_cv_logs <- capture.output({
    cv_bst <- lgb.cv(
2413
      params = list(num_threads = .LGB_MAX_THREADS)
2414
2415
2416
2417
2418
2419
2420
2421
2422
      , nfold = 2L
      , nrounds = 5L
      , data = dtrain
      , obj = "binary"
      , verbose = -1L
    )
  })
  # NOTE: this is not length(lgb_cv_logs) == 0 because lightgbm's
  #       dependencies might print other messages
2423
2424
  expect_false(any(grepl("[LightGBM] [Info]", lgb_cv_logs, fixed = TRUE)))
  expect_false(any(grepl("[LightGBM] [Warning]", lgb_cv_logs, fixed = TRUE)))
2425
2426
})

2427
2428
2429
2430
test_that("lgb.cv() updates params based on keyword arguments", {
  dtrain <- lgb.Dataset(
    data = matrix(rnorm(400L), ncol =  4L)
    , label = rnorm(100L)
2431
    , params = list(num_threads = .LGB_MAX_THREADS)
2432
2433
2434
2435
2436
2437
2438
2439
  )

  # defaults from keyword arguments should be used if not specified in params
  invisible(
    capture.output({
      cv_bst <- lgb.cv(
        data = dtrain
        , obj = "regression"
2440
        , params = list(num_threads = .LGB_MAX_THREADS)
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
        , nfold = 2L
      )
    })
  )

  for (bst in cv_bst$boosters) {
    bst_params <- bst[["booster"]]$params
    expect_equal(bst_params[["verbosity"]], 1L)
    expect_equal(bst_params[["num_iterations"]], 100L)
  }

  # main param names should be preferred to keyword arguments
  invisible(
    capture.output({
      cv_bst <- lgb.cv(
        data = dtrain
        , obj = "regression"
        , params = list(
          "verbosity" = 5L
          , "num_iterations" = 2L
2461
          , num_threads = .LGB_MAX_THREADS
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
        )
        , nfold = 2L
      )
    })
  )
  for (bst in cv_bst$boosters) {
    bst_params <- bst[["booster"]]$params
    expect_equal(bst_params[["verbosity"]], 5L)
    expect_equal(bst_params[["num_iterations"]], 2L)
  }

  # aliases should be preferred to keyword arguments, and converted to main parameter name
  invisible(
    capture.output({
      cv_bst <- lgb.cv(
        data = dtrain
        , obj = "regression"
        , params = list(
          "verbose" = 5L
          , "num_boost_round" = 2L
2482
          , num_threads = .LGB_MAX_THREADS
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
        )
        , nfold = 2L
      )
    })
  )
  for (bst in cv_bst$boosters) {
    bst_params <- bst[["booster"]]$params
    expect_equal(bst_params[["verbosity"]], 5L)
    expect_false("verbose" %in% bst_params)
    expect_equal(bst_params[["num_iterations"]], 2L)
    expect_false("num_boost_round" %in% bst_params)
  }

})

2498
2499
2500
2501
2502
2503
2504
test_that("lgb.train() fit on linearly-relatead data improves when using linear learners", {
  set.seed(708L)
  .new_dataset <- function() {
    X <- matrix(rnorm(100L), ncol = 1L)
    return(lgb.Dataset(
      data = X
      , label = 2L * X + runif(nrow(X), 0L, 0.1)
2505
      , params = list(num_threads = .LGB_MAX_THREADS)
2506
2507
2508
2509
2510
    ))
  }

  params <- list(
    objective = "regression"
2511
    , verbose = .LGB_VERBOSITY
2512
2513
2514
    , metric = "mse"
    , seed = 0L
    , num_leaves = 2L
2515
    , num_threads = .LGB_MAX_THREADS
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
  )

  dtrain <- .new_dataset()
  bst <- lgb.train(
    data = dtrain
    , nrounds = 10L
    , params = params
    , valids = list("train" = dtrain)
  )
  expect_true(lgb.is.Booster(bst))

  dtrain <- .new_dataset()
  bst_linear <- lgb.train(
    data = dtrain
    , nrounds = 10L
2531
    , params = utils::modifyList(params, list(linear_tree = TRUE))
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
    , valids = list("train" = dtrain)
  )
  expect_true(lgb.is.Booster(bst_linear))

  bst_last_mse <- bst$record_evals[["train"]][["l2"]][["eval"]][[10L]]
  bst_lin_last_mse <- bst_linear$record_evals[["train"]][["l2"]][["eval"]][[10L]]
  expect_true(bst_lin_last_mse <  bst_last_mse)
})


2542
test_that("lgb.train() with linear learner fails already-constructed dataset with linear=false", {
2543
2544
2545
  set.seed(708L)
  params <- list(
    objective = "regression"
2546
    , verbose = .LGB_VERBOSITY
2547
2548
2549
    , metric = "mse"
    , seed = 0L
    , num_leaves = 2L
2550
    , num_threads = .LGB_MAX_THREADS
2551
2552
2553
2554
2555
  )

  dtrain <- lgb.Dataset(
    data = matrix(rnorm(100L), ncol = 1L)
    , label = rnorm(100L)
2556
    , params = list(num_threads = .LGB_MAX_THREADS)
2557
2558
2559
  )
  dtrain$construct()
  expect_error({
2560
2561
2562
2563
2564
2565
2566
    capture.output({
      bst_linear <- lgb.train(
        data = dtrain
        , nrounds = 10L
        , params = utils::modifyList(params, list(linear_tree = TRUE))
      )
    }, type = "message")
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
  }, regexp = "Cannot change linear_tree after constructed Dataset handle")
})

test_that("lgb.train() works with linear learners even if Dataset has missing values", {
  set.seed(708L)
  .new_dataset <- function() {
    values <- rnorm(100L)
    values[sample(seq_len(length(values)), size = 10L)] <- NA_real_
    X <- matrix(
      data = sample(values, size = 100L)
      , ncol = 1L
    )
    return(lgb.Dataset(
      data = X
      , label = 2L * X + runif(nrow(X), 0L, 0.1)
2582
      , params = list(num_threads = .LGB_MAX_THREADS)
2583
2584
2585
2586
2587
    ))
  }

  params <- list(
    objective = "regression"
2588
    , verbose = .LGB_VERBOSITY
2589
2590
2591
    , metric = "mse"
    , seed = 0L
    , num_leaves = 2L
2592
    , num_threads = .LGB_MAX_THREADS
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
  )

  dtrain <- .new_dataset()
  bst <- lgb.train(
    data = dtrain
    , nrounds = 10L
    , params = params
    , valids = list("train" = dtrain)
  )
  expect_true(lgb.is.Booster(bst))

  dtrain <- .new_dataset()
  bst_linear <- lgb.train(
    data = dtrain
    , nrounds = 10L
2608
    , params = utils::modifyList(params, list(linear_tree = TRUE))
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
    , valids = list("train" = dtrain)
  )
  expect_true(lgb.is.Booster(bst_linear))

  bst_last_mse <- bst$record_evals[["train"]][["l2"]][["eval"]][[10L]]
  bst_lin_last_mse <- bst_linear$record_evals[["train"]][["l2"]][["eval"]][[10L]]
  expect_true(bst_lin_last_mse <  bst_last_mse)
})

test_that("lgb.train() works with linear learners, bagging, and a Dataset that has missing values", {
  set.seed(708L)
  .new_dataset <- function() {
    values <- rnorm(100L)
    values[sample(seq_len(length(values)), size = 10L)] <- NA_real_
    X <- matrix(
      data = sample(values, size = 100L)
      , ncol = 1L
    )
    return(lgb.Dataset(
      data = X
      , label = 2L * X + runif(nrow(X), 0L, 0.1)
2630
      , params = list(num_threads = .LGB_MAX_THREADS)
2631
2632
2633
2634
2635
    ))
  }

  params <- list(
    objective = "regression"
2636
    , verbose = .LGB_VERBOSITY
2637
2638
2639
2640
2641
    , metric = "mse"
    , seed = 0L
    , num_leaves = 2L
    , bagging_freq = 1L
    , subsample = 0.8
2642
    , num_threads = .LGB_MAX_THREADS
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
  )

  dtrain <- .new_dataset()
  bst <- lgb.train(
    data = dtrain
    , nrounds = 10L
    , params = params
    , valids = list("train" = dtrain)
  )
  expect_true(lgb.is.Booster(bst))

  dtrain <- .new_dataset()
  bst_linear <- lgb.train(
    data = dtrain
    , nrounds = 10L
2658
    , params = utils::modifyList(params, list(linear_tree = TRUE))
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
    , valids = list("train" = dtrain)
  )
  expect_true(lgb.is.Booster(bst_linear))

  bst_last_mse <- bst$record_evals[["train"]][["l2"]][["eval"]][[10L]]
  bst_lin_last_mse <- bst_linear$record_evals[["train"]][["l2"]][["eval"]][[10L]]
  expect_true(bst_lin_last_mse <  bst_last_mse)
})

test_that("lgb.train() works with linear learners and data where a feature has only 1 non-NA value", {
  set.seed(708L)
  .new_dataset <- function() {
2671
2672
    values <- c(rnorm(100L), rep(NA_real_, 100L))
    values[118L] <- rnorm(1L)
2673
2674
    X <- matrix(
      data = values
2675
      , ncol = 2L
2676
2677
2678
    )
    return(lgb.Dataset(
      data = X
2679
      , label = 2L * X[, 1L] + runif(nrow(X), 0L, 0.1)
2680
2681
      , params = list(
        feature_pre_filter = FALSE
2682
        , num_threads = .LGB_MAX_THREADS
2683
      )
2684
2685
2686
2687
2688
2689
2690
2691
2692
    ))
  }

  params <- list(
    objective = "regression"
    , verbose = -1L
    , metric = "mse"
    , seed = 0L
    , num_leaves = 2L
2693
    , num_threads = .LGB_MAX_THREADS
2694
2695
2696
2697
2698
2699
  )

  dtrain <- .new_dataset()
  bst_linear <- lgb.train(
    data = dtrain
    , nrounds = 10L
2700
    , params = utils::modifyList(params, list(linear_tree = TRUE))
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
  )
  expect_true(lgb.is.Booster(bst_linear))
})

test_that("lgb.train() works with linear learners when Dataset has categorical features", {
  set.seed(708L)
  .new_dataset <- function() {
    X <- matrix(numeric(200L), nrow = 100L, ncol = 2L)
    X[, 1L] <- rnorm(100L)
    X[, 2L] <- sample(seq_len(4L), size = 100L, replace = TRUE)
    return(lgb.Dataset(
      data = X
      , label = 2L * X[, 1L] + runif(nrow(X), 0L, 0.1)
2714
      , params = list(num_threads = .LGB_MAX_THREADS)
2715
2716
2717
2718
2719
2720
2721
2722
2723
    ))
  }

  params <- list(
    objective = "regression"
    , verbose = -1L
    , metric = "mse"
    , seed = 0L
    , num_leaves = 2L
2724
    , categorical_feature = 1L
2725
    , num_threads = .LGB_MAX_THREADS
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
  )

  dtrain <- .new_dataset()
  bst <- lgb.train(
    data = dtrain
    , nrounds = 10L
    , params = params
    , valids = list("train" = dtrain)
  )
  expect_true(lgb.is.Booster(bst))

  dtrain <- .new_dataset()
  bst_linear <- lgb.train(
    data = dtrain
    , nrounds = 10L
2741
    , params = utils::modifyList(params, list(linear_tree = TRUE))
2742
2743
2744
2745
2746
2747
2748
2749
2750
    , valids = list("train" = dtrain)
  )
  expect_true(lgb.is.Booster(bst_linear))

  bst_last_mse <- bst$record_evals[["train"]][["l2"]][["eval"]][[10L]]
  bst_lin_last_mse <- bst_linear$record_evals[["train"]][["l2"]][["eval"]][[10L]]
  expect_true(bst_lin_last_mse <  bst_last_mse)
})

2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
test_that("lgb.train() throws an informative error if interaction_constraints is not a list", {
  dtrain <- lgb.Dataset(train$data, label = train$label)
  params <- list(objective = "regression", interaction_constraints = "[1,2],[3]")
    expect_error({
      bst <- lightgbm(
        data = dtrain
        , params = params
        , nrounds = 2L
      )
    }, "interaction_constraints must be a list")
})

test_that(paste0("lgb.train() throws an informative error if the members of interaction_constraints ",
                 "are not character or numeric vectors"), {
  dtrain <- lgb.Dataset(train$data, label = train$label)
  params <- list(objective = "regression", interaction_constraints = list(list(1L, 2L), list(3L)))
    expect_error({
      bst <- lightgbm(
        data = dtrain
        , params = params
        , nrounds = 2L
      )
    }, "every element in interaction_constraints must be a character vector or numeric vector")
})

test_that("lgb.train() throws an informative error if interaction_constraints contains a too large index", {
  dtrain <- lgb.Dataset(train$data, label = train$label)
  params <- list(objective = "regression",
                 interaction_constraints = list(c(1L, length(colnames(train$data)) + 1L), 3L))
    expect_error({
      bst <- lightgbm(
        data = dtrain
        , params = params
        , nrounds = 2L
      )
    }, "supplied a too large value in interaction_constraints")
})

test_that(paste0("lgb.train() gives same result when interaction_constraints is specified as a list of ",
                 "character vectors, numeric vectors, or a combination"), {
  set.seed(1L)
2792
  dtrain <- lgb.Dataset(train$data, label = train$label, params = list(num_threads = .LGB_MAX_THREADS))
2793

2794
2795
2796
  params <- list(
    objective = "regression"
    , interaction_constraints = list(c(1L, 2L), 3L)
2797
    , verbose = .LGB_VERBOSITY
2798
    , num_threads = .LGB_MAX_THREADS
2799
  )
2800
2801
2802
2803
2804
2805
2806
2807
  bst <- lightgbm(
    data = dtrain
    , params = params
    , nrounds = 2L
  )
  pred1 <- bst$predict(test$data)

  cnames <- colnames(train$data)
2808
2809
2810
  params <- list(
    objective = "regression"
    , interaction_constraints = list(c(cnames[[1L]], cnames[[2L]]), cnames[[3L]])
2811
    , verbose = .LGB_VERBOSITY
2812
    , num_threads = .LGB_MAX_THREADS
2813
  )
2814
2815
2816
2817
2818
2819
2820
  bst <- lightgbm(
    data = dtrain
    , params = params
    , nrounds = 2L
  )
  pred2 <- bst$predict(test$data)

2821
2822
2823
  params <- list(
    objective = "regression"
    , interaction_constraints = list(c(cnames[[1L]], cnames[[2L]]), 3L)
2824
    , verbose = .LGB_VERBOSITY
2825
    , num_threads = .LGB_MAX_THREADS
2826
  )
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
  bst <- lightgbm(
    data = dtrain
    , params = params
    , nrounds = 2L
  )
  pred3 <- bst$predict(test$data)

  expect_equal(pred1, pred2)
  expect_equal(pred2, pred3)

})

test_that(paste0("lgb.train() gives same results when using interaction_constraints and specifying colnames"), {
  set.seed(1L)
2841
  dtrain <- lgb.Dataset(train$data, label = train$label, params = list(num_threads = .LGB_MAX_THREADS))
2842

2843
2844
2845
  params <- list(
    objective = "regression"
    , interaction_constraints = list(c(1L, 2L), 3L)
2846
    , verbose = .LGB_VERBOSITY
2847
    , num_threads = .LGB_MAX_THREADS
2848
  )
2849
2850
2851
2852
2853
2854
2855
2856
  bst <- lightgbm(
    data = dtrain
    , params = params
    , nrounds = 2L
  )
  pred1 <- bst$predict(test$data)

  new_colnames <- paste0(colnames(train$data), "_x")
2857
2858
2859
  params <- list(
    objective = "regression"
    , interaction_constraints = list(c(new_colnames[1L], new_colnames[2L]), new_colnames[3L])
2860
    , verbose = .LGB_VERBOSITY
2861
    , num_threads = .LGB_MAX_THREADS
2862
  )
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
  bst <- lightgbm(
    data = dtrain
    , params = params
    , nrounds = 2L
    , colnames = new_colnames
  )
  pred2 <- bst$predict(test$data)

  expect_equal(pred1, pred2)

})
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910

.generate_trainset_for_monotone_constraints_tests <- function(x3_to_categorical) {
  n_samples <- 3000L
  x1_positively_correlated_with_y <- runif(n = n_samples, min = 0.0, max = 1.0)
  x2_negatively_correlated_with_y <- runif(n = n_samples, min = 0.0, max = 1.0)
  x3_negatively_correlated_with_y <- runif(n = n_samples, min = 0.0, max = 1.0)
  if (x3_to_categorical) {
    x3_negatively_correlated_with_y <- as.integer(x3_negatively_correlated_with_y / 0.01)
    categorical_features <- "feature_3"
  } else {
    categorical_features <- NULL
  }
  X <- matrix(
    data = c(
        x1_positively_correlated_with_y
        , x2_negatively_correlated_with_y
        , x3_negatively_correlated_with_y
    )
    , ncol = 3L
  )
  zs <- rnorm(n = n_samples, mean = 0.0, sd = 0.01)
  scales <- 10.0 * (runif(n = 6L, min = 0.0, max = 1.0) + 0.5)
  y <- (
    scales[1L] * x1_positively_correlated_with_y
    + sin(scales[2L] * pi * x1_positively_correlated_with_y)
    - scales[3L] * x2_negatively_correlated_with_y
    - cos(scales[4L] * pi * x2_negatively_correlated_with_y)
    - scales[5L] * x3_negatively_correlated_with_y
    - cos(scales[6L] * pi * x3_negatively_correlated_with_y)
    + zs
  )
  return(lgb.Dataset(
    data = X
    , label = y
    , categorical_feature = categorical_features
    , free_raw_data = FALSE
    , colnames = c("feature_1", "feature_2", "feature_3")
2911
    , params = list(num_threads = .LGB_MAX_THREADS)
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
  ))
}

.is_increasing <- function(y) {
  return(all(diff(y) >= 0.0))
}

.is_decreasing <- function(y) {
  return(all(diff(y) <= 0.0))
}

.is_non_monotone <- function(y) {
  return(any(diff(y) < 0.0) & any(diff(y) > 0.0))
}

# R equivalent of numpy.linspace()
.linspace <- function(start_val, stop_val, num) {
  weights <- (seq_len(num) - 1L) / (num - 1L)
  return(start_val + weights * (stop_val - start_val))
}

.is_correctly_constrained <- function(learner, x3_to_categorical) {
  iterations <- 10L
  n <- 1000L
  variable_x <- .linspace(0L, 1L, n)
  fixed_xs_values <- .linspace(0L, 1L, n)
  for (i in seq_len(iterations)) {
    fixed_x <- fixed_xs_values[i] * rep(1.0, n)
    monotonically_increasing_x <- matrix(
      data = c(variable_x, fixed_x, fixed_x)
      , ncol = 3L
    )
    monotonically_increasing_y <- predict(
      learner
      , monotonically_increasing_x
    )

    monotonically_decreasing_x <- matrix(
      data = c(fixed_x, variable_x, fixed_x)
      , ncol = 3L
    )
    monotonically_decreasing_y <- predict(
      learner
      , monotonically_decreasing_x
    )

    if (x3_to_categorical) {
      non_monotone_data <- c(
        fixed_x
        , fixed_x
        , as.integer(variable_x / 0.01)
      )
    } else {
      non_monotone_data <- c(fixed_x, fixed_x, variable_x)
    }
    non_monotone_x <- matrix(
      data = non_monotone_data
      , ncol = 3L
    )
    non_monotone_y <- predict(
      learner
      , non_monotone_x
    )
    if (!(.is_increasing(monotonically_increasing_y) &&
          .is_decreasing(monotonically_decreasing_y) &&
          .is_non_monotone(non_monotone_y)
    )) {
      return(FALSE)
    }
  }
  return(TRUE)
}

for (x3_to_categorical in c(TRUE, FALSE)) {
  set.seed(708L)
  dtrain <- .generate_trainset_for_monotone_constraints_tests(
    x3_to_categorical = x3_to_categorical
  )
  for (monotone_constraints_method in c("basic", "intermediate", "advanced")) {
    test_msg <- paste0(
      "lgb.train() supports monotone constraints ("
      , "categoricals="
      , x3_to_categorical
      , ", method="
      , monotone_constraints_method
      , ")"
    )
    test_that(test_msg, {
      params <- list(
        min_data = 20L
        , num_leaves = 20L
        , monotone_constraints = c(1L, -1L, 0L)
        , monotone_constraints_method = monotone_constraints_method
        , use_missing = FALSE
3006
        , verbose = .LGB_VERBOSITY
3007
        , num_threads = .LGB_MAX_THREADS
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
      )
      constrained_model <- lgb.train(
        params = params
        , data = dtrain
        , obj = "regression_l2"
        , nrounds = 100L
      )
      expect_true({
        .is_correctly_constrained(
          learner = constrained_model
          , x3_to_categorical = x3_to_categorical
        )
      })
    })
  }
}
3024
3025
3026
3027
3028

test_that("lightgbm() accepts objective as function argument and under params", {
  bst1 <- lightgbm(
    data = train$data
    , label = train$label
3029
    , params = list(objective = "regression_l1", num_threads = .LGB_MAX_THREADS)
3030
    , nrounds = 5L
3031
    , verbose = .LGB_VERBOSITY
3032
3033
3034
3035
3036
  )
  expect_equal(bst1$params$objective, "regression_l1")
  model_txt_lines <- strsplit(
    x = bst1$save_model_to_string()
    , split = "\n"
3037
    , fixed = TRUE
3038
3039
3040
3041
3042
3043
3044
3045
3046
  )[[1L]]
  expect_true(any(model_txt_lines == "objective=regression_l1"))
  expect_false(any(model_txt_lines == "objective=regression_l2"))

  bst2 <- lightgbm(
    data = train$data
    , label = train$label
    , objective = "regression_l1"
    , nrounds = 5L
3047
    , verbose = .LGB_VERBOSITY
3048
3049
3050
3051
3052
  )
  expect_equal(bst2$params$objective, "regression_l1")
  model_txt_lines <- strsplit(
    x = bst2$save_model_to_string()
    , split = "\n"
3053
    , fixed = TRUE
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
  )[[1L]]
  expect_true(any(model_txt_lines == "objective=regression_l1"))
  expect_false(any(model_txt_lines == "objective=regression_l2"))
})

test_that("lightgbm() prioritizes objective under params over objective as function argument", {
  bst1 <- lightgbm(
    data = train$data
    , label = train$label
    , objective = "regression"
3064
    , params = list(objective = "regression_l1", num_threads = .LGB_MAX_THREADS)
3065
    , nrounds = 5L
3066
    , verbose = .LGB_VERBOSITY
3067
3068
3069
3070
3071
  )
  expect_equal(bst1$params$objective, "regression_l1")
  model_txt_lines <- strsplit(
    x = bst1$save_model_to_string()
    , split = "\n"
3072
    , fixed = TRUE
3073
3074
3075
3076
3077
3078
3079
3080
  )[[1L]]
  expect_true(any(model_txt_lines == "objective=regression_l1"))
  expect_false(any(model_txt_lines == "objective=regression_l2"))

  bst2 <- lightgbm(
    data = train$data
    , label = train$label
    , objective = "regression"
3081
    , params = list(loss = "regression_l1", num_threads = .LGB_MAX_THREADS)
3082
    , nrounds = 5L
3083
    , verbose = .LGB_VERBOSITY
3084
3085
3086
3087
3088
  )
  expect_equal(bst2$params$objective, "regression_l1")
  model_txt_lines <- strsplit(
    x = bst2$save_model_to_string()
    , split = "\n"
3089
    , fixed = TRUE
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
  )[[1L]]
  expect_true(any(model_txt_lines == "objective=regression_l1"))
  expect_false(any(model_txt_lines == "objective=regression_l2"))
})

test_that("lightgbm() accepts init_score as function argument", {
  bst1 <- lightgbm(
    data = train$data
    , label = train$label
    , objective = "binary"
    , nrounds = 5L
3101
    , verbose = .LGB_VERBOSITY
3102
    , params = list(num_threads = .LGB_MAX_THREADS)
3103
  )
3104
  pred1 <- predict(bst1, train$data, type = "raw")
3105
3106
3107
3108
3109
3110
3111

  bst2 <- lightgbm(
    data = train$data
    , label = train$label
    , init_score = pred1
    , objective = "binary"
    , nrounds = 5L
3112
    , verbose = .LGB_VERBOSITY
3113
    , params = list(num_threads = .LGB_MAX_THREADS)
3114
  )
3115
  pred2 <- predict(bst2, train$data, type = "raw")
3116
3117
3118
3119
3120
3121
3122
3123
3124

  expect_true(any(pred1 != pred2))
})

test_that("lightgbm() defaults to 'regression' objective if objective not otherwise provided", {
  bst <- lightgbm(
    data = train$data
    , label = train$label
    , nrounds = 5L
3125
    , verbose = .LGB_VERBOSITY
3126
    , params = list(num_threads = .LGB_MAX_THREADS)
3127
3128
3129
3130
3131
  )
  expect_equal(bst$params$objective, "regression")
  model_txt_lines <- strsplit(
    x = bst$save_model_to_string()
    , split = "\n"
3132
    , fixed = TRUE
3133
3134
3135
3136
  )[[1L]]
  expect_true(any(model_txt_lines == "objective=regression"))
  expect_false(any(model_txt_lines == "objective=regression_l1"))
})
3137

3138
3139
3140
3141
3142
test_that("lightgbm() accepts 'num_threads' as either top-level argument or under params", {
  bst <- lightgbm(
    data = train$data
    , label = train$label
    , nrounds = 5L
3143
    , verbose = .LGB_VERBOSITY
3144
3145
3146
3147
3148
3149
    , num_threads = 1L
  )
  expect_equal(bst$params$num_threads, 1L)
  model_txt_lines <- strsplit(
    x = bst$save_model_to_string()
    , split = "\n"
3150
    , fixed = TRUE
3151
  )[[1L]]
3152
  expect_true(any(grepl("[num_threads: 1]", model_txt_lines, fixed = TRUE)))
3153
3154
3155
3156
3157

  bst <- lightgbm(
    data = train$data
    , label = train$label
    , nrounds = 5L
3158
    , verbose = .LGB_VERBOSITY
3159
3160
3161
3162
3163
3164
    , params = list(num_threads = 1L)
  )
  expect_equal(bst$params$num_threads, 1L)
  model_txt_lines <- strsplit(
    x = bst$save_model_to_string()
    , split = "\n"
3165
    , fixed = TRUE
3166
  )[[1L]]
3167
  expect_true(any(grepl("[num_threads: 1]", model_txt_lines, fixed = TRUE)))
3168
3169
3170
3171
3172

  bst <- lightgbm(
    data = train$data
    , label = train$label
    , nrounds = 5L
3173
    , verbose = .LGB_VERBOSITY
3174
3175
3176
3177
3178
3179
3180
    , num_threads = 10L
    , params = list(num_threads = 1L)
  )
  expect_equal(bst$params$num_threads, 1L)
  model_txt_lines <- strsplit(
    x = bst$save_model_to_string()
    , split = "\n"
3181
    , fixed = TRUE
3182
  )[[1L]]
3183
  expect_true(any(grepl("[num_threads: 1]", model_txt_lines, fixed = TRUE)))
3184
3185
})

3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
test_that("lightgbm() accepts 'weight' and 'weights'", {
  data(mtcars)
  X <- as.matrix(mtcars[, -1L])
  y <- as.numeric(mtcars[, 1L])
  w <- rep(1.0, nrow(X))
  model <- lightgbm(
    X
    , y
    , weights = w
    , obj = "regression"
    , nrounds = 5L
3197
    , verbose = .LGB_VERBOSITY
3198
3199
3200
    , params = list(
      min_data_in_bin = 1L
      , min_data_in_leaf = 1L
3201
      , num_threads = .LGB_MAX_THREADS
3202
    )
3203
  )
3204
  expect_equal(model$.__enclos_env__$private$train_set$get_field("weight"), w)
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215

  # Avoid a bad CRAN check due to partial argument matches
  lgb_args <- list(
    X
    , y
    , weight = w
    , obj = "regression"
    , nrounds = 5L
    , verbose = -1L
  )
  model <- do.call(lightgbm, lgb_args)
3216
  expect_equal(model$.__enclos_env__$private$train_set$get_field("weight"), w)
3217
})
3218

3219
.assert_has_expected_logs <- function(log_txt, lgb_info, lgb_warn, early_stopping, valid_eval_msg) {
3220
  expect_identical(
3221
    object = any(grepl("[LightGBM] [Info]", log_txt, fixed = TRUE))
3222
3223
3224
    , expected = lgb_info
  )
  expect_identical(
3225
    object = any(grepl("[LightGBM] [Warning]", log_txt, fixed = TRUE))
3226
3227
3228
    , expected = lgb_warn
  )
  expect_identical(
3229
    object = any(grepl("Will train until there is no improvement in 5 rounds", log_txt, fixed = TRUE))
3230
3231
3232
    , expected = early_stopping
  )
  expect_identical(
3233
    object = any(grepl("Did not meet early stopping", log_txt, fixed = TRUE))
3234
3235
3236
3237
3238
3239
3240
3241
    , expected = early_stopping
  )
  expect_identical(
    object = any(grepl("valid's auc\\:[0-9]+", log_txt))
    , expected = valid_eval_msg
  )
}

3242
.assert_has_expected_record_evals <- function(fitted_model) {
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
  record_evals <- fitted_model$record_evals
  expect_equal(record_evals$start_iter, 1L)
  if (inherits(fitted_model, "lgb.CVBooster")) {
    expected_valid_auc <- c(0.979056, 0.9844697, 0.9900813, 0.9908026, 0.9935588)
  } else {
    expected_valid_auc <-  c(0.9805752, 0.9805752, 0.9934957, 0.9934957, 0.9949372)
  }
  expect_equal(
    object = unlist(record_evals[["valid"]][["auc"]][["eval"]])
    , expected = expected_valid_auc
3253
    , tolerance = .LGB_NUMERIC_TOLERANCE
3254
  )
3255
   expect_named(record_evals, c("start_iter", "valid"), ignore.order = TRUE, ignore.case = FALSE)
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
  expect_equal(record_evals[["valid"]][["auc"]][["eval_err"]], list())
}

.train_for_verbosity_test <- function(train_function, verbose_kwarg, verbose_param) {
  set.seed(708L)
  nrounds <- 5L
  params <- list(
    num_leaves = 5L
    , objective = "binary"
    , metric =  "auc"
    , early_stopping_round = nrounds
3267
    , num_threads = .LGB_MAX_THREADS
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
  )
  if (!is.null(verbose_param)) {
    params[["verbose"]] <- verbose_param
  }
  train_kwargs <- list(
    params = params
    , nrounds = nrounds
  )
  if (!is.null(verbose_kwarg)) {
    train_kwargs[["verbose"]] <- verbose_kwarg
  }
  function_name <- deparse(substitute(train_function))
  if (function_name == "lgb.train") {
    train_kwargs[["data"]] <- lgb.Dataset(
      data = train$data
      , label = train$label
3284
      , params = list(num_threads = .LGB_MAX_THREADS)
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
    )
    train_kwargs[["valids"]] <- list(
      "valid" = lgb.Dataset(data = test$data, label = test$label)
    )
  } else if (function_name == "lightgbm") {
    train_kwargs[["data"]] <- train$data
    train_kwargs[["label"]] <- train$label
    train_kwargs[["valids"]] <- list(
      "valid" = lgb.Dataset(data = test$data, label = test$label)
    )
  } else if (function_name == "lgb.cv") {
    train_kwargs[["data"]] <- lgb.Dataset(
      data = train$data
      , label = train$label
    )
    train_kwargs[["nfold"]] <- 3L
    train_kwargs[["showsd"]] <- FALSE
  }
  log_txt <- capture.output({
    bst <- do.call(
      what = train_function
      , args = train_kwargs
    )
  })
  return(list(booster = bst, logs = log_txt))
}

test_that("lgb.train() only prints eval metrics when expected to", {

  # regardless of value passed to keyword argument 'verbose', value in params
  # should take precedence
  for (verbose_keyword_arg in c(-5L, -1L, 0L, 1L, 5L)) {

    # (verbose = -1) should not be any logs, should be record evals
    out <- .train_for_verbosity_test(
      train_function = lgb.train
      , verbose_kwarg = verbose_keyword_arg
      , verbose_param = -1L
    )
    .assert_has_expected_logs(
      log_txt = out[["logs"]]
      , lgb_info = FALSE
      , lgb_warn = FALSE
      , early_stopping = FALSE
      , valid_eval_msg = FALSE
    )
    .assert_has_expected_record_evals(
      fitted_model = out[["booster"]]
    )

    # (verbose = 0) should be only WARN-level LightGBM logs
    out <- .train_for_verbosity_test(
      train_function = lgb.train
      , verbose_kwarg = verbose_keyword_arg
      , verbose_param = 0L
    )
    .assert_has_expected_logs(
      log_txt = out[["logs"]]
      , lgb_info = FALSE
      , lgb_warn = TRUE
      , early_stopping = FALSE
      , valid_eval_msg = FALSE
    )
    .assert_has_expected_record_evals(
      fitted_model = out[["booster"]]
    )

    # (verbose > 0) should be INFO- and WARN-level LightGBM logs, and record eval messages
    out <- .train_for_verbosity_test(
      train_function = lgb.train
      , verbose_kwarg = verbose_keyword_arg
      , verbose_param = 1L
    )
    .assert_has_expected_logs(
      log_txt = out[["logs"]]
      , lgb_info = TRUE
      , lgb_warn = TRUE
      , early_stopping = TRUE
      , valid_eval_msg = TRUE
    )
    .assert_has_expected_record_evals(
      fitted_model = out[["booster"]]
    )
  }

  # if verbosity isn't specified in `params`, changing keyword argument `verbose` should
  # alter what messages are printed

  # (verbose = -1) should not be any logs, should be record evals
  out <- .train_for_verbosity_test(
    train_function = lgb.train
    , verbose_kwarg = -1L
    , verbose_param = NULL
  )
  .assert_has_expected_logs(
    log_txt = out[["logs"]]
    , lgb_info = FALSE
    , lgb_warn = FALSE
    , early_stopping = FALSE
    , valid_eval_msg = FALSE
  )
  .assert_has_expected_record_evals(
    fitted_model = out[["booster"]]
  )

  # (verbose = 0) should be only WARN-level LightGBM logs
  out <- .train_for_verbosity_test(
    train_function = lgb.train
    , verbose_kwarg = 0L
    , verbose_param = NULL
  )
  .assert_has_expected_logs(
    log_txt = out[["logs"]]
    , lgb_info = FALSE
    , lgb_warn = TRUE
    , early_stopping = FALSE
    , valid_eval_msg = FALSE
  )
  .assert_has_expected_record_evals(
    fitted_model = out[["booster"]]
  )

  # (verbose > 0) should be INFO- and WARN-level LightGBM logs, and record eval messages
  out <- .train_for_verbosity_test(
    train_function = lgb.train
    , verbose_kwarg = 1L
    , verbose_param = NULL
  )
  .assert_has_expected_logs(
    log_txt = out[["logs"]]
    , lgb_info = TRUE
    , lgb_warn = TRUE
    , early_stopping = TRUE
    , valid_eval_msg = TRUE
  )
  .assert_has_expected_record_evals(
    fitted_model = out[["booster"]]
  )
})

test_that("lightgbm() only prints eval metrics when expected to", {

  # regardless of value passed to keyword argument 'verbose', value in params
  # should take precedence
  for (verbose_keyword_arg in c(-5L, -1L, 0L, 1L, 5L)) {

    # (verbose = -1) should not be any logs, train should not be in valids
    out <- .train_for_verbosity_test(
      train_function = lightgbm
      , verbose_kwarg = verbose_keyword_arg
      , verbose_param = -1L
    )
    .assert_has_expected_logs(
      log_txt = out[["logs"]]
      , lgb_info = FALSE
      , lgb_warn = FALSE
      , early_stopping = FALSE
      , valid_eval_msg = FALSE
    )
    .assert_has_expected_record_evals(
      fitted_model = out[["booster"]]
    )

    # (verbose = 0) should be only WARN-level LightGBM logs, train should not be in valids
    out <- .train_for_verbosity_test(
      train_function = lightgbm
      , verbose_kwarg = verbose_keyword_arg
      , verbose_param = 0L
    )
    .assert_has_expected_logs(
      log_txt = out[["logs"]]
      , lgb_info = FALSE
      , lgb_warn = TRUE
      , early_stopping = FALSE
      , valid_eval_msg = FALSE
    )
    .assert_has_expected_record_evals(
      fitted_model = out[["booster"]]
    )

    # (verbose > 0) should be INFO- and WARN-level LightGBM logs, and record eval messages, and
    #               train should be in valids
    out <- .train_for_verbosity_test(
      train_function = lightgbm
      , verbose_kwarg = verbose_keyword_arg
      , verbose_param = 1L
    )
    .assert_has_expected_logs(
      log_txt = out[["logs"]]
      , lgb_info = TRUE
      , lgb_warn = TRUE
      , early_stopping = TRUE
      , valid_eval_msg = TRUE
    )
    .assert_has_expected_record_evals(
      fitted_model = out[["booster"]]
    )
  }

  # if verbosity isn't specified in `params`, changing keyword argument `verbose` should
  # alter what messages are printed

  # (verbose = -1) should not be any logs, train should not be in valids
  out <- .train_for_verbosity_test(
    train_function = lightgbm
    , verbose_kwarg = -1L
    , verbose_param = NULL
  )
  .assert_has_expected_logs(
    log_txt = out[["logs"]]
    , lgb_info = FALSE
    , lgb_warn = FALSE
    , early_stopping = FALSE
    , valid_eval_msg = FALSE
  )
  .assert_has_expected_record_evals(
    fitted_model = out[["booster"]]
  )

  # (verbose = 0) should be only WARN-level LightGBM logs, train should not be in valids
  out <- .train_for_verbosity_test(
    train_function = lightgbm
    , verbose_kwarg = 0L
    , verbose_param = NULL
  )
  .assert_has_expected_logs(
    log_txt = out[["logs"]]
    , lgb_info = FALSE
    , lgb_warn = TRUE
    , early_stopping = FALSE
    , valid_eval_msg = FALSE
  )
  .assert_has_expected_record_evals(
    fitted_model = out[["booster"]]
  )

  # (verbose > 0) should be INFO- and WARN-level LightGBM logs, and record eval messages, and
  #               train should be in valids
  out <- .train_for_verbosity_test(
    train_function = lightgbm
    , verbose_kwarg = 1L
    , verbose_param = NULL
  )
  .assert_has_expected_logs(
    log_txt = out[["logs"]]
    , lgb_info = TRUE
    , lgb_warn = TRUE
    , early_stopping = TRUE
    , valid_eval_msg = TRUE
  )
  .assert_has_expected_record_evals(
    fitted_model = out[["booster"]]
  )
})

test_that("lgb.cv() only prints eval metrics when expected to", {

  # regardless of value passed to keyword argument 'verbose', value in params
  # should take precedence
  for (verbose_keyword_arg in c(-5L, -1L, 0L, 1L, 5L)) {

    # (verbose = -1) should not be any logs, should be record evals
    out <- .train_for_verbosity_test(
      verbose_kwarg = verbose_keyword_arg
      , verbose_param = -1L
      , train_function = lgb.cv
    )
    .assert_has_expected_logs(
      log_txt = out[["logs"]]
      , lgb_info = FALSE
      , lgb_warn = FALSE
      , early_stopping = FALSE
      , valid_eval_msg = FALSE
    )
    .assert_has_expected_record_evals(
      fitted_model = out[["booster"]]
    )

    # (verbose = 0) should be only WARN-level LightGBM logs
    out <- .train_for_verbosity_test(
      verbose_kwarg = verbose_keyword_arg
      , verbose_param = 0L
      , train_function = lgb.cv
    )
    .assert_has_expected_logs(
      log_txt = out[["logs"]]
      , lgb_info = FALSE
      , lgb_warn = TRUE
      , early_stopping = FALSE
      , valid_eval_msg = FALSE
    )
    .assert_has_expected_record_evals(
      fitted_model = out[["booster"]]
    )

    # (verbose > 0) should be INFO- and WARN-level LightGBM logs, and record eval messages
    out <- .train_for_verbosity_test(
      verbose_kwarg = verbose_keyword_arg
      , verbose_param = 1L
      , train_function = lgb.cv
    )
    .assert_has_expected_logs(
      log_txt = out[["logs"]]
      , lgb_info = TRUE
      , lgb_warn = TRUE
      , early_stopping = TRUE
      , valid_eval_msg = TRUE
    )
    .assert_has_expected_record_evals(
      fitted_model = out[["booster"]]
    )
  }

  # if verbosity isn't specified in `params`, changing keyword argument `verbose` should
  # alter what messages are printed

  # (verbose = -1) should not be any logs, should be record evals
  out <- .train_for_verbosity_test(
    verbose_kwarg = verbose_keyword_arg
    , verbose_param = -1L
    , train_function = lgb.cv
  )
  .assert_has_expected_logs(
    log_txt = out[["logs"]]
    , lgb_info = FALSE
    , lgb_warn = FALSE
    , early_stopping = FALSE
    , valid_eval_msg = FALSE
  )
  .assert_has_expected_record_evals(
    fitted_model = out[["booster"]]
  )

  # (verbose = 0) should be only WARN-level LightGBM logs
  out <- .train_for_verbosity_test(
    verbose_kwarg = verbose_keyword_arg
    , verbose_param = 0L
    , train_function = lgb.cv
  )
  .assert_has_expected_logs(
    log_txt = out[["logs"]]
    , lgb_info = FALSE
    , lgb_warn = TRUE
    , early_stopping = FALSE
    , valid_eval_msg = FALSE
  )
  .assert_has_expected_record_evals(
    fitted_model = out[["booster"]]
  )

  # (verbose > 0) should be INFO- and WARN-level LightGBM logs, and record eval messages
  out <- .train_for_verbosity_test(
    verbose_kwarg = verbose_keyword_arg
    , verbose_param = 1L
    , train_function = lgb.cv
  )
  .assert_has_expected_logs(
    log_txt = out[["logs"]]
    , lgb_info = TRUE
    , lgb_warn = TRUE
    , early_stopping = TRUE
    , valid_eval_msg = TRUE
  )
  .assert_has_expected_record_evals(
    fitted_model = out[["booster"]]
  )
})
3652
3653
3654
3655
3656
3657

test_that("lightgbm() changes objective='auto' appropriately", {
  # Regression
  data("mtcars")
  y <- mtcars$mpg
  x <- as.matrix(mtcars[, -1L])
3658
  model <- lightgbm(x, y, objective = "auto", verbose = .LGB_VERBOSITY, nrounds = 5L, num_threads = .LGB_MAX_THREADS)
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
  expect_equal(model$params$objective, "regression")
  model_txt_lines <- strsplit(
    x = model$save_model_to_string()
    , split = "\n"
    , fixed = TRUE
  )[[1L]]
  expect_true(any(grepl("objective=regression", model_txt_lines, fixed = TRUE)))
  expect_false(any(grepl("objective=regression_l1", model_txt_lines, fixed = TRUE)))

  # Binary classification
  x <- train$data
  y <- factor(train$label)
3671
  model <- lightgbm(x, y, objective = "auto", verbose = .LGB_VERBOSITY, nrounds = 5L, num_threads = .LGB_MAX_THREADS)
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
  expect_equal(model$params$objective, "binary")
  model_txt_lines <- strsplit(
    x = model$save_model_to_string()
    , split = "\n"
    , fixed = TRUE
  )[[1L]]
  expect_true(any(grepl("objective=binary", model_txt_lines, fixed = TRUE)))

  # Multi-class classification
  data("iris")
  y <- factor(iris$Species)
  x <- as.matrix(iris[, -5L])
3684
  model <- lightgbm(x, y, objective = "auto", verbose = .LGB_VERBOSITY, nrounds = 5L, num_threads = .LGB_MAX_THREADS)
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
  expect_equal(model$params$objective, "multiclass")
  expect_equal(model$params$num_class, 3L)
  model_txt_lines <- strsplit(
    x = model$save_model_to_string()
    , split = "\n"
    , fixed = TRUE
  )[[1L]]
  expect_true(any(grepl("objective=multiclass", model_txt_lines, fixed = TRUE)))
})

test_that("lightgbm() determines number of classes for non-default multiclass objectives", {
  data("iris")
  y <- factor(iris$Species)
  x <- as.matrix(iris[, -5L])
3699
3700
3701
3702
  model <- lightgbm(
    x
    , y
    , objective = "multiclassova"
3703
    , verbose = .LGB_VERBOSITY
3704
3705
3706
    , nrounds = 5L
    , num_threads = .LGB_MAX_THREADS
  )
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
  expect_equal(model$params$objective, "multiclassova")
  expect_equal(model$params$num_class, 3L)
  model_txt_lines <- strsplit(
    x = model$save_model_to_string()
    , split = "\n"
    , fixed = TRUE
  )[[1L]]
  expect_true(any(grepl("objective=multiclassova", model_txt_lines, fixed = TRUE)))
})

test_that("lightgbm() doesn't accept binary classification with non-binary factors", {
  data("iris")
  y <- factor(iris$Species)
  x <- as.matrix(iris[, -5L])
  expect_error({
3722
    lightgbm(x, y, objective = "binary", verbose = .LGB_VERBOSITY, nrounds = 5L, num_threads = .LGB_MAX_THREADS)
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
  }, regexp = "Factors with >2 levels as labels only allowed for multi-class objectives")
})

test_that("lightgbm() doesn't accept multi-class classification with binary factors", {
  data("iris")
  y <- as.character(iris$Species)
  y[y == "setosa"] <- "versicolor"
  y <- factor(y)
  x <- as.matrix(iris[, -5L])
  expect_error({
3733
    lightgbm(x, y, objective = "multiclass", verbose = .LGB_VERBOSITY, nrounds = 5L, num_threads = .LGB_MAX_THREADS)
3734
3735
3736
3737
3738
3739
3740
  }, regexp = "Two-level factors as labels only allowed for objective='binary'")
})

test_that("lightgbm() model predictions retain factor levels for multiclass classification", {
  data("iris")
  y <- factor(iris$Species)
  x <- as.matrix(iris[, -5L])
3741
  model <- lightgbm(x, y, objective = "auto", verbose = .LGB_VERBOSITY, nrounds = 5L, num_threads = .LGB_MAX_THREADS)
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759

  pred <- predict(model, x, type = "class")
  expect_true(is.factor(pred))
  expect_equal(levels(pred), levels(y))

  pred <- predict(model, x, type = "response")
  expect_equal(colnames(pred), levels(y))

  pred <- predict(model, x, type = "raw")
  expect_equal(colnames(pred), levels(y))
})

test_that("lightgbm() model predictions retain factor levels for binary classification", {
  data("iris")
  y <- as.character(iris$Species)
  y[y == "setosa"] <- "versicolor"
  y <- factor(y)
  x <- as.matrix(iris[, -5L])
3760
  model <- lightgbm(x, y, objective = "auto", verbose = .LGB_VERBOSITY, nrounds = 5L, num_threads = .LGB_MAX_THREADS)
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775

  pred <- predict(model, x, type = "class")
  expect_true(is.factor(pred))
  expect_equal(levels(pred), levels(y))

  pred <- predict(model, x, type = "response")
  expect_true(is.vector(pred))
  expect_true(is.numeric(pred))
  expect_false(any(pred %in% y))

  pred <- predict(model, x, type = "raw")
  expect_true(is.vector(pred))
  expect_true(is.numeric(pred))
  expect_false(any(pred %in% y))
})
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790

test_that("lightgbm() accepts named categorical_features", {
  data(mtcars)
  y <- mtcars$mpg
  x <- as.matrix(mtcars[, -1L])
  model <- lightgbm(
    x
    , y
    , categorical_feature = "cyl"
    , verbose = .LGB_VERBOSITY
    , nrounds = 5L
    , num_threads = .LGB_MAX_THREADS
  )
  expect_true(length(model$params$categorical_feature) > 0L)
})