test_Predictor.R 23.2 KB
Newer Older
1
2
library(Matrix)

3
test_that("Predictor's finalizer should not fail", {
4
5
6
7
8
    X <- as.matrix(as.integer(iris[, "Species"]), ncol = 1L)
    y <- iris[["Sepal.Length"]]
    dtrain <- lgb.Dataset(X, label = y)
    bst <- lgb.train(
        data = dtrain
9
10
        , params = list(
            objective = "regression"
11
            , num_threads = .LGB_MAX_THREADS
12
        )
13
        , verbose = .LGB_VERBOSITY
14
15
16
17
18
19
        , nrounds = 3L
    )
    model_file <- tempfile(fileext = ".model")
    bst$save_model(filename = model_file)
    predictor <- Predictor$new(modelfile = model_file)

20
    expect_true(.is_Predictor(predictor))
21

22
    expect_false(.is_null_handle(predictor$.__enclos_env__$private$handle))
23

24
    predictor$.__enclos_env__$private$finalize()
25
    expect_true(.is_null_handle(predictor$.__enclos_env__$private$handle))
26
27

    # calling finalize() a second time shouldn't cause any issues
28
    predictor$.__enclos_env__$private$finalize()
29
    expect_true(.is_null_handle(predictor$.__enclos_env__$private$handle))
30
31
})

32
33
34
35
36
37
test_that("predictions do not fail for integer input", {
    X <- as.matrix(as.integer(iris[, "Species"]), ncol = 1L)
    y <- iris[["Sepal.Length"]]
    dtrain <- lgb.Dataset(X, label = y)
    fit <- lgb.train(
        data = dtrain
38
39
        , params = list(
            objective = "regression"
40
            , num_threads = .LGB_MAX_THREADS
41
        )
42
        , verbose = .LGB_VERBOSITY
43
        , nrounds = 3L
44
45
46
47
48
49
50
51
    )
    X_double <- X[c(1L, 51L, 101L), , drop = FALSE]
    X_integer <- X_double
    storage.mode(X_double) <- "double"
    pred_integer <- predict(fit, X_integer)
    pred_double <- predict(fit, X_double)
    expect_equal(pred_integer, pred_double)
})
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70

test_that("start_iteration works correctly", {
    set.seed(708L)
    data(agaricus.train, package = "lightgbm")
    data(agaricus.test, package = "lightgbm")
    train <- agaricus.train
    test <- agaricus.test
    dtrain <- lgb.Dataset(
        agaricus.train$data
        , label = agaricus.train$label
    )
    dtest <- lgb.Dataset.create.valid(
        dtrain
        , agaricus.test$data
        , label = agaricus.test$label
    )
    bst <- lightgbm(
        data = as.matrix(train$data)
        , label = train$label
71
72
73
74
        , params = list(
            num_leaves = 4L
            , learning_rate = 0.6
            , objective = "binary"
75
            , verbosity = .LGB_VERBOSITY
76
            , num_threads = .LGB_MAX_THREADS
77
        )
78
        , nrounds = 50L
79
80
81
        , valids = list("test" = dtest)
        , early_stopping_rounds = 2L
    )
82
    expect_true(.is_Booster(bst))
83
84
    pred1 <- predict(bst, newdata = test$data, type = "raw")
    pred_contrib1 <- predict(bst, test$data, type = "contrib")
85
86
87
    pred2 <- rep(0.0, length(pred1))
    pred_contrib2 <- rep(0.0, length(pred2))
    step <- 11L
88
    end_iter <- 49L
89
90
91
92
93
94
95
96
97
    if (bst$best_iter != -1L) {
        end_iter <- bst$best_iter - 1L
    }
    start_iters <- seq(0L, end_iter, by = step)
    for (start_iter in start_iters) {
        n_iter <- min(c(end_iter - start_iter + 1L, step))
        inc_pred <- predict(bst, test$data
            , start_iteration = start_iter
            , num_iteration = n_iter
98
            , type = "raw"
99
100
101
102
103
104
105
106
107
108
109
110
        )
        inc_pred_contrib <- bst$predict(test$data
            , start_iteration = start_iter
            , num_iteration = n_iter
            , predcontrib = TRUE
        )
        pred2 <- pred2 + inc_pred
        pred_contrib2 <- pred_contrib2 + inc_pred_contrib
    }
    expect_equal(pred2, pred1)
    expect_equal(pred_contrib2, pred_contrib1)

111
112
    pred_leaf1 <- predict(bst, test$data, type = "leaf")
    pred_leaf2 <- predict(bst, test$data, start_iteration = 0L, num_iteration = end_iter + 1L, type = "leaf")
113
114
    expect_equal(pred_leaf1, pred_leaf2)
})
115

116
117
118
119
120
121
122
123
124
test_that("Feature contributions from sparse inputs produce sparse outputs", {
    data(mtcars)
    X <- as.matrix(mtcars[, -1L])
    y <- as.numeric(mtcars[, 1L])
    dtrain <- lgb.Dataset(X, label = y, params = list(max_bins = 5L))
    bst <- lgb.train(
      data = dtrain
      , obj = "regression"
      , nrounds = 5L
125
      , verbose = .LGB_VERBOSITY
126
      , params = list(min_data_in_leaf = 5L, num_threads = .LGB_MAX_THREADS)
127
128
    )

129
    pred_dense <- predict(bst, X, type = "contrib")
130
131

    Xcsc <- as(X, "CsparseMatrix")
132
    pred_csc <- predict(bst, Xcsc, type = "contrib")
133
134
135
136
    expect_s4_class(pred_csc, "dgCMatrix")
    expect_equal(unname(pred_dense), unname(as.matrix(pred_csc)))

    Xcsr <- as(X, "RsparseMatrix")
137
    pred_csr <- predict(bst, Xcsr, type = "contrib")
138
139
140
141
    expect_s4_class(pred_csr, "dgRMatrix")
    expect_equal(as(pred_csr, "CsparseMatrix"), pred_csc)

    Xspv <- as(X[1L, , drop = FALSE], "sparseVector")
142
    pred_spv <- predict(bst, Xspv, type = "contrib")
143
144
145
146
147
148
149
150
151
152
153
154
155
    expect_s4_class(pred_spv, "dsparseVector")
    expect_equal(Matrix::t(as(pred_spv, "CsparseMatrix")), unname(pred_csc[1L, , drop = FALSE]))
})

test_that("Sparse feature contribution predictions do not take inputs with wrong number of columns", {
    data(mtcars)
    X <- as.matrix(mtcars[, -1L])
    y <- as.numeric(mtcars[, 1L])
    dtrain <- lgb.Dataset(X, label = y, params = list(max_bins = 5L))
    bst <- lgb.train(
      data = dtrain
      , obj = "regression"
      , nrounds = 5L
156
      , verbose = .LGB_VERBOSITY
157
      , params = list(min_data_in_leaf = 5L, num_threads = .LGB_MAX_THREADS)
158
159
160
161
    )

    X_wrong <- X[, c(1L:10L, 1L:10L)]
    X_wrong <- as(X_wrong, "CsparseMatrix")
162
    expect_error(predict(bst, X_wrong, type = "contrib"), regexp = "input data has 20 columns")
163
164

    X_wrong <- as(X_wrong, "RsparseMatrix")
165
    expect_error(predict(bst, X_wrong, type = "contrib"), regexp = "input data has 20 columns")
166
167
168

    X_wrong <- as(X_wrong, "CsparseMatrix")
    X_wrong <- X_wrong[, 1L:3L]
169
    expect_error(predict(bst, X_wrong, type = "contrib"), regexp = "input data has 3 columns")
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
})

test_that("Feature contribution predictions do not take non-general CSR or CSC inputs", {
    set.seed(123L)
    y <- runif(25L)
    Dmat <- matrix(runif(625L), nrow = 25L, ncol = 25L)
    Dmat <- crossprod(Dmat)
    Dmat <- as(Dmat, "symmetricMatrix")
    SmatC <- as(Dmat, "sparseMatrix")
    SmatR <- as(SmatC, "RsparseMatrix")

    dtrain <- lgb.Dataset(as.matrix(Dmat), label = y, params = list(max_bins = 5L))
    bst <- lgb.train(
      data = dtrain
      , obj = "regression"
      , nrounds = 5L
186
      , verbose = .LGB_VERBOSITY
187
      , params = list(min_data_in_leaf = 5L, num_threads = .LGB_MAX_THREADS)
188
189
    )

190
191
192
193
194
195
196
197
    expect_error(
      predict(bst, SmatC, type = "contrib")
      , regexp = "Predictions on sparse inputs are only allowed for 'dsparseVector', 'dgRMatrix', 'dgCMatrix' - got: dsCMatrix"  # nolint: line_length.
    )
    expect_error(
      predict(bst, SmatR, type = "contrib")
      , regexp = "Predictions on sparse inputs are only allowed for 'dsparseVector', 'dgRMatrix', 'dgCMatrix' - got: dsRMatrix" # nolint: line_length.
    )
198
199
})

200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
test_that("predict() params should override keyword argument for raw-score predictions", {
  data(agaricus.train, package = "lightgbm")
  X <- agaricus.train$data
  y <- agaricus.train$label
  bst <- lgb.train(
    data = lgb.Dataset(
      data = X
      , label = y
      , params = list(
        data_seed = 708L
        , min_data_in_bin = 5L
      )
    )
    , params = list(
      objective = "binary"
      , min_data_in_leaf = 1L
      , seed = 708L
217
      , num_threads = .LGB_MAX_THREADS
218
219
    )
    , nrounds = 10L
220
    , verbose = .LGB_VERBOSITY
221
222
223
224
  )

  # check that the predictions from predict.lgb.Booster() really look like raw score predictions
  preds_prob <- predict(bst, X)
225
  preds_raw_s3_keyword <- predict(bst, X, type = "raw")
226
  preds_prob_from_raw <- 1.0 / (1.0 + exp(-preds_raw_s3_keyword))
227
  expect_equal(preds_prob, preds_prob_from_raw, tolerance = .LGB_NUMERIC_TOLERANCE)
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
  accuracy <- sum(as.integer(preds_prob_from_raw > 0.5) == y) / length(y)
  expect_equal(accuracy, 1.0)

  # should get the same results from Booster$predict() method
  preds_raw_r6_keyword <- bst$predict(X, rawscore = TRUE)
  expect_equal(preds_raw_s3_keyword, preds_raw_r6_keyword)

  # using a parameter alias of predict_raw_score should result in raw scores being returned
  aliases <- .PARAMETER_ALIASES()[["predict_raw_score"]]
  expect_true(length(aliases) > 1L)
  for (rawscore_alias in aliases) {
    params <- as.list(
      stats::setNames(
        object = TRUE
        , nm = rawscore_alias
      )
    )
    preds_raw_s3_param <- predict(bst, X, params = params)
    preds_raw_r6_param <- bst$predict(X, params = params)
    expect_equal(preds_raw_s3_keyword, preds_raw_s3_param)
    expect_equal(preds_raw_s3_keyword, preds_raw_r6_param)
  }
})

test_that("predict() params should override keyword argument for leaf-index predictions", {
  data(mtcars)
  X <- as.matrix(mtcars[, which(names(mtcars) != "mpg")])
  y <- as.numeric(mtcars[, "mpg"])
  bst <- lgb.train(
    data = lgb.Dataset(
      data = X
      , label = y
      , params = list(
        min_data_in_bin = 1L
        , data_seed = 708L
      )
    )
    , params = list(
      objective = "regression"
      , min_data_in_leaf = 1L
      , seed = 708L
269
      , num_threads = .LGB_MAX_THREADS
270
271
    )
    , nrounds = 10L
272
    , verbose = .LGB_VERBOSITY
273
274
275
  )

  # check that predictions really look like leaf index predictions
276
  preds_leaf_s3_keyword <- predict(bst, X, type = "leaf")
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
  expect_true(is.matrix(preds_leaf_s3_keyword))
  expect_equal(dim(preds_leaf_s3_keyword), c(nrow(X), bst$current_iter()))
  expect_true(min(preds_leaf_s3_keyword) >= 0L)
  trees_dt <- lgb.model.dt.tree(bst)
  max_leaf_by_tree_from_dt <- trees_dt[, .(idx = max(leaf_index, na.rm = TRUE)), by = tree_index]$idx
  max_leaf_by_tree_from_preds <- apply(preds_leaf_s3_keyword, 2L, max, na.rm = TRUE)
  expect_equal(max_leaf_by_tree_from_dt, max_leaf_by_tree_from_preds)

  # should get the same results from Booster$predict() method
  preds_leaf_r6_keyword <- bst$predict(X, predleaf = TRUE)
  expect_equal(preds_leaf_s3_keyword, preds_leaf_r6_keyword)

  # using a parameter alias of predict_leaf_index should result in leaf indices being returned
  aliases <- .PARAMETER_ALIASES()[["predict_leaf_index"]]
  expect_true(length(aliases) > 1L)
  for (predleaf_alias in aliases) {
    params <- as.list(
      stats::setNames(
        object = TRUE
        , nm = predleaf_alias
      )
    )
    preds_leaf_s3_param <- predict(bst, X, params = params)
    preds_leaf_r6_param <- bst$predict(X, params = params)
    expect_equal(preds_leaf_s3_keyword, preds_leaf_s3_param)
    expect_equal(preds_leaf_s3_keyword, preds_leaf_r6_param)
  }
})

test_that("predict() params should override keyword argument for feature contributions", {
  data(mtcars)
  X <- as.matrix(mtcars[, which(names(mtcars) != "mpg")])
  y <- as.numeric(mtcars[, "mpg"])
  bst <- lgb.train(
    data = lgb.Dataset(
      data = X
      , label = y
      , params = list(
        min_data_in_bin = 1L
        , data_seed = 708L
      )
    )
    , params = list(
      objective = "regression"
      , min_data_in_leaf = 1L
      , seed = 708L
323
      , num_threads = .LGB_MAX_THREADS
324
325
    )
    , nrounds = 10L
326
    , verbose = .LGB_VERBOSITY
327
328
329
  )

  # check that predictions really look like feature contributions
330
  preds_contrib_s3_keyword <- predict(bst, X, type = "contrib")
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
  num_features <- ncol(X)
  shap_base_value <- unname(preds_contrib_s3_keyword[, ncol(preds_contrib_s3_keyword)])
  expect_true(is.matrix(preds_contrib_s3_keyword))
  expect_equal(dim(preds_contrib_s3_keyword), c(nrow(X), num_features + 1L))
  expect_equal(length(unique(shap_base_value)), 1L)
  expect_equal(mean(y), shap_base_value[1L])
  expect_equal(predict(bst, X), rowSums(preds_contrib_s3_keyword))

  # should get the same results from Booster$predict() method
  preds_contrib_r6_keyword <- bst$predict(X, predcontrib = TRUE)
  expect_equal(preds_contrib_s3_keyword, preds_contrib_r6_keyword)

  # using a parameter alias of predict_contrib should result in feature contributions being returned
  aliases <- .PARAMETER_ALIASES()[["predict_contrib"]]
  expect_true(length(aliases) > 1L)
  for (predcontrib_alias in aliases) {
    params <- as.list(
      stats::setNames(
        object = TRUE
        , nm = predcontrib_alias
      )
    )
    preds_contrib_s3_param <- predict(bst, X, params = params)
    preds_contrib_r6_param <- bst$predict(X, params = params)
    expect_equal(preds_contrib_s3_keyword, preds_contrib_s3_param)
    expect_equal(preds_contrib_s3_keyword, preds_contrib_r6_param)
  }
})

360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
.expect_has_row_names <- function(pred, X) {
    if (is.vector(pred)) {
        rnames <- names(pred)
    } else {
        rnames <- row.names(pred)
    }
    expect_false(is.null(rnames))
    expect_true(is.vector(rnames))
    expect_true(length(rnames) > 0L)
    expect_equal(row.names(X), rnames)
}

.expect_doesnt_have_row_names <- function(pred) {
    if (is.vector(pred)) {
        expect_null(names(pred))
    } else {
        expect_null(row.names(pred))
    }
}

.check_all_row_name_expectations <- function(bst, X) {

    # dense matrix with row names
    pred <- predict(bst, X)
    .expect_has_row_names(pred, X)
385
    pred <- predict(bst, X, type = "raw")
386
    .expect_has_row_names(pred, X)
387
    pred <- predict(bst, X, type = "leaf")
388
    .expect_has_row_names(pred, X)
389
    pred <- predict(bst, X, type = "contrib")
390
391
392
393
394
395
396
397
398
399
400
401
    .expect_has_row_names(pred, X)

    # dense matrix without row names
    Xcopy <- X
    row.names(Xcopy) <- NULL
    pred <- predict(bst, Xcopy)
    .expect_doesnt_have_row_names(pred)

    # sparse matrix with row names
    Xcsc <- as(X, "CsparseMatrix")
    pred <- predict(bst, Xcsc)
    .expect_has_row_names(pred, Xcsc)
402
    pred <- predict(bst, Xcsc, type = "raw")
403
    .expect_has_row_names(pred, Xcsc)
404
    pred <- predict(bst, Xcsc, type = "leaf")
405
    .expect_has_row_names(pred, Xcsc)
406
    pred <- predict(bst, Xcsc, type = "contrib")
407
    .expect_has_row_names(pred, Xcsc)
408
    pred <- predict(bst, as(Xcsc, "RsparseMatrix"), type = "contrib")
409
    .expect_has_row_names(pred, Xcsc)
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433

    # sparse matrix without row names
    Xcopy <- Xcsc
    row.names(Xcopy) <- NULL
    pred <- predict(bst, Xcopy)
    .expect_doesnt_have_row_names(pred)
}

test_that("predict() keeps row names from data (regression)", {
    data("mtcars")
    X <- as.matrix(mtcars[, -1L])
    y <- as.numeric(mtcars[, 1L])
    dtrain <- lgb.Dataset(
      X
      , label = y
      , params = list(
        max_bins = 5L
        , min_data_in_bin = 1L
      )
    )
    bst <- lgb.train(
        data = dtrain
        , obj = "regression"
        , nrounds = 5L
434
        , verbose = .LGB_VERBOSITY
435
        , params = list(min_data_in_leaf = 1L, num_threads = .LGB_MAX_THREADS)
436
437
438
439
440
441
442
443
    )
    .check_all_row_name_expectations(bst, X)
})

test_that("predict() keeps row names from data (binary classification)", {
    data(agaricus.train, package = "lightgbm")
    X <- as.matrix(agaricus.train$data)
    y <- agaricus.train$label
444
    row.names(X) <- paste0("rname", seq(1L, nrow(X)))
445
446
447
448
449
    dtrain <- lgb.Dataset(X, label = y, params = list(max_bins = 5L))
    bst <- lgb.train(
        data = dtrain
        , obj = "binary"
        , nrounds = 5L
450
        , verbose = .LGB_VERBOSITY
451
        , params = list(num_threads = .LGB_MAX_THREADS)
452
453
454
455
456
457
458
459
    )
    .check_all_row_name_expectations(bst, X)
})

test_that("predict() keeps row names from data (multi-class classification)", {
    data(iris)
    y <- as.numeric(iris$Species) - 1.0
    X <- as.matrix(iris[, names(iris) != "Species"])
460
    row.names(X) <- paste0("rname", seq(1L, nrow(X)))
461
462
463
464
    dtrain <- lgb.Dataset(X, label = y, params = list(max_bins = 5L))
    bst <- lgb.train(
        data = dtrain
        , obj = "multiclass"
465
        , params = list(num_class = 3L, num_threads = .LGB_MAX_THREADS)
466
        , nrounds = 5L
467
        , verbose = .LGB_VERBOSITY
468
469
470
471
    )
    .check_all_row_name_expectations(bst, X)
})

472
473
474
475
test_that("predictions for regression and binary classification are returned as vectors", {
    data(mtcars)
    X <- as.matrix(mtcars[, -1L])
    y <- as.numeric(mtcars[, 1L])
476
477
478
479
480
481
482
483
    dtrain <- lgb.Dataset(
      X
      , label = y
      , params = list(
        max_bins = 5L
        , min_data_in_bin = 1L
      )
    )
484
485
486
487
    model <- lgb.train(
      data = dtrain
      , obj = "regression"
      , nrounds = 5L
488
      , verbose = .LGB_VERBOSITY
489
      , params = list(min_data_in_leaf = 1L, num_threads = .LGB_MAX_THREADS)
490
491
492
493
    )
    pred <- predict(model, X)
    expect_true(is.vector(pred))
    expect_equal(length(pred), nrow(X))
494
    pred <- predict(model, X, type = "raw")
495
496
497
498
499
500
501
502
503
504
505
    expect_true(is.vector(pred))
    expect_equal(length(pred), nrow(X))

    data(agaricus.train, package = "lightgbm")
    X <- agaricus.train$data
    y <- agaricus.train$label
    dtrain <- lgb.Dataset(X, label = y)
    model <- lgb.train(
      data = dtrain
      , obj = "binary"
      , nrounds = 5L
506
      , verbose = .LGB_VERBOSITY
507
      , params = list(num_threads = .LGB_MAX_THREADS)
508
509
510
511
    )
    pred <- predict(model, X)
    expect_true(is.vector(pred))
    expect_equal(length(pred), nrow(X))
512
    pred <- predict(model, X, type = "raw")
513
514
515
516
517
518
519
520
521
522
523
524
525
    expect_true(is.vector(pred))
    expect_equal(length(pred), nrow(X))
})

test_that("predictions for multiclass classification are returned as matrix", {
    data(iris)
    X <- as.matrix(iris[, -5L])
    y <- as.numeric(iris$Species) - 1.0
    dtrain <- lgb.Dataset(X, label = y)
    model <- lgb.train(
      data = dtrain
      , obj = "multiclass"
      , nrounds = 5L
526
      , verbose = .LGB_VERBOSITY
527
      , params = list(num_class = 3L, num_threads = .LGB_MAX_THREADS)
528
529
530
531
532
    )
    pred <- predict(model, X)
    expect_true(is.matrix(pred))
    expect_equal(nrow(pred), nrow(X))
    expect_equal(ncol(pred), 3L)
533
    pred <- predict(model, X, type = "raw")
534
535
536
537
    expect_true(is.matrix(pred))
    expect_equal(nrow(pred), nrow(X))
    expect_equal(ncol(pred), 3L)
})
538

539
540
541
542
543
test_that("Single-row predictions are identical to multi-row ones", {
    data(mtcars)
    X <- as.matrix(mtcars[, -1L])
    y <- mtcars[, 1L]
    dtrain <- lgb.Dataset(X, label = y, params = list(max_bin = 5L))
544
    params <- list(min_data_in_leaf = 2L, num_threads = .LGB_MAX_THREADS)
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
    model <- lgb.train(
      params = params
     , data = dtrain
     , obj = "regression"
     , nrounds = 5L
     , verbose = -1L
    )

    x1 <- X[1L, , drop = FALSE]
    x11 <- X[11L, , drop = FALSE]
    x1_spv <- as(x1, "sparseVector")
    x11_spv <- as(x11, "sparseVector")
    x1_csr <- as(x1, "RsparseMatrix")
    x11_csr <- as(x11, "RsparseMatrix")

    pred_all <- predict(model, X)
    pred1_wo_config <- predict(model, x1)
    pred11_wo_config <- predict(model, x11)
    pred1_spv_wo_config <- predict(model, x1_spv)
    pred11_spv_wo_config <- predict(model, x11_spv)
    pred1_csr_wo_config <- predict(model, x1_csr)
    pred11_csr_wo_config <- predict(model, x11_csr)

    lgb.configure_fast_predict(model)
    pred1_w_config <- predict(model, x1)
    pred11_w_config <- predict(model, x11)

    model <- lgb.train(
      params = params
     , data = dtrain
     , obj = "regression"
     , nrounds = 5L
     , verbose = -1L
    )
    lgb.configure_fast_predict(model, csr = TRUE)
    pred1_spv_w_config <- predict(model, x1_spv)
    pred11_spv_w_config <- predict(model, x11_spv)
    pred1_csr_w_config <- predict(model, x1_csr)
    pred11_csr_w_config <- predict(model, x11_csr)

    expect_equal(pred1_wo_config, pred_all[1L])
    expect_equal(pred11_wo_config, pred_all[11L])
    expect_equal(pred1_spv_wo_config, unname(pred_all[1L]))
    expect_equal(pred11_spv_wo_config, unname(pred_all[11L]))
    expect_equal(pred1_csr_wo_config, pred_all[1L])
    expect_equal(pred11_csr_wo_config, pred_all[11L])

    expect_equal(pred1_w_config, pred_all[1L])
    expect_equal(pred11_w_config, pred_all[11L])
    expect_equal(pred1_spv_w_config, unname(pred_all[1L]))
    expect_equal(pred11_spv_w_config, unname(pred_all[11L]))
    expect_equal(pred1_csr_w_config, pred_all[1L])
    expect_equal(pred11_csr_w_config, pred_all[11L])
})

test_that("Fast-predict configuration accepts non-default prediction types", {
    data(mtcars)
    X <- as.matrix(mtcars[, -1L])
    y <- mtcars[, 1L]
    dtrain <- lgb.Dataset(X, label = y, params = list(max_bin = 5L))
605
    params <- list(min_data_in_leaf = 2L, num_threads = .LGB_MAX_THREADS)
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
    model <- lgb.train(
      params = params
     , data = dtrain
     , obj = "regression"
     , nrounds = 5L
     , verbose = -1L
    )

    x1 <- X[1L, , drop = FALSE]
    x11 <- X[11L, , drop = FALSE]

    pred_all <- predict(model, X, type = "leaf")
    pred1_wo_config <- predict(model, x1, type = "leaf")
    pred11_wo_config <- predict(model, x11, type = "leaf")
    expect_equal(pred1_wo_config, pred_all[1L, , drop = FALSE])
    expect_equal(pred11_wo_config, pred_all[11L, , drop = FALSE])

    lgb.configure_fast_predict(model, type = "leaf")
    pred1_w_config <- predict(model, x1, type = "leaf")
    pred11_w_config <- predict(model, x11, type = "leaf")
    expect_equal(pred1_w_config, pred_all[1L, , drop = FALSE])
    expect_equal(pred11_w_config, pred_all[11L, , drop = FALSE])
})

test_that("Fast-predict configuration does not block other prediction types", {
    data(mtcars)
    X <- as.matrix(mtcars[, -1L])
    y <- mtcars[, 1L]
    dtrain <- lgb.Dataset(X, label = y, params = list(max_bin = 5L))
635
    params <- list(min_data_in_leaf = 2L, num_threads = .LGB_MAX_THREADS)
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
    model <- lgb.train(
      params = params
     , data = dtrain
     , obj = "regression"
     , nrounds = 5L
     , verbose = -1L
    )

    x1 <- X[1L, , drop = FALSE]
    x11 <- X[11L, , drop = FALSE]

    pred_all <- predict(model, X)
    pred_all_leaf <- predict(model, X, type = "leaf")

    lgb.configure_fast_predict(model)
    pred1_w_config <- predict(model, x1)
    pred11_w_config <- predict(model, x11)
    pred1_leaf_w_config <- predict(model, x1, type = "leaf")
    pred11_leaf_w_config <- predict(model, x11, type = "leaf")

    expect_equal(pred1_w_config, pred_all[1L])
    expect_equal(pred11_w_config, pred_all[11L])
    expect_equal(pred1_leaf_w_config, pred_all_leaf[1L, , drop = FALSE])
    expect_equal(pred11_leaf_w_config, pred_all_leaf[11L, , drop = FALSE])
})

662
663
664
665
666
667
668
669
670
test_that("predict type='class' returns predicted class for classification objectives", {
    data(agaricus.train, package = "lightgbm")
    X <- as.matrix(agaricus.train$data)
    y <- agaricus.train$label
    dtrain <- lgb.Dataset(X, label = y, params = list(max_bins = 5L))
    bst <- lgb.train(
        data = dtrain
        , obj = "binary"
        , nrounds = 5L
671
        , verbose = .LGB_VERBOSITY
672
        , params = list(num_threads = .LGB_MAX_THREADS)
673
674
675
676
677
678
679
680
681
682
683
684
    )
    pred <- predict(bst, X, type = "class")
    expect_true(all(pred %in% c(0L, 1L)))

    data(iris)
    X <- as.matrix(iris[, -5L])
    y <- as.numeric(iris$Species) - 1.0
    dtrain <- lgb.Dataset(X, label = y)
    model <- lgb.train(
      data = dtrain
      , obj = "multiclass"
      , nrounds = 5L
685
      , verbose = .LGB_VERBOSITY
686
      , params = list(num_class = 3L, num_threads = .LGB_MAX_THREADS)
687
688
689
690
691
692
693
694
695
696
697
698
699
700
    )
    pred <- predict(model, X, type = "class")
    expect_true(all(pred %in% c(0L, 1L, 2L)))
})

test_that("predict type='class' returns values in the target's range for regression objectives", {
    data(agaricus.train, package = "lightgbm")
    X <- as.matrix(agaricus.train$data)
    y <- agaricus.train$label
    dtrain <- lgb.Dataset(X, label = y, params = list(max_bins = 5L))
    bst <- lgb.train(
        data = dtrain
        , obj = "regression"
        , nrounds = 5L
701
        , verbose = .LGB_VERBOSITY
702
        , params = list(num_threads = .LGB_MAX_THREADS)
703
704
705
706
    )
    pred <- predict(bst, X, type = "class")
    expect_true(!any(pred %in% c(0.0, 1.0)))
})