test_lgb.Booster.R 43.6 KB
Newer Older
1
2
3
4
VERBOSITY <- as.integer(
  Sys.getenv("LIGHTGBM_TEST_VERBOSITY", "-1")
)

5
ON_WINDOWS <- .Platform$OS.type == "windows"
6
7
TOLERANCE <- 1e-6

8
9
10
11
12
13
test_that("Booster$finalize() should not fail", {
    X <- as.matrix(as.integer(iris[, "Species"]), ncol = 1L)
    y <- iris[["Sepal.Length"]]
    dtrain <- lgb.Dataset(X, label = y)
    bst <- lgb.train(
        data = dtrain
14
15
        , params = list(
            objective = "regression"
16
            , num_threads = .LGB_MAX_THREADS
17
        )
18
        , verbose = VERBOSITY
19
20
21
22
23
24
25
26
27
28
29
30
31
32
        , nrounds = 3L
    )
    expect_true(lgb.is.Booster(bst))

    expect_false(lgb.is.null.handle(bst$.__enclos_env__$private$handle))

    bst$finalize()
    expect_true(lgb.is.null.handle(bst$.__enclos_env__$private$handle))

    # calling finalize() a second time shouldn't cause any issues
    bst$finalize()
    expect_true(lgb.is.null.handle(bst$.__enclos_env__$private$handle))
})

33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
test_that("lgb.get.eval.result() should throw an informative error if booster is not an lgb.Booster", {
    bad_inputs <- list(
        matrix(1.0:10.0, 2L, 5L)
        , TRUE
        , c("a", "b")
        , NA
        , 10L
        , lgb.Dataset(
            data = matrix(1.0:10.0, 2L, 5L)
            , params = list()
        )
    )
    for (bad_input in bad_inputs) {
        expect_error({
            lgb.get.eval.result(
                booster = bad_input
                , data_name = "test"
                , eval_name = "l2"
            )
        }, regexp = "Can only use", fixed = TRUE)
    }
})

test_that("lgb.get.eval.result() should throw an informative error for incorrect data_name", {
    data(agaricus.train, package = "lightgbm")
    data(agaricus.test, package = "lightgbm")
    dtrain <- lgb.Dataset(
        agaricus.train$data
        , label = agaricus.train$label
    )
    model <- lgb.train(
        params = list(
            objective = "regression"
            , metric = "l2"
67
68
            , min_data = 1L
            , learning_rate = 1.0
69
            , verbose = VERBOSITY
70
            , num_threads = .LGB_MAX_THREADS
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
        )
        , data = dtrain
        , nrounds = 5L
        , valids = list(
            "test" = lgb.Dataset.create.valid(
                dtrain
                , agaricus.test$data
                , label = agaricus.test$label
            )
        )
    )
    expect_error({
        eval_results <- lgb.get.eval.result(
            booster = model
            , data_name = "testing"
            , eval_name = "l2"
        )
    }, regexp = "Only the following datasets exist in record evals: [test]", fixed = TRUE)
})

test_that("lgb.get.eval.result() should throw an informative error for incorrect eval_name", {
    data(agaricus.train, package = "lightgbm")
    data(agaricus.test, package = "lightgbm")
    dtrain <- lgb.Dataset(
        agaricus.train$data
        , label = agaricus.train$label
    )
    model <- lgb.train(
        params = list(
            objective = "regression"
            , metric = "l2"
102
103
            , min_data = 1L
            , learning_rate = 1.0
104
            , verbose = VERBOSITY
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
        )
        , data = dtrain
        , nrounds = 5L
        , valids = list(
            "test" = lgb.Dataset.create.valid(
                dtrain
                , agaricus.test$data
                , label = agaricus.test$label
            )
        )
    )
    expect_error({
        eval_results <- lgb.get.eval.result(
            booster = model
            , data_name = "test"
            , eval_name = "l1"
        )
122
    }, regexp = "Only the following eval_names exist for dataset.*\\: \\[l2\\]", fixed = FALSE)
123
})
124
125
126
127
128
129
130
131
132
133

test_that("lgb.load() gives the expected error messages given different incorrect inputs", {
    set.seed(708L)
    data(agaricus.train, package = "lightgbm")
    data(agaricus.test, package = "lightgbm")
    train <- agaricus.train
    test <- agaricus.test
    bst <- lightgbm(
        data = as.matrix(train$data)
        , label = train$label
134
135
136
137
        , params = list(
            objective = "binary"
            , num_leaves = 4L
            , learning_rate = 1.0
138
            , verbose = VERBOSITY
139
        )
140
141
142
143
144
145
146
147
148
149
150
151
        , nrounds = 2L
    )

    # you have to give model_str or filename
    expect_error({
        lgb.load()
    }, regexp = "either filename or model_str must be given")
    expect_error({
        lgb.load(filename = NULL, model_str = NULL)
    }, regexp = "either filename or model_str must be given")

    # if given, filename should be a string that points to an existing file
152
    model_file <- tempfile(fileext = ".model")
153
    expect_error({
154
        lgb.load(filename = list(model_file))
155
156
157
158
159
160
161
162
163
164
165
166
    }, regexp = "filename should be character")
    file_to_check <- paste0("a.model")
    while (file.exists(file_to_check)) {
        file_to_check <- paste0("a", file_to_check)
    }
    expect_error({
        lgb.load(filename = file_to_check)
    }, regexp = "passed to filename does not exist")

    # if given, model_str should be a string
    expect_error({
        lgb.load(model_str = c(4.0, 5.0, 6.0))
167
    }, regexp = "lgb.load: model_str should be a character/raw vector")
168
169
170

})

171
test_that("Loading a Booster from a text file works", {
172
173
174
175
176
    set.seed(708L)
    data(agaricus.train, package = "lightgbm")
    data(agaricus.test, package = "lightgbm")
    train <- agaricus.train
    test <- agaricus.test
177
178
179
180
181
182
183
184
185
186
187
188
189
    params <- list(
        num_leaves = 4L
        , boosting = "rf"
        , bagging_fraction = 0.8
        , bagging_freq = 1L
        , boost_from_average = FALSE
        , categorical_feature = c(1L, 2L)
        , interaction_constraints = list(c(1L, 2L), 1L)
        , feature_contri = rep(0.5, ncol(train$data))
        , metric = c("mape", "average_precision")
        , learning_rate = 1.0
        , objective = "binary"
        , verbosity = VERBOSITY
190
        , num_threads = .LGB_MAX_THREADS
191
    )
192
193
194
    bst <- lightgbm(
        data = as.matrix(train$data)
        , label = train$label
195
        , params = params
196
197
198
199
200
        , nrounds = 2L
    )
    expect_true(lgb.is.Booster(bst))

    pred <- predict(bst, test$data)
201
202
    model_file <- tempfile(fileext = ".model")
    lgb.save(bst, model_file)
203
204
205
206
207
208
209

    # finalize the booster and destroy it so you know we aren't cheating
    bst$finalize()
    expect_null(bst$.__enclos_env__$private$handle)
    rm(bst)

    bst2 <- lgb.load(
210
        filename = model_file
211
212
213
    )
    pred2 <- predict(bst2, test$data)
    expect_identical(pred, pred2)
214
215
216

    # check that the parameters are loaded correctly
    expect_equal(bst2$params[names(params)], params)
217
218
})

219
220
221
222
223
224
225
226
227
228
229
230
231
232
test_that("boosters with linear models at leaves can be written to text file and re-loaded successfully", {
    X <- matrix(rnorm(100L), ncol = 1L)
    labels <- 2L * X + runif(nrow(X), 0L, 0.1)
    dtrain <- lgb.Dataset(
        data = X
        , label = labels
    )

    params <- list(
        objective = "regression"
        , verbose = -1L
        , metric = "mse"
        , seed = 0L
        , num_leaves = 2L
233
        , num_threads = .LGB_MAX_THREADS
234
235
236
237
238
239
    )

    bst <- lgb.train(
        data = dtrain
        , nrounds = 10L
        , params = params
240
        , verbose = VERBOSITY
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
    )
    expect_true(lgb.is.Booster(bst))

    # save predictions, then write the model to a file and destroy it in R
    preds <- predict(bst, X)
    model_file <- tempfile(fileext = ".model")
    lgb.save(bst, model_file)
    bst$finalize()
    expect_null(bst$.__enclos_env__$private$handle)
    rm(bst)

    # load the booster and make predictions...should be the same
    bst2 <- lgb.load(
        filename = model_file
    )
256
257
    preds2 <- predict(bst2, X)
    expect_identical(preds, preds2)
258
259
260
})


261
262
263
264
265
266
267
268
269
test_that("Loading a Booster from a string works", {
    set.seed(708L)
    data(agaricus.train, package = "lightgbm")
    data(agaricus.test, package = "lightgbm")
    train <- agaricus.train
    test <- agaricus.test
    bst <- lightgbm(
        data = as.matrix(train$data)
        , label = train$label
270
271
272
273
        , params = list(
            num_leaves = 4L
            , learning_rate = 1.0
            , objective = "binary"
274
            , verbose = VERBOSITY
275
            , num_threads = .LGB_MAX_THREADS
276
        )
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
        , nrounds = 2L
    )
    expect_true(lgb.is.Booster(bst))

    pred <- predict(bst, test$data)
    model_string <- bst$save_model_to_string()

    # finalize the booster and destroy it so you know we aren't cheating
    bst$finalize()
    expect_null(bst$.__enclos_env__$private$handle)
    rm(bst)

    bst2 <- lgb.load(
        model_str = model_string
    )
    pred2 <- predict(bst2, test$data)
    expect_identical(pred, pred2)
})

296
297
298
299
300
301
302
test_that("Saving a large model to string should work", {
    set.seed(708L)
    data(agaricus.train, package = "lightgbm")
    train <- agaricus.train
    bst <- lightgbm(
        data = as.matrix(train$data)
        , label = train$label
303
304
305
306
        , params = list(
            num_leaves = 100L
            , learning_rate = 0.01
            , objective = "binary"
307
            , num_threads = .LGB_MAX_THREADS
308
        )
309
        , nrounds = 500L
310
        , verbose = VERBOSITY
311
312
313
    )

    pred <- predict(bst, train$data)
314
315
    pred_leaf_indx <- predict(bst, train$data, type = "leaf")
    pred_raw_score <- predict(bst, train$data, type = "raw")
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
    model_string <- bst$save_model_to_string()

    # make sure this test is still producing a model bigger than the default
    # buffer size used in LGBM_BoosterSaveModelToString_R
    expect_gt(nchar(model_string), 1024L * 1024L)

    # finalize the booster and destroy it so you know we aren't cheating
    bst$finalize()
    expect_null(bst$.__enclos_env__$private$handle)
    rm(bst)

    # make sure a new model can be created from this string, and that it
    # produces expected results
    bst2 <- lgb.load(
        model_str = model_string
    )
    pred2 <- predict(bst2, train$data)
333
334
    pred2_leaf_indx <- predict(bst2, train$data, type = "leaf")
    pred2_raw_score <- predict(bst2, train$data, type = "raw")
335
336
337
338
339
340
341
342
343
344
345
346
    expect_identical(pred, pred2)
    expect_identical(pred_leaf_indx, pred2_leaf_indx)
    expect_identical(pred_raw_score, pred2_raw_score)
})

test_that("Saving a large model to JSON should work", {
    set.seed(708L)
    data(agaricus.train, package = "lightgbm")
    train <- agaricus.train
    bst <- lightgbm(
        data = as.matrix(train$data)
        , label = train$label
347
348
349
350
        , params = list(
            num_leaves = 100L
            , learning_rate = 0.01
            , objective = "binary"
351
            , num_threads = .LGB_MAX_THREADS
352
        )
353
        , nrounds = 200L
354
        , verbose = VERBOSITY
355
356
357
358
359
360
361
362
363
364
365
366
367
    )

    model_json <- bst$dump_model()

    # make sure this test is still producing a model bigger than the default
    # buffer size used in LGBM_BoosterDumpModel_R
    expect_gt(nchar(model_json), 1024L * 1024L)

    # check that it is valid JSON that looks like a LightGBM model
    model_list <- jsonlite::fromJSON(model_json)
    expect_equal(model_list[["objective"]], "binary sigmoid:1")
})

368
369
370
371
372
373
374
375
376
test_that("If a string and a file are both passed to lgb.load() the file is used model_str is totally ignored", {
    set.seed(708L)
    data(agaricus.train, package = "lightgbm")
    data(agaricus.test, package = "lightgbm")
    train <- agaricus.train
    test <- agaricus.test
    bst <- lightgbm(
        data = as.matrix(train$data)
        , label = train$label
377
378
379
380
        , params = list(
            num_leaves = 4L
            , learning_rate = 1.0
            , objective = "binary"
381
            , verbose = VERBOSITY
382
            , num_threads = .LGB_MAX_THREADS
383
        )
384
385
386
387
388
        , nrounds = 2L
    )
    expect_true(lgb.is.Booster(bst))

    pred <- predict(bst, test$data)
389
390
    model_file <- tempfile(fileext = ".model")
    lgb.save(bst, model_file)
391
392
393
394
395
396
397

    # finalize the booster and destroy it so you know we aren't cheating
    bst$finalize()
    expect_null(bst$.__enclos_env__$private$handle)
    rm(bst)

    bst2 <- lgb.load(
398
        filename = model_file
399
400
401
402
403
        , model_str = 4.0
    )
    pred2 <- predict(bst2, test$data)
    expect_identical(pred, pred2)
})
404
405
406
407
408
409
410
411
412
413
414
415

test_that("Creating a Booster from a Dataset should work", {
    set.seed(708L)
    data(agaricus.train, package = "lightgbm")
    data(agaricus.test, package = "lightgbm")
    dtrain <- lgb.Dataset(
        agaricus.train$data
        , label = agaricus.train$label
    )
    bst <- Booster$new(
        params = list(
            objective = "binary"
416
            , verbose = VERBOSITY
417
            , num_threads = .LGB_MAX_THREADS
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
        ),
        train_set = dtrain
    )
    expect_true(lgb.is.Booster(bst))
    expect_equal(bst$current_iter(), 0L)
    expect_true(is.na(bst$best_score))
    expect_true(all(bst$predict(agaricus.train$data) == 0.5))
})

test_that("Creating a Booster from a Dataset with an existing predictor should work", {
    set.seed(708L)
    data(agaricus.train, package = "lightgbm")
    nrounds <- 2L
    bst <- lightgbm(
        data = as.matrix(agaricus.train$data)
        , label = agaricus.train$label
434
435
436
437
        , params = list(
            num_leaves = 4L
            , learning_rate = 1.0
            , objective = "binary"
438
            , verbose = VERBOSITY
439
            , num_threads = .LGB_MAX_THREADS
440
        )
441
442
443
444
445
446
447
448
449
450
        , nrounds = nrounds
    )
    data(agaricus.test, package = "lightgbm")
    dtest <- Dataset$new(
        data = agaricus.test$data
        , label = agaricus.test$label
        , predictor = bst$to_predictor()
    )
    bst_from_ds <- Booster$new(
        train_set = dtest
451
452
        , params = list(
            verbose = VERBOSITY
453
            , num_threads = .LGB_MAX_THREADS
454
        )
455
456
457
458
    )
    expect_true(lgb.is.Booster(bst))
    expect_equal(bst$current_iter(), nrounds)
    expect_equal(bst$eval_train()[[1L]][["value"]], 0.1115352)
459
    expect_true(lgb.is.Booster(bst_from_ds))
460
    expect_equal(bst_from_ds$current_iter(), nrounds)
461
    expect_equal(bst_from_ds$eval_train()[[1L]][["value"]], 5.65704892)
462
463
    dumped_model <- jsonlite::fromJSON(bst$dump_model())
})
464

465
466
467
468
469
470
471
472
473
474
475
test_that("Booster$eval() should work on a Dataset stored in a binary file", {
    set.seed(708L)
    data(agaricus.train, package = "lightgbm")
    train <- agaricus.train
    dtrain <- lgb.Dataset(train$data, label = train$label)

    bst <- lgb.train(
        params = list(
            objective = "regression"
            , metric = "l2"
            , num_leaves = 4L
476
            , verbose = VERBOSITY
477
            , num_threads = .LGB_MAX_THREADS
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
        )
        , data = dtrain
        , nrounds = 2L
    )

    data(agaricus.test, package = "lightgbm")
    test <- agaricus.test
    dtest <- lgb.Dataset.create.valid(
        dataset = dtrain
        , data = test$data
        , label = test$label
    )
    dtest$construct()

    eval_in_mem <- bst$eval(
        data = dtest
        , name = "test"
    )

    test_file <- tempfile(pattern = "lgb.Dataset_")
    lgb.Dataset.save(
        dataset = dtest
        , fname = test_file
    )
    rm(dtest)

    eval_from_file <- bst$eval(
        data = lgb.Dataset(
            data = test_file
507
            , params = list(verbose = VERBOSITY, num_threads = .LGB_MAX_THREADS)
508
509
510
511
512
        )$construct()
        , name = "test"
    )

    expect_true(abs(eval_in_mem[[1L]][["value"]] - 0.1744423) < TOLERANCE)
513
    # refer to https://github.com/microsoft/LightGBM/issues/4680
514
515
516
517
518
    if (isTRUE(ON_WINDOWS)) {
      expect_equal(eval_in_mem, eval_from_file)
    } else {
      expect_identical(eval_in_mem, eval_from_file)
    }
519
520
})

521
522
523
524
525
526
527
528
529
530
test_that("Booster$rollback_one_iter() should work as expected", {
    set.seed(708L)
    data(agaricus.train, package = "lightgbm")
    data(agaricus.test, package = "lightgbm")
    train <- agaricus.train
    test <- agaricus.test
    nrounds <- 5L
    bst <- lightgbm(
        data = as.matrix(train$data)
        , label = train$label
531
532
533
534
        , params = list(
            num_leaves = 4L
            , learning_rate = 1.0
            , objective = "binary"
535
            , verbose = VERBOSITY
536
            , num_threads = .LGB_MAX_THREADS
537
        )
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
        , nrounds = nrounds
    )
    expect_equal(bst$current_iter(), nrounds)
    expect_true(lgb.is.Booster(bst))
    logloss <- bst$eval_train()[[1L]][["value"]]
    expect_equal(logloss, 0.01904786)

    x <- bst$rollback_one_iter()

    # rollback_one_iter() should return a booster and modify the original
    # booster in place
    expect_true(lgb.is.Booster(x))
    expect_equal(bst$current_iter(), nrounds - 1L)

    # score should now come from the model as of 4 iterations
    logloss <- bst$eval_train()[[1L]][["value"]]
    expect_equal(logloss, 0.027915146)
})
556
557
558
559
560
561
562
563
564
565

test_that("Booster$update() passing a train_set works as expected", {
    set.seed(708L)
    data(agaricus.train, package = "lightgbm")
    nrounds <- 2L

    # train with 2 rounds and then update
    bst <- lightgbm(
        data = as.matrix(agaricus.train$data)
        , label = agaricus.train$label
566
567
568
569
        , params = list(
            num_leaves = 4L
            , learning_rate = 1.0
            , objective = "binary"
570
            , verbose = VERBOSITY
571
            , num_threads = .LGB_MAX_THREADS
572
        )
573
574
575
576
577
578
579
580
        , nrounds = nrounds
    )
    expect_true(lgb.is.Booster(bst))
    expect_equal(bst$current_iter(), nrounds)
    bst$update(
        train_set = Dataset$new(
            data = agaricus.train$data
            , label = agaricus.train$label
581
            , params = list(verbose = VERBOSITY)
582
583
584
585
586
        )
    )
    expect_true(lgb.is.Booster(bst))
    expect_equal(bst$current_iter(), nrounds + 1L)

587
    # train with 3 rounds directly
588
589
590
    bst2 <- lightgbm(
        data = as.matrix(agaricus.train$data)
        , label = agaricus.train$label
591
592
593
594
        , params = list(
            num_leaves = 4L
            , learning_rate = 1.0
            , objective = "binary"
595
            , verbose = VERBOSITY
596
            , num_threads = .LGB_MAX_THREADS
597
        )
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
        , nrounds = nrounds +  1L
    )
    expect_true(lgb.is.Booster(bst2))
    expect_equal(bst2$current_iter(), nrounds +  1L)

    # model with 2 rounds + 1 update should be identical to 3 rounds
    expect_equal(bst2$eval_train()[[1L]][["value"]], 0.04806585)
    expect_equal(bst$eval_train()[[1L]][["value"]], bst2$eval_train()[[1L]][["value"]])
})

test_that("Booster$update() throws an informative error if you provide a non-Dataset to update()", {
    set.seed(708L)
    data(agaricus.train, package = "lightgbm")
    nrounds <- 2L

    # train with 2 rounds and then update
    bst <- lightgbm(
        data = as.matrix(agaricus.train$data)
        , label = agaricus.train$label
617
618
619
620
        , params = list(
            num_leaves = 4L
            , learning_rate = 1.0
            , objective = "binary"
621
            , verbose = VERBOSITY
622
            , num_threads = .LGB_MAX_THREADS
623
        )
624
625
626
627
628
629
630
631
        , nrounds = nrounds
    )
    expect_error({
        bst$update(
            train_set = data.frame(x = rnorm(10L))
        )
    }, regexp = "lgb.Booster.update: Only can use lgb.Dataset", fixed = TRUE)
})
632

633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
test_that("Booster should store parameters and Booster$reset_parameter() should update them", {
    data(agaricus.train, package = "lightgbm")
    dtrain <- lgb.Dataset(
        agaricus.train$data
        , label = agaricus.train$label
    )
    # testing that this works for some cases that could break it:
    #    - multiple metrics
    #    - using "metric", "boosting", "num_class" in params
    params <- list(
        objective = "multiclass"
        , max_depth = 4L
        , bagging_fraction = 0.8
        , metric = c("multi_logloss", "multi_error")
        , boosting = "gbdt"
        , num_class = 5L
649
        , verbose = VERBOSITY
650
        , num_threads = .LGB_MAX_THREADS
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
    )
    bst <- Booster$new(
        params = params
        , train_set = dtrain
    )
    expect_identical(bst$params, params)

    params[["bagging_fraction"]] <- 0.9
    ret_bst <- bst$reset_parameter(params = params)
    expect_identical(ret_bst$params, params)
    expect_identical(bst$params, params)
})

test_that("Booster$params should include dataset params, before and after Booster$reset_parameter()", {
    data(agaricus.train, package = "lightgbm")
    dtrain <- lgb.Dataset(
        agaricus.train$data
        , label = agaricus.train$label
        , params = list(
            max_bin = 17L
        )
    )
    params <- list(
        objective = "binary"
        , max_depth = 4L
        , bagging_fraction = 0.8
677
        , verbose = VERBOSITY
678
        , num_threads = .LGB_MAX_THREADS
679
680
681
682
683
684
685
686
687
688
689
    )
    bst <- Booster$new(
        params = params
        , train_set = dtrain
    )
    expect_identical(
        bst$params
        , list(
            objective = "binary"
            , max_depth = 4L
            , bagging_fraction = 0.8
690
            , verbose = VERBOSITY
691
            , num_threads = .LGB_MAX_THREADS
692
693
694
695
696
697
698
699
700
701
            , max_bin = 17L
        )
    )

    params[["bagging_fraction"]] <- 0.9
    ret_bst <- bst$reset_parameter(params = params)
    expected_params <- list(
        objective = "binary"
        , max_depth = 4L
        , bagging_fraction = 0.9
702
        , verbose = VERBOSITY
703
        , num_threads = .LGB_MAX_THREADS
704
705
706
707
708
709
        , max_bin = 17L
    )
    expect_identical(ret_bst$params, expected_params)
    expect_identical(bst$params, expected_params)
})

710
711
712
713
714
715
716
test_that("Saving a model with different feature importance types works", {
    set.seed(708L)
    data(agaricus.train, package = "lightgbm")
    train <- agaricus.train
    bst <- lightgbm(
        data = as.matrix(train$data)
        , label = train$label
717
718
719
720
        , params = list(
            num_leaves = 4L
            , learning_rate = 1.0
            , objective = "binary"
721
            , verbose = VERBOSITY
722
            , num_threads = .LGB_MAX_THREADS
723
        )
724
725
726
727
728
        , nrounds = 2L
    )
    expect_true(lgb.is.Booster(bst))

    .feat_importance_from_string <- function(model_string) {
729
        file_lines <- strsplit(model_string, "\n", fixed = TRUE)[[1L]]
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
        start_indx <- which(grepl("^feature_importances\\:$", file_lines)) + 1L
        blank_line_indices <- which(file_lines == "")
        end_indx <- blank_line_indices[blank_line_indices > start_indx][1L] - 1L
        importances <- file_lines[start_indx: end_indx]
        return(importances)
    }

    GAIN_IMPORTANCE <- 1L
    model_string <- bst$save_model_to_string(feature_importance_type = GAIN_IMPORTANCE)
    expect_equal(
        .feat_importance_from_string(model_string)
        , c(
            "odor=none=4010"
            , "stalk-root=club=1163"
            , "stalk-root=rooted=573"
            , "stalk-surface-above-ring=silky=450"
            , "spore-print-color=green=397"
            , "gill-color=buff=281"
        )
    )

    SPLIT_IMPORTANCE <- 0L
    model_string <- bst$save_model_to_string(feature_importance_type = SPLIT_IMPORTANCE)
    expect_equal(
        .feat_importance_from_string(model_string)
        , c(
            "odor=none=1"
            , "gill-color=buff=1"
            , "stalk-root=club=1"
            , "stalk-root=rooted=1"
            , "stalk-surface-above-ring=silky=1"
            , "spore-print-color=green=1"
        )
    )
764
765
766
767
768
769
770
771
772
})

test_that("Saving a model with unknown importance type fails", {
    set.seed(708L)
    data(agaricus.train, package = "lightgbm")
    train <- agaricus.train
    bst <- lightgbm(
        data = as.matrix(train$data)
        , label = train$label
773
774
775
776
        , params = list(
            num_leaves = 4L
            , learning_rate = 1.0
            , objective = "binary"
777
            , verbose = VERBOSITY
778
            , num_threads = .LGB_MAX_THREADS
779
        )
780
781
782
        , nrounds = 2L
    )
    expect_true(lgb.is.Booster(bst))
783
784
785

    UNSUPPORTED_IMPORTANCE <- 2L
    expect_error({
786
787
788
789
790
        capture.output({
          model_string <- bst$save_model_to_string(
            feature_importance_type = UNSUPPORTED_IMPORTANCE
          )
        }, type = "message")
791
792
    }, "Unknown importance type")
})
793

794

795
.params_from_model_string <- function(model_str) {
796
    file_lines <- strsplit(model_str, "\n", fixed = TRUE)[[1L]]
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
    start_indx <- which(grepl("^parameters\\:$", file_lines)) + 1L
    blank_line_indices <- which(file_lines == "")
    end_indx <- blank_line_indices[blank_line_indices > start_indx][1L] - 1L
    params <- file_lines[start_indx: end_indx]
    return(params)
}

test_that("all parameters are stored correctly with save_model_to_string()", {
    dtrain <- lgb.Dataset(
        data = matrix(rnorm(500L), nrow = 100L)
        , label = rnorm(100L)
    )
    nrounds <- 4L
    bst <- lgb.train(
        params = list(
            objective = "regression"
            , metric = "l2"
814
            , num_threads = .LGB_MAX_THREADS
815
816
817
        )
        , data = dtrain
        , nrounds = nrounds
818
        , verbose = VERBOSITY
819
820
821
822
823
824
    )

    model_str <- bst$save_model_to_string()
    params_in_file <- .params_from_model_string(model_str = model_str)

    # parameters should match what was passed from the R package
825
    expect_equal(sum(startsWith(params_in_file, "[metric:")), 1L)
826
827
    expect_equal(sum(params_in_file == "[metric: l2]"), 1L)

828
    expect_equal(sum(startsWith(params_in_file, "[num_iterations:")), 1L)
829
830
    expect_equal(sum(params_in_file == "[num_iterations: 4]"), 1L)

831
    expect_equal(sum(startsWith(params_in_file, "[objective:")), 1L)
832
833
    expect_equal(sum(params_in_file == "[objective: regression]"), 1L)

834
    expect_equal(sum(startsWith(params_in_file, "[verbosity:")), 1L)
835
    expect_equal(sum(params_in_file == sprintf("[verbosity: %i]", VERBOSITY)), 1L)
836
837

    # early stopping should be off by default
838
    expect_equal(sum(startsWith(params_in_file, "[early_stopping_round:")), 1L)
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
    expect_equal(sum(params_in_file == "[early_stopping_round: 0]"), 1L)
})

test_that("early_stopping, num_iterations are stored correctly in model string even with aliases", {
    dtrain <- lgb.Dataset(
        data = matrix(rnorm(500L), nrow = 100L)
        , label = rnorm(100L)
    )
    dvalid <- lgb.Dataset(
        data = matrix(rnorm(500L), nrow = 100L)
        , label = rnorm(100L)
    )

    # num_iterations values (all different)
    num_iterations <- 4L
    num_boost_round <- 2L
    n_iter <- 3L
    nrounds_kwarg <- 6L

    # early_stopping_round values (all different)
    early_stopping_round <- 2L
    early_stopping_round_kwarg <- 3L
    n_iter_no_change <- 4L

    params <- list(
        objective = "regression"
        , metric = "l2"
        , num_boost_round = num_boost_round
        , num_iterations = num_iterations
        , n_iter = n_iter
        , early_stopping_round = early_stopping_round
        , n_iter_no_change = n_iter_no_change
871
        , num_threads = .LGB_MAX_THREADS
872
873
874
875
876
877
878
879
880
881
    )

    bst <- lgb.train(
        params = params
        , data = dtrain
        , nrounds = nrounds_kwarg
        , early_stopping_rounds = early_stopping_round_kwarg
        , valids = list(
            "random_valid" = dvalid
        )
882
        , verbose = VERBOSITY
883
884
885
886
887
888
889
    )

    model_str <- bst$save_model_to_string()
    params_in_file <- .params_from_model_string(model_str = model_str)

    # parameters should match what was passed from the R package, and the "main" (non-alias)
    # params values in `params` should be preferred to keyword argumentts or aliases
890
    expect_equal(sum(startsWith(params_in_file, "[num_iterations:")), 1L)
891
    expect_equal(sum(params_in_file == sprintf("[num_iterations: %s]", num_iterations)), 1L)
892
    expect_equal(sum(startsWith(params_in_file, "[early_stopping_round:")), 1L)
893
894
895
    expect_equal(sum(params_in_file == sprintf("[early_stopping_round: %s]", early_stopping_round)), 1L)

    # none of the aliases shouold have been written to the model file
896
897
898
    expect_equal(sum(startsWith(params_in_file, "[num_boost_round:")), 0L)
    expect_equal(sum(startsWith(params_in_file, "[n_iter:")), 0L)
    expect_equal(sum(startsWith(params_in_file, "[n_iter_no_change:")), 0L)
899
900
901

})

902
903
904
905
906
907
908
909
910
test_that("Booster: method calls Booster with a null handle should raise an informative error and not segfault", {
    data(agaricus.train, package = "lightgbm")
    train <- agaricus.train
    dtrain <- lgb.Dataset(train$data, label = train$label)
    bst <- lgb.train(
        params = list(
            objective = "regression"
            , metric = "l2"
            , num_leaves = 8L
911
            , num_threads = .LGB_MAX_THREADS
912
913
        )
        , data = dtrain
914
        , verbose = VERBOSITY
915
916
917
918
        , nrounds = 5L
        , valids = list(
            train = dtrain
        )
919
        , serializable = FALSE
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
    )
    tmp_file <- tempfile(fileext = ".rds")
    saveRDS(bst, tmp_file)
    rm(bst)
    bst <- readRDS(tmp_file)
    .expect_booster_error <- function(object) {
        error_regexp <- "Attempting to use a Booster which no longer exists"
        expect_error(object, regexp = error_regexp)
    }
    .expect_booster_error({
        bst$current_iter()
    })
    .expect_booster_error({
        bst$dump_model()
    })
    .expect_booster_error({
        bst$eval(data = dtrain, name = "valid")
    })
    .expect_booster_error({
        bst$eval_train()
    })
    .expect_booster_error({
        bst$lower_bound()
    })
    .expect_booster_error({
        bst$predict(data = train$data[seq_len(5L), ])
    })
    .expect_booster_error({
        bst$reset_parameter(params = list(learning_rate = 0.123))
    })
    .expect_booster_error({
        bst$rollback_one_iter()
    })
    .expect_booster_error({
954
        bst$save_raw()
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
    })
    .expect_booster_error({
        bst$save_model(filename = tempfile(fileext = ".model"))
    })
    .expect_booster_error({
        bst$save_model_to_string()
    })
    .expect_booster_error({
        bst$update()
    })
    .expect_booster_error({
        bst$upper_bound()
    })
    predictor <- bst$to_predictor()
    .expect_booster_error({
        predictor$current_iter()
    })
    .expect_booster_error({
        predictor$predict(data = train$data[seq_len(5L), ])
    })
})

test_that("Booster$new() using a Dataset with a null handle should raise an informative error and not segfault", {
    data(agaricus.train, package = "lightgbm")
    train <- agaricus.train
    dtrain <- lgb.Dataset(train$data, label = train$label)
    dtrain$construct()
    tmp_file <- tempfile(fileext = ".bin")
    saveRDS(dtrain, tmp_file)
    rm(dtrain)
    dtrain <- readRDS(tmp_file)
    expect_error({
987
988
989
990
991
992
        bst <- Booster$new(
            train_set = dtrain
            , params = list(
                verbose = VERBOSITY
            )
        )
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
    }, regexp = "Attempting to create a Dataset without any raw data")
})

test_that("Booster$new() raises informative errors for malformed inputs", {
  data(agaricus.train, package = "lightgbm")
  train <- agaricus.train
  dtrain <- lgb.Dataset(train$data, label = train$label)

  # no inputs
  expect_error({
    Booster$new()
  }, regexp = "lgb.Booster: Need at least either training dataset, model file, or model_str")

  # unrecognized objective
  expect_error({
1008
1009
1010
1011
1012
1013
    capture.output({
      Booster$new(
        params = list(objective = "not_a_real_objective")
        , train_set = dtrain
      )
    }, type = "message")
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
  }, regexp = "Unknown objective type name: not_a_real_objective")

  # train_set is not a Dataset
  expect_error({
    Booster$new(
      train_set = data.table::data.table(rnorm(1L:10L))
    )
  }, regexp = "lgb.Booster: Can only use lgb.Dataset as training data")

  # model file isn't a string
  expect_error({
    Booster$new(
      modelfile = list()
    )
  }, regexp = "lgb.Booster: Can only use a string as model file path")

  # model file doesn't exist
  expect_error({
1032
1033
1034
1035
1036
1037
    capture.output({
      Booster$new(
        params = list()
        , modelfile = "file-that-does-not-exist.model"
      )
    }, type = "message")
1038
1039
1040
1041
1042
1043
1044
1045
1046
  }, regexp = "Could not open file-that-does-not-exist.model")

  # model file doesn't contain a valid LightGBM model
  model_file <- tempfile(fileext = ".model")
  writeLines(
    text = c("make", "good", "predictions")
    , con = model_file
  )
  expect_error({
1047
1048
1049
1050
1051
1052
    capture.output({
      Booster$new(
        params = list()
        , modelfile = model_file
      )
    }, type = "message")
1053
1054
1055
1056
  }, regexp = "Unknown model format or submodel type in model file")

  # malformed model string
  expect_error({
1057
1058
1059
1060
1061
1062
    capture.output({
      Booster$new(
        params = list()
        , model_str = "a\nb\n"
      )
    }, type = "message")
1063
1064
1065
1066
1067
1068
1069
1070
  }, regexp = "Model file doesn't specify the number of classes")

  # model string isn't character or raw
  expect_error({
    Booster$new(
      model_str = numeric()
    )
  }, regexp = "lgb.Booster: Can only use a character/raw vector as model_str")
1071
1072
})

1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
# this is almost identical to the test above it, but for lgb.cv(). A lot of code
# is duplicated between lgb.train() and lgb.cv(), and this will catch cases where
# one is updated and the other isn't
test_that("lgb.cv() correctly handles passing through params to the model file", {
    dtrain <- lgb.Dataset(
        data = matrix(rnorm(500L), nrow = 100L)
        , label = rnorm(100L)
    )

    # num_iterations values (all different)
    num_iterations <- 4L
    num_boost_round <- 2L
    n_iter <- 3L
    nrounds_kwarg <- 6L

    # early_stopping_round values (all different)
    early_stopping_round <- 2L
    early_stopping_round_kwarg <- 3L
    n_iter_no_change <- 4L

    params <- list(
        objective = "regression"
        , metric = "l2"
        , num_boost_round = num_boost_round
        , num_iterations = num_iterations
        , n_iter = n_iter
        , early_stopping_round = early_stopping_round
        , n_iter_no_change = n_iter_no_change
1101
        , verbose = VERBOSITY
1102
        , num_threads = .LGB_MAX_THREADS
1103
1104
1105
1106
1107
1108
1109
1110
    )

    cv_bst <- lgb.cv(
        params = params
        , data = dtrain
        , nrounds = nrounds_kwarg
        , early_stopping_rounds = early_stopping_round_kwarg
        , nfold = 3L
1111
        , verbose = VERBOSITY
1112
1113
1114
1115
1116
1117
1118
1119
    )

    for (bst in cv_bst$boosters) {
        model_str <- bst[["booster"]]$save_model_to_string()
        params_in_file <- .params_from_model_string(model_str = model_str)

        # parameters should match what was passed from the R package, and the "main" (non-alias)
        # params values in `params` should be preferred to keyword argumentts or aliases
1120
        expect_equal(sum(startsWith(params_in_file, "[num_iterations:")), 1L)
1121
        expect_equal(sum(params_in_file == sprintf("[num_iterations: %s]", num_iterations)), 1L)
1122
        expect_equal(sum(startsWith(params_in_file, "[early_stopping_round:")), 1L)
1123
1124
1125
        expect_equal(sum(params_in_file == sprintf("[early_stopping_round: %s]", early_stopping_round)), 1L)

        # none of the aliases shouold have been written to the model file
1126
1127
1128
        expect_equal(sum(startsWith(params_in_file, "[num_boost_round:")), 0L)
        expect_equal(sum(startsWith(params_in_file, "[n_iter:")), 0L)
        expect_equal(sum(startsWith(params_in_file, "[n_iter_no_change:")), 0L)
1129
1130
1131
    }

})
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145

test_that("params (including dataset params) should be stored in .rds file for Booster", {
    data(agaricus.train, package = "lightgbm")
    dtrain <- lgb.Dataset(
        agaricus.train$data
        , label = agaricus.train$label
        , params = list(
            max_bin = 17L
        )
    )
    params <- list(
        objective = "binary"
        , max_depth = 4L
        , bagging_fraction = 0.8
1146
        , verbose = VERBOSITY
1147
        , num_threads = .LGB_MAX_THREADS
1148
1149
1150
1151
1152
1153
    )
    bst <- Booster$new(
        params = params
        , train_set = dtrain
    )
    bst_file <- tempfile(fileext = ".rds")
1154
    expect_warning(saveRDS.lgb.Booster(bst, file = bst_file))
1155

1156
    expect_warning(bst_from_file <- readRDS.lgb.Booster(file = bst_file))
1157
1158
1159
1160
1161
1162
    expect_identical(
        bst_from_file$params
        , list(
            objective = "binary"
            , max_depth = 4L
            , bagging_fraction = 0.8
1163
            , verbose = VERBOSITY
1164
            , num_threads = .LGB_MAX_THREADS
1165
1166
1167
1168
            , max_bin = 17L
        )
    )
})
1169

1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
test_that("params (including dataset params) should be stored in .rds file for Booster", {
    data(agaricus.train, package = "lightgbm")
    dtrain <- lgb.Dataset(
        agaricus.train$data
        , label = agaricus.train$label
        , params = list(
            max_bin = 17L
        )
    )
    params <- list(
        objective = "binary"
        , max_depth = 4L
        , bagging_fraction = 0.8
1183
        , verbose = VERBOSITY
1184
        , num_threads = .LGB_MAX_THREADS
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
    )
    bst <- Booster$new(
        params = params
        , train_set = dtrain
    )
    bst_file <- tempfile(fileext = ".rds")
    saveRDS(bst, file = bst_file)

    bst_from_file <- readRDS(file = bst_file)
    expect_identical(
        bst_from_file$params
        , list(
            objective = "binary"
            , max_depth = 4L
            , bagging_fraction = 0.8
1200
            , verbose = VERBOSITY
1201
            , num_threads = .LGB_MAX_THREADS
1202
1203
1204
1205
1206
1207
1208
            , max_bin = 17L
        )
    )
})

test_that("Handle is automatically restored when calling predict", {
    data(agaricus.train, package = "lightgbm")
1209
1210
1211
1212
1213
1214
1215
1216
    bst <- lightgbm(
        agaricus.train$data
        , agaricus.train$label
        , nrounds = 5L
        , obj = "binary"
        , params = list(
            verbose = VERBOSITY
        )
1217
        , num_threads = .LGB_MAX_THREADS
1218
    )
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
    bst_file <- tempfile(fileext = ".rds")
    saveRDS(bst, file = bst_file)

    bst_from_file <- readRDS(file = bst_file)

    pred_before <- predict(bst, agaricus.train$data)
    pred_after <- predict(bst_from_file, agaricus.train$data)
    expect_equal(pred_before, pred_after)
})

test_that("boosters with linear models at leaves work with saveRDS.lgb.Booster and readRDS.lgb.Booster", {
    X <- matrix(rnorm(100L), ncol = 1L)
    labels <- 2L * X + runif(nrow(X), 0L, 0.1)
    dtrain <- lgb.Dataset(
        data = X
        , label = labels
    )

    params <- list(
        objective = "regression"
1239
        , verbose = VERBOSITY
1240
1241
1242
        , metric = "mse"
        , seed = 0L
        , num_leaves = 2L
1243
        , num_threads = .LGB_MAX_THREADS
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
    )

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

    # save predictions, then write the model to a file and destroy it in R
    preds <- predict(bst, X)
    model_file <- tempfile(fileext = ".rds")
    expect_warning(saveRDS.lgb.Booster(bst, file = model_file))
    bst$finalize()
    expect_null(bst$.__enclos_env__$private$handle)
    rm(bst)

    # load the booster and make predictions...should be the same
1262
1263
1264
    expect_warning({
        bst2 <- readRDS.lgb.Booster(file = model_file)
    })
1265
1266
1267
1268
    preds2 <- predict(bst2, X)
    expect_identical(preds, preds2)
})

1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
test_that("boosters with linear models at leaves can be written to RDS and re-loaded successfully", {
    X <- matrix(rnorm(100L), ncol = 1L)
    labels <- 2L * X + runif(nrow(X), 0L, 0.1)
    dtrain <- lgb.Dataset(
        data = X
        , label = labels
    )

    params <- list(
        objective = "regression"
1279
        , verbose = VERBOSITY
1280
1281
1282
        , metric = "mse"
        , seed = 0L
        , num_leaves = 2L
1283
        , num_threads = .LGB_MAX_THREADS
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
    )

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

    # save predictions, then write the model to a file and destroy it in R
    preds <- predict(bst, X)
    model_file <- tempfile(fileext = ".rds")
1296
    saveRDS(bst, file = model_file)
1297
1298
1299
1300
1301
    bst$finalize()
    expect_null(bst$.__enclos_env__$private$handle)
    rm(bst)

    # load the booster and make predictions...should be the same
1302
    bst2 <- readRDS(file = model_file)
1303
1304
    preds2 <- predict(bst2, X)
    expect_identical(preds, preds2)
1305
})
1306
1307
1308
1309
1310
1311
1312
1313
1314

test_that("Booster's print, show, and summary work correctly", {
    .have_same_handle <- function(model, other_model) {
       expect_equal(
         model$.__enclos_env__$private$handle
         , other_model$.__enclos_env__$private$handle
       )
    }

1315
    .has_expected_content_for_fitted_model <- function(printed_txt) {
1316
1317
      expect_true(any(startsWith(printed_txt, "LightGBM Model")))
      expect_true(any(startsWith(printed_txt, "Fitted to dataset")))
1318
1319
1320
1321
    }

    .has_expected_content_for_finalized_model <- function(printed_txt) {
      expect_true(any(grepl("^LightGBM Model$", printed_txt)))
1322
      expect_true(any(grepl("Booster handle is invalid", printed_txt, fixed = TRUE)))
1323
1324
    }

1325
1326
    .check_methods_work <- function(model) {

1327
1328
1329
1330
1331
1332
        #--- should work for fitted models --- #

        # print()
        log_txt <- capture.output({
          ret <- print(model)
        })
1333
        .have_same_handle(ret, model)
1334
1335
1336
1337
1338
1339
        .has_expected_content_for_fitted_model(log_txt)

        # show()
        log_txt <- capture.output({
          ret <- show(model)
        })
1340
        expect_null(ret)
1341
1342
1343
        .has_expected_content_for_fitted_model(log_txt)

        # summary()
1344
        log_txt <- capture.output({
1345
1346
          ret <- summary(model)
        })
1347
        .have_same_handle(ret, model)
1348
        .has_expected_content_for_fitted_model(log_txt)
1349

1350
        #--- should not fail for finalized models ---#
1351
        model$finalize()
1352
1353
1354
1355
1356
1357
1358
1359

        # print()
        log_txt <- capture.output({
          ret <- print(model)
        })
        .has_expected_content_for_finalized_model(log_txt)

        # show()
1360
        .have_same_handle(ret, model)
1361
1362
1363
        log_txt <- capture.output({
          ret <- show(model)
        })
1364
        expect_null(ret)
1365
1366
1367
1368
1369
1370
        .has_expected_content_for_finalized_model(log_txt)

        # summary()
        log_txt <- capture.output({
          ret <- summary(model)
        })
1371
        .have_same_handle(ret, model)
1372
        .has_expected_content_for_finalized_model(log_txt)
1373
1374
1375
1376
    }

    data("mtcars")
    model <- lgb.train(
1377
1378
1379
        params = list(
          objective = "regression"
          , min_data_in_leaf = 1L
1380
          , num_threads = .LGB_MAX_THREADS
1381
        )
1382
1383
        , data = lgb.Dataset(
            as.matrix(mtcars[, -1L])
1384
1385
1386
1387
1388
            , label = mtcars$mpg
            , params = list(
              min_data_in_bin = 1L
            )
        )
1389
        , verbose = VERBOSITY
1390
1391
1392
1393
1394
1395
        , nrounds = 5L
    )
    .check_methods_work(model)

    data("iris")
    model <- lgb.train(
1396
        params = list(objective = "multiclass", num_class = 3L, num_threads = .LGB_MAX_THREADS)
1397
1398
1399
1400
        , data = lgb.Dataset(
            as.matrix(iris[, -5L])
            , label = as.numeric(factor(iris$Species)) - 1.0
        )
1401
        , verbose = VERBOSITY
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
        , nrounds = 5L
    )
    .check_methods_work(model)


    # with custom objective
    .logregobj <- function(preds, dtrain) {
        labels <- get_field(dtrain, "label")
        preds <- 1.0 / (1.0 + exp(-preds))
        grad <- preds - labels
        hess <- preds * (1.0 - preds)
        return(list(grad = grad, hess = hess))
    }

    .evalerror <- function(preds, dtrain) {
        labels <- get_field(dtrain, "label")
        preds <- 1.0 / (1.0 + exp(-preds))
        err <- as.numeric(sum(labels != (preds > 0.5))) / length(labels)
        return(list(
            name = "error"
            , value = err
            , higher_better = FALSE
        ))
    }

    model <- lgb.train(
        data = lgb.Dataset(
            as.matrix(iris[, -5L])
            , label = as.numeric(iris$Species == "virginica")
        )
        , obj = .logregobj
        , eval = .evalerror
1434
        , verbose = VERBOSITY
1435
        , nrounds = 5L
1436
        , params = list(num_threads = .LGB_MAX_THREADS)
1437
1438
1439
1440
1441
1442
1443
1444
    )

    .check_methods_work(model)
})

test_that("LGBM_BoosterGetNumFeature_R returns correct outputs", {
    data("mtcars")
    model <- lgb.train(
1445
1446
1447
        params = list(
          objective = "regression"
          , min_data_in_leaf = 1L
1448
          , num_threads = .LGB_MAX_THREADS
1449
        )
1450
1451
        , data = lgb.Dataset(
            as.matrix(mtcars[, -1L])
1452
1453
1454
1455
1456
            , label = mtcars$mpg
            , params = list(
              min_data_in_bin = 1L
            )
        )
1457
        , verbose = VERBOSITY
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
        , nrounds = 5L
    )
    ncols <- .Call(LGBM_BoosterGetNumFeature_R, model$.__enclos_env__$private$handle)
    expect_equal(ncols, ncol(mtcars) - 1L)

    data("iris")
    model <- lgb.train(
        params = list(objective = "multiclass", num_class = 3L)
        , data = lgb.Dataset(
            as.matrix(iris[, -5L])
            , label = as.numeric(factor(iris$Species)) - 1.0
        )
1470
        , verbose = VERBOSITY
1471
1472
1473
1474
1475
        , nrounds = 5L
    )
    ncols <- .Call(LGBM_BoosterGetNumFeature_R, model$.__enclos_env__$private$handle)
    expect_equal(ncols, ncol(iris) - 1L)
})