test_custom_objective.R 2.12 KB
Newer Older
1
context("Test models with custom objective")
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
8
dtrain <- lgb.Dataset(agaricus.train$data, label = agaricus.train$label)
dtest <- lgb.Dataset(agaricus.test$data, label = agaricus.test$label)
watchlist <- list(eval = dtest, train = dtrain)

9
10
TOLERANCE <- 1e-6

Guolin Ke's avatar
Guolin Ke committed
11
12
logregobj <- function(preds, dtrain) {
  labels <- getinfo(dtrain, "label")
13
  preds <- 1.0 / (1.0 + exp(-preds))
Guolin Ke's avatar
Guolin Ke committed
14
  grad <- preds - labels
15
  hess <- preds * (1.0 - preds)
Guolin Ke's avatar
Guolin Ke committed
16
17
18
  return(list(grad = grad, hess = hess))
}

19
20
21
22
# User-defined evaluation function returns a pair (metric_name, result, higher_better)
# NOTE: when you do customized loss function, the default prediction value is margin
# This may make built-in evalution metric calculate wrong results
# Keep this in mind when you use the customization, and maybe you need write customized evaluation function
Guolin Ke's avatar
Guolin Ke committed
23
24
evalerror <- function(preds, dtrain) {
  labels <- getinfo(dtrain, "label")
25
26
  preds <- 1.0 / (1.0 + exp(-preds))
  err <- as.numeric(sum(labels != (preds > 0.5))) / length(labels)
27
28
29
30
31
  return(list(
    name = "error"
    , value = err
    , higher_better = FALSE
  ))
Guolin Ke's avatar
Guolin Ke committed
32
33
}

34
param <- list(
35
36
  num_leaves = 8L
  , learning_rate = 1.0
37
38
39
  , objective = logregobj
  , metric = "auc"
)
40
num_round <- 10L
Guolin Ke's avatar
Guolin Ke committed
41
42

test_that("custom objective works", {
43
  bst <- lgb.train(param, dtrain, num_round, watchlist, eval = evalerror)
Guolin Ke's avatar
Guolin Ke committed
44
45
  expect_false(is.null(bst$record_evals))
})
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

test_that("using a custom objective, custom eval, and no other metrics works", {
  set.seed(708L)
  bst <- lgb.train(
    params = list(
      num_leaves = 8L
      , learning_rate = 1.0
    )
    , data = dtrain
    , nrounds = 4L
    , valids = watchlist
    , obj = logregobj
    , eval = evalerror
  )
  expect_false(is.null(bst$record_evals))
  expect_equal(bst$best_iter, 4L)
  expect_true(abs(bst$best_score - 0.000621) < TOLERANCE)

  eval_results <- bst$eval_valid(feval = evalerror)[[1L]]
  expect_true(eval_results[["data_name"]] == "eval")
  expect_true(abs(eval_results[["value"]] - 0.0006207325) < TOLERANCE)
  expect_true(eval_results[["name"]] == "error")
  expect_false(eval_results[["higher_better"]])
})