| 1 |
context('Test Poisson regression model') |
| 2 |
|
| 3 |
set.seed(1994) |
| 4 |
|
| 5 |
test_that("Poisson regression works", { |
| 6 |
data(mtcars) |
| 7 |
bst <- xgb.train( |
| 8 |
data = xgb.DMatrix(as.matrix(mtcars[, -11]), label = mtcars[, 11], nthread = 1), |
| 9 |
nrounds = 10, verbose = 0, |
| 10 |
params = xgb.params(objective = 'count:poisson', nthread = 2) |
| 11 |
) |
| 12 |
expect_equal(class(bst), "xgb.Booster") |
| 13 |
pred <- predict(bst, as.matrix(mtcars[, -11])) |
| 14 |
expect_equal(length(pred), 32) |
| 15 |
expect_lt(sqrt(mean((pred - mtcars[, 11])^2)), 1.2) |
| 16 |
}) |
| 17 |
|
| 18 |
test_that("Poisson regression is centered around mean", { |
| 19 |
m <- 50L |
| 20 |
n <- 10L |
| 21 |
y <- rpois(m, n) |
| 22 |
x <- matrix(rnorm(m * n), nrow = m) |
| 23 |
model <- xgb.train( |
| 24 |
data = xgb.DMatrix(x, label = y, nthread = 1), |
| 25 |
params = xgb.params(objective = "count:poisson", min_split_loss = 1e4), |
| 26 |
nrounds = 1 |
| 27 |
) |
| 28 |
model_json <- xgb.save.raw(model, "json") |> rawToChar() |> jsonlite::fromJSON() |
| 29 |
expect_equal( |
| 30 |
get_basescore(model_json), |
| 31 |
mean(y), |
| 32 |
tolerance = 1e-4 |
| 33 |
) |
| 34 |
|
| 35 |
pred <- predict(model, x) |
| 36 |
expect_equal( |
| 37 |
pred, |
| 38 |
rep(mean(y), m), |
| 39 |
tolerance = 1e-4 |
| 40 |
) |
| 41 |
|
| 42 |
w <- y + 1 |
| 43 |
model_weighted <- xgb.train( |
| 44 |
data = xgb.DMatrix(x, label = y, weight = w, nthread = 1), |
| 45 |
params = xgb.params(objective = "count:poisson", min_split_loss = 1e4), |
| 46 |
nrounds = 1 |
| 47 |
) |
| 48 |
model_json <- xgb.save.raw(model_weighted, "json") |> rawToChar() |> jsonlite::fromJSON() |
| 49 |
expect_equal( |
| 50 |
get_basescore(model_json), |
| 51 |
weighted.mean(y, w), |
| 52 |
tolerance = 1e-4 |
| 53 |
) |
| 54 |
}) |