fix calculation of weighted gamma loss (fixes #4174) (#4283)

* fixed weighted gamma obj

* added unit tests

* fixing linter errors

* another linter

* set seed

* fix linter (integer seed)
This commit is contained in:
Michael Mayer 2021-05-21 14:28:10 +02:00 коммит произвёл GitHub
Родитель 237ac299fc
Коммит 4b1b412452
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
2 изменённых файлов: 68 добавлений и 1 удалений

Просмотреть файл

@ -0,0 +1,67 @@
context("Case weights are respected")
test_that("Gamma regression reacts on 'weight'", {
n <- 100L
set.seed(87L)
X <- matrix(runif(2L * n), ncol = 2L)
y <- X[, 1L] + X[, 2L] + runif(n)
X_pred <- X[1L:5L, ]
params <- list(objective = "gamma")
# Unweighted
dtrain <- lgb.Dataset(X, label = y)
bst <- lgb.train(
params = params
, data = dtrain
, nrounds = 4L
, verbose = 0L
)
pred_unweighted <- predict(bst, X_pred)
# Constant weight 1
dtrain <- lgb.Dataset(
X
, label = y
, weight = rep(1.0, n)
)
bst <- lgb.train(
params = params
, data = dtrain
, nrounds = 4L
, verbose = 0L
)
pred_weighted_1 <- predict(bst, X_pred)
# Constant weight 2
dtrain <- lgb.Dataset(
X
, label = y
, weight = rep(2.0, n)
)
bst <- lgb.train(
params = params
, data = dtrain
, nrounds = 4L
, verbose = 0L
)
pred_weighted_2 <- predict(bst, X_pred)
# Non-constant weights
dtrain <- lgb.Dataset(
X
, label = y
, weight = seq(0.0, 1.0, length.out = n)
)
bst <- lgb.train(
params = params
, data = dtrain
, nrounds = 4L
, verbose = 0L
)
pred_weighted <- predict(bst, X_pred)
expect_equal(pred_unweighted, pred_weighted_1)
expect_equal(pred_weighted_1, pred_weighted_2)
expect_false(all(pred_unweighted == pred_weighted))
})

Просмотреть файл

@ -695,7 +695,7 @@ class RegressionGammaLoss : public RegressionPoissonLoss {
} else {
#pragma omp parallel for schedule(static)
for (data_size_t i = 0; i < num_data_; ++i) {
gradients[i] = static_cast<score_t>(1.0 - label_[i] * std::exp(-score[i]) * weights_[i]);
gradients[i] = static_cast<score_t>((1.0 - label_[i] * std::exp(-score[i])) * weights_[i]);
hessians[i] = static_cast<score_t>(label_[i] * std::exp(-score[i]) * weights_[i]);
}
}