test_custom_objective.R 1.02 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
9
10
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)

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

evalerror <- function(preds, dtrain) {
  labels <- getinfo(dtrain, "label")
19
  err <- as.numeric(sum(labels != (preds > 0.0))) / length(labels)
20
21
22
23
24
  return(list(
    name = "error"
    , value = err
    , higher_better = FALSE
  ))
Guolin Ke's avatar
Guolin Ke committed
25
26
}

27
param <- list(
28
29
  num_leaves = 8L
  , learning_rate = 1.0
30
31
32
  , objective = logregobj
  , metric = "auc"
)
33
num_round <- 10L
Guolin Ke's avatar
Guolin Ke committed
34
35

test_that("custom objective works", {
36
  bst <- lgb.train(param, dtrain, num_round, watchlist, eval = evalerror)
Guolin Ke's avatar
Guolin Ke committed
37
38
  expect_false(is.null(bst$record_evals))
})