test_basic.R 9.25 KB
Newer Older
1
context("lightgbm()")
Guolin Ke's avatar
Guolin Ke committed
2

3
4
data(agaricus.train, package = "lightgbm")
data(agaricus.test, package = "lightgbm")
Guolin Ke's avatar
Guolin Ke committed
5
6
7
train <- agaricus.train
test <- agaricus.test

8
windows_flag <- grepl("Windows", Sys.info()[["sysname"]])
Guolin Ke's avatar
Guolin Ke committed
9

10
11
TOLERANCE <- 1e-6

Guolin Ke's avatar
Guolin Ke committed
12
test_that("train and predict binary classification", {
13
  nrounds <- 10L
14
15
16
  bst <- lightgbm(
    data = train$data
    , label = train$label
17
    , num_leaves = 5L
18
19
20
21
    , nrounds = nrounds
    , objective = "binary"
    , metric = "binary_error"
  )
Guolin Ke's avatar
Guolin Ke committed
22
23
24
25
26
  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)
27
  expect_equal(length(pred), 1611L)
28

29
30
31
32
  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]
33
  expect_lt(abs(err_pred1 - err_log), TOLERANCE)
Guolin Ke's avatar
Guolin Ke committed
34
35
36
37
})


test_that("train and predict softmax", {
38
  lb <- as.numeric(iris$Species) - 1L
Guolin Ke's avatar
Guolin Ke committed
39

40
  bst <- lightgbm(
41
    data = as.matrix(iris[, -5L])
42
    , label = lb
43
    , num_leaves = 4L
44
    , learning_rate = 0.1
45
46
47
    , nrounds = 20L
    , min_data = 20L
    , min_hess = 20.0
48
49
    , objective = "multiclass"
    , metric = "multi_error"
50
    , num_class = 3L
51
  )
Guolin Ke's avatar
Guolin Ke committed
52
53
54
55
56

  expect_false(is.null(bst$record_evals))
  record_results <- lgb.get.eval.result(bst, "train", "multi_error")
  expect_lt(min(record_results), 0.03)

57
58
  pred <- predict(bst, as.matrix(iris[, -5L]))
  expect_equal(length(pred), nrow(iris) * 3L)
Guolin Ke's avatar
Guolin Ke committed
59
60
61
62
})


test_that("use of multiple eval metrics works", {
63
64
65
  bst <- lightgbm(
    data = train$data
    , label = train$label
66
67
68
    , num_leaves = 4L
    , learning_rate = 1.0
    , nrounds = 10L
69
    , objective = "binary"
70
    , metric = list("binary_error", "auc", "binary_logloss")
71
  )
Guolin Ke's avatar
Guolin Ke committed
72
73
74
  expect_false(is.null(bst$record_evals))
})

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
102
103
104
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
    , num_leaves = 5L
    , nrounds = nrounds
    , objective = "binary"
    , metric = "binary_error"
  )
  expect_true(abs(bst$lower_bound() - -1.590853) < TOLERANCE)
  expect_true(abs(bst$upper_bound() - 1.871015) <  TOLERANCE)
})

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
    , num_leaves = 5L
    , nrounds = nrounds
    , objective = "regression"
    , metric = "l2"
  )
  expect_true(abs(bst$lower_bound() - 0.1513859) < TOLERANCE)
  expect_true(abs(bst$upper_bound() - 0.9080349) < TOLERANCE)
})

105
106
107
108
109
110
111
112
113
114
115
116
117
118
test_that("lightgbm() rejects negative or 0 value passed to nrounds", {
  dtrain <- lgb.Dataset(train$data, label = train$label)
  params <- list(objective = "regression", metric = "l2,l1")
  for (nround_value in c(-10L, 0L)) {
    expect_error({
      bst <- lightgbm(
        data = dtrain
        , params = params
        , nrounds = nround_value
      )
    }, "nrounds should be greater than zero")
  }
})

Guolin Ke's avatar
Guolin Ke committed
119
120

test_that("training continuation works", {
121
  testthat::skip("This test is currently broken. See issue #2468 for details.")
122
123
124
125
126
  dtrain <- lgb.Dataset(
    train$data
    , label = train$label
    , free_raw_data = FALSE
  )
127
  watchlist <- list(train = dtrain)
128
129
130
  param <- list(
    objective = "binary"
    , metric = "binary_logloss"
131
132
    , num_leaves = 5L
    , learning_rate = 1.0
133
  )
Guolin Ke's avatar
Guolin Ke committed
134
135

  # for the reference, use 10 iterations at once:
136
137
  bst <- lgb.train(param, dtrain, nrounds = 10L, watchlist)
  err_bst <- lgb.get.eval.result(bst, "train", "binary_logloss", 10L)
Guolin Ke's avatar
Guolin Ke committed
138
  # first 5 iterations:
139
  bst1 <- lgb.train(param, dtrain, nrounds = 5L, watchlist)
Guolin Ke's avatar
Guolin Ke committed
140
141
142
  # test continuing from a model in file
  lgb.save(bst1, "lightgbm.model")
  # continue for 5 more:
143
144
  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
145
146
  expect_lt(abs(err_bst - err_bst2), 0.01)

147
148
  bst2 <- lgb.train(param, dtrain, nrounds = 5L, watchlist, init_model = "lightgbm.model")
  err_bst2 <- lgb.get.eval.result(bst2, "train", "binary_logloss", 10L)
Guolin Ke's avatar
Guolin Ke committed
149
150
151
  expect_lt(abs(err_bst - err_bst2), 0.01)
})

152
context("lgb.cv()")
Guolin Ke's avatar
Guolin Ke committed
153
154

test_that("cv works", {
155
156
157
158
159
  dtrain <- lgb.Dataset(train$data, label = train$label)
  params <- list(objective = "regression", metric = "l2,l1")
  bst <- lgb.cv(
    params
    , dtrain
160
161
162
163
164
    , 10L
    , nfold = 5L
    , min_data = 1L
    , learning_rate = 1.0
    , early_stopping_rounds = 10L
165
  )
Guolin Ke's avatar
Guolin Ke committed
166
167
  expect_false(is.null(bst$record_evals))
})
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286

test_that("lgb.cv() rejects negative or 0 value passed to nrounds", {
  dtrain <- lgb.Dataset(train$data, label = train$label)
  params <- list(objective = "regression", metric = "l2,l1")
  for (nround_value in c(-10L, 0L)) {
    expect_error({
      bst <- lgb.cv(
        params
        , dtrain
        , nround_value
        , nfold = 5L
        , min_data = 1L
      )
    }, "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(
        params = list(objective = "regression", metric = "l2,l1")
        , data = val
        , 10L
        , nfold = 5L
        , min_data = 1L
      )
    }, regexp = "'label' must be provided for lgb.cv if 'data' is not an 'lgb.Dataset'", fixed = TRUE)
  }
})

context("lgb.train()")

test_that("lgb.train() rejects negative or 0 value passed to nrounds", {
  dtrain <- lgb.Dataset(train$data, label = train$label)
  params <- list(objective = "regression", metric = "l2,l1")
  for (nround_value in c(-10L, 0L)) {
    expect_error({
      bst <- lgb.train(
        params
        , dtrain
        , nround_value
      )
    }, "nrounds should be greater than zero")
  }
})

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(
        params = list(objective = "regression", metric = "l2,l1")
        , 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(
      params = list(objective = "regression", metric = "l2,l1")
      , 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(
      params = list(objective = "regression", metric = "l2,l1")
      , 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(
      params = list(objective = "regression", metric = "l2,l1")
      , data = lgb.Dataset(train$data, label = train$label)
      , 10L
      , valids = valids
    )
  }, regexp = "each element of valids must have a name")
})
287
288
289
290
291
292
293
294
295
296
297
298
299

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
  )
  params <- list(
    objective = "binary"
    , metric = "binary_error"
    , force_col_wise = TRUE
  )
300
  bst_col_wise <- lgb.train(
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
    params = params
    , data = dtrain
    , nrounds = nrounds
  )

  params <- list(
    objective = "binary"
    , metric = "binary_error"
    , force_row_wise = TRUE
  )
  bst_row_wise <- lgb.train(
    params = params
    , data = dtrain
    , nrounds = nrounds
  )

  expected_error <- 0.003070782
318
  expect_equal(bst_col_wise$eval_train()[[1L]][["value"]], expected_error)
319
320
321
322
  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
323
  for (bst in list(bst_row_wise, bst_col_wise)) {
324
325
326
327
328
329
    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)
  }
})