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

5
context("Test models with custom objective")
Guolin Ke's avatar
Guolin Ke committed
6

7
8
data(agaricus.train, package = "lightgbm")
data(agaricus.test, package = "lightgbm")
Guolin Ke's avatar
Guolin Ke committed
9
10
11
12
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)

13
14
TOLERANCE <- 1e-6

Guolin Ke's avatar
Guolin Ke committed
15
logregobj <- function(preds, dtrain) {
16
  labels <- get_field(dtrain, "label")
17
  preds <- 1.0 / (1.0 + exp(-preds))
Guolin Ke's avatar
Guolin Ke committed
18
  grad <- preds - labels
19
  hess <- preds * (1.0 - preds)
Guolin Ke's avatar
Guolin Ke committed
20
21
22
  return(list(grad = grad, hess = hess))
}

23
24
25
26
# 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
27
evalerror <- function(preds, dtrain) {
28
  labels <- get_field(dtrain, "label")
29
30
  preds <- 1.0 / (1.0 + exp(-preds))
  err <- as.numeric(sum(labels != (preds > 0.5))) / length(labels)
31
32
33
34
35
  return(list(
    name = "error"
    , value = err
    , higher_better = FALSE
  ))
Guolin Ke's avatar
Guolin Ke committed
36
37
}

38
param <- list(
39
40
  num_leaves = 8L
  , learning_rate = 1.0
41
42
  , objective = logregobj
  , metric = "auc"
43
  , verbose = VERBOSITY
44
)
45
num_round <- 10L
Guolin Ke's avatar
Guolin Ke committed
46
47

test_that("custom objective works", {
48
  bst <- lgb.train(param, dtrain, num_round, watchlist, eval = evalerror)
Guolin Ke's avatar
Guolin Ke committed
49
50
  expect_false(is.null(bst$record_evals))
})
51
52
53
54
55
56
57

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
58
      , verbose = VERBOSITY
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
    )
    , 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"]])
})