cross_validation.R 2.14 KB
Newer Older
Guolin Ke's avatar
Guolin Ke committed
1
2
require(lightgbm)
# load in the agaricus dataset
3
4
data(agaricus.train, package = "lightgbm")
data(agaricus.test, package = "lightgbm")
Guolin Ke's avatar
Guolin Ke committed
5
dtrain <- lgb.Dataset(agaricus.train$data, label = agaricus.train$label)
6
dtest <- lgb.Dataset.create.valid(dtrain, data = agaricus.test$data, label = agaricus.test$label)
Guolin Ke's avatar
Guolin Ke committed
7

8
nrounds <- 2L
9
param <- list(
10
11
  num_leaves = 4L
  , learning_rate = 1.0
12
13
  , objective = "binary"
)
Guolin Ke's avatar
Guolin Ke committed
14

15
16
print("Running cross validation")
# Do cross validation, this will print result out as
Guolin Ke's avatar
Guolin Ke committed
17
18
# [iteration]  metric_name:mean_value+std_value
# std_value is standard deviation of the metric
19
20
21
22
lgb.cv(
  param
  , dtrain
  , nrounds
23
  , nfold = 5L
24
25
  , eval = "binary_error"
)
Guolin Ke's avatar
Guolin Ke committed
26

27
print("Running cross validation, disable standard deviation display")
Guolin Ke's avatar
Guolin Ke committed
28
29
30
# do cross validation, this will print result out as
# [iteration]  metric_name:mean_value+std_value
# std_value is standard deviation of the metric
31
32
33
34
lgb.cv(
  param
  , dtrain
  , nrounds
35
  , nfold = 5L
36
37
38
  , eval = "binary_error"
  , showsd = FALSE
)
Guolin Ke's avatar
Guolin Ke committed
39

joshkyh's avatar
joshkyh committed
40
# You can also do cross validation with cutomized loss function
41
print("Running cross validation, with cutomsized loss function")
Guolin Ke's avatar
Guolin Ke committed
42
43
44

logregobj <- function(preds, dtrain) {
  labels <- getinfo(dtrain, "label")
45
  preds <- 1.0 / (1.0 + exp(-preds))
Guolin Ke's avatar
Guolin Ke committed
46
  grad <- preds - labels
47
  hess <- preds * (1.0 - preds)
Guolin Ke's avatar
Guolin Ke committed
48
49
  return(list(grad = grad, hess = hess))
}
50
51
52
53
54
55

# 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
# For example, we are doing logistic loss, the prediction is score before logistic transformation
# Keep this in mind when you use the customization, and maybe you need write customized evaluation function
Guolin Ke's avatar
Guolin Ke committed
56
57
evalerror <- function(preds, dtrain) {
  labels <- getinfo(dtrain, "label")
58
59
  preds <- 1.0 / (1.0 + exp(-preds))
  err <- as.numeric(sum(labels != (preds > 0.5))) / length(labels)
60
  return(list(name = "error", value = err, higher_better = FALSE))
Guolin Ke's avatar
Guolin Ke committed
61
62
63
}

# train with customized objective
64
65
66
67
68
69
lgb.cv(
  params = param
  , data = dtrain
  , nrounds = nrounds
  , obj = logregobj
  , eval = evalerror
70
  , nfold = 5L
71
)