Debian Codegraph @

tests/testthat/test_io.R

raw
1 context("Test model IO.")
2
3 data(agaricus.train, package = "xgboost")
4 data(agaricus.test, package = "xgboost")
5 train <- agaricus.train
6 test <- agaricus.test
7
8 test_that("load/save raw works", {
9 nrounds <- 8
10 booster <- xgb.train(
11 data = xgb.DMatrix(train$data, label = train$label, nthread = 1),
12 nrounds = nrounds,
13 params = xgb.params(
14 objective = "binary:logistic",
15 nthread = 2
16 )
17 )
18
19 json_bytes <- xgb.save.raw(booster, raw_format = "json")
20 ubj_bytes <- xgb.save.raw(booster, raw_format = "ubj")
21
22 from_json <- xgb.load.raw(json_bytes)
23 from_ubj <- xgb.load.raw(ubj_bytes)
24
25 json2ubj <- xgb.save.raw(from_json, raw_format = "ubj")
26 ubj2ubj <- xgb.save.raw(from_ubj, raw_format = "ubj")
27
28 expect_equal(json2ubj, ubj2ubj)
29 })
30
31 test_that("saveRDS preserves C and R attributes", {
32 data(mtcars)
33 y <- mtcars$mpg
34 x <- as.matrix(mtcars[, -1])
35 dm <- xgb.DMatrix(x, label = y, nthread = 1)
36 model <- xgb.train(
37 data = dm,
38 params = xgb.params(nthread = 1, max_depth = 2),
39 nrounds = 5
40 )
41 attributes(model)$my_attr <- "qwerty"
42 xgb.attr(model, "c_attr") <- "asdf"
43
44 fname <- file.path(tempdir(), "xgb_model.Rds")
45 saveRDS(model, fname)
46 model_new <- readRDS(fname)
47
48 expect_equal(attributes(model_new)$my_attr, attributes(model)$my_attr)
49 expect_equal(xgb.attr(model, "c_attr"), xgb.attr(model_new, "c_attr"))
50 })
51
52 test_that("R serializers keep C config", {
53 data(mtcars)
54 y <- mtcars$mpg
55 x <- as.matrix(mtcars[, -1])
56 dm <- xgb.DMatrix(x, label = y, nthread = 1)
57 model <- xgb.train(
58 data = dm,
59 params = list(
60 tree_method = "approx",
61 nthread = 1,
62 max_depth = 2
63 ),
64 nrounds = 3
65 )
66 model_new <- unserialize(serialize(model, NULL))
67 expect_equal(
68 xgb.config(model)$learner$gradient_booster$gbtree_train_param$tree_method,
69 xgb.config(model_new)$learner$gradient_booster$gbtree_train_param$tree_method
70 )
71 expect_equal(variable.names(model), variable.names(model_new))
72 })