如何为我的自定义丢失函数修改lightgbm?

时间:2017-11-02 04:04:35

标签: lightgbm

添加我自己的自定义丢失功能时应该更改哪些文件?我知道我可以在ObjectiveFunction中添加我的目标和渐变/粗体计算,只是想知道我还有什么需要做的,或者是否还有其他自定义丢失函数的替代方案。

1 个答案:

答案 0 :(得分:0)

根据lightGBM early stopping example中的演示文件,

将目标函数设置为:

# User define objective function, given prediction, return gradient and second order gradient
# This is loglikelihood loss
logregobj <- function(preds, dtrain) {
  labels <- getinfo(dtrain, "label")
  preds <- 1 / (1 + exp(-preds))
  grad <- preds - labels
  hess <- preds * (1 - preds)
  return(list(grad = grad, hess = hess))
}

将错误功能设置为:

# User defined evaluation function, return a pair metric_name, result, higher_better
# NOTE: when you do customized loss function, the default prediction value is margin
# This may make buildin evalution metric not function properly
# For example, we are doing logistic loss, the prediction is score before logistic transformation
# The buildin evaluation error assumes input is after logistic transformation
# Take this in mind when you use the customization, and maybe you need write customized evaluation function
evalerror <- function(preds, dtrain) {
  labels <- getinfo(dtrain, "label")
  err <- as.numeric(sum(labels != (preds > 0.5))) / length(labels)
  return(list(name = "error", value = err, higher_better = FALSE))
}

然后你可以运行lightgbm:

bst <- lgb.train(param,
                 dtrain,
                 num_round,
                 valids,
                 objective = logregobj,
                 eval = evalerror,
early_stopping_round = 3)