| 1 |
context('Test helper functions') |
| 2 |
|
| 3 |
VCD_AVAILABLE <- requireNamespace("vcd", quietly = TRUE) |
| 4 |
.skip_if_vcd_not_available <- function() { |
| 5 |
if (!VCD_AVAILABLE) { |
| 6 |
testthat::skip("Optional testing dependency 'vcd' not found.") |
| 7 |
} |
| 8 |
} |
| 9 |
|
| 10 |
float_tolerance <- 5e-6 |
| 11 |
|
| 12 |
# disable some tests for 32-bit environment |
| 13 |
flag_32bit <- .Machine$sizeof.pointer != 8 |
| 14 |
|
| 15 |
set.seed(1982) |
| 16 |
|
| 17 |
nrounds <- 12 |
| 18 |
if (isTRUE(VCD_AVAILABLE)) { |
| 19 |
data(Arthritis, package = "vcd") |
| 20 |
df <- data.table::data.table(Arthritis, keep.rownames = FALSE) |
| 21 |
df[, AgeDiscret := as.factor(round(Age / 10, 0))] |
| 22 |
df[, AgeCat := as.factor(ifelse(Age > 30, "Old", "Young"))] |
| 23 |
df[, ID := NULL] |
| 24 |
sparse_matrix <- Matrix::sparse.model.matrix(Improved~.-1, data = df) # nolint |
| 25 |
label <- df[, ifelse(Improved == "Marked", 1, 0)] |
| 26 |
|
| 27 |
# binary |
| 28 |
bst.Tree <- xgb.train( |
| 29 |
data = xgb.DMatrix(sparse_matrix, label = label, nthread = 1), |
| 30 |
nrounds = nrounds, verbose = 0, |
| 31 |
params = xgb.params( |
| 32 |
max_depth = 9, |
| 33 |
learning_rate = 1, |
| 34 |
nthread = 2, |
| 35 |
objective = "binary:logistic", |
| 36 |
booster = "gbtree", |
| 37 |
base_score = 0.5 |
| 38 |
) |
| 39 |
) |
| 40 |
|
| 41 |
bst.GLM <- xgb.train( |
| 42 |
data = xgb.DMatrix(sparse_matrix, label = label, nthread = 1), |
| 43 |
nrounds = nrounds, verbose = 0, |
| 44 |
params = xgb.params( |
| 45 |
learning_rate = 1, |
| 46 |
nthread = 1, |
| 47 |
objective = "binary:logistic", |
| 48 |
booster = "gblinear", |
| 49 |
base_score = 0.5 |
| 50 |
) |
| 51 |
) |
| 52 |
|
| 53 |
feature.names <- colnames(sparse_matrix) |
| 54 |
|
| 55 |
# without feature names |
| 56 |
bst.Tree.unnamed <- xgb.copy.Booster(bst.Tree) |
| 57 |
setinfo(bst.Tree.unnamed, "feature_name", NULL) |
| 58 |
} |
| 59 |
|
| 60 |
# multiclass |
| 61 |
mlabel <- as.numeric(iris$Species) - 1 |
| 62 |
nclass <- 3 |
| 63 |
mbst.Tree <- xgb.train( |
| 64 |
data = xgb.DMatrix(as.matrix(iris[, -5]), label = mlabel, nthread = 1), |
| 65 |
verbose = 0, |
| 66 |
nrounds = nrounds, |
| 67 |
params = xgb.params( |
| 68 |
max_depth = 3, learning_rate = 0.5, nthread = 2, |
| 69 |
objective = "multi:softprob", num_class = nclass, base_score = 0 |
| 70 |
) |
| 71 |
) |
| 72 |
|
| 73 |
mbst.GLM <- xgb.train( |
| 74 |
data = xgb.DMatrix(as.matrix(iris[, -5]), label = mlabel, nthread = 1), |
| 75 |
verbose = 0, |
| 76 |
nrounds = nrounds, |
| 77 |
params = xgb.params( |
| 78 |
booster = "gblinear", learning_rate = 0.1, nthread = 1, |
| 79 |
objective = "multi:softprob", num_class = nclass, base_score = 0 |
| 80 |
) |
| 81 |
) |
| 82 |
|
| 83 |
test_that("xgb.dump works", { |
| 84 |
.skip_if_vcd_not_available() |
| 85 |
if (!flag_32bit) |
| 86 |
expect_length(xgb.dump(bst.Tree), 200) |
| 87 |
dump_file <- file.path(tempdir(), 'xgb.model.dump') |
| 88 |
expect_true(xgb.dump(bst.Tree, dump_file, with_stats = TRUE)) |
| 89 |
expect_true(file.exists(dump_file)) |
| 90 |
expect_gt(file.size(dump_file), 8000) |
| 91 |
|
| 92 |
# JSON format |
| 93 |
dmp <- xgb.dump(bst.Tree, dump_format = "json") |
| 94 |
expect_length(dmp, 1) |
| 95 |
if (!flag_32bit) |
| 96 |
expect_length(grep('nodeid', strsplit(dmp, '\n', fixed = TRUE)[[1]], fixed = TRUE), 188) |
| 97 |
}) |
| 98 |
|
| 99 |
test_that("xgb.dump works for gblinear", { |
| 100 |
.skip_if_vcd_not_available() |
| 101 |
expect_length(xgb.dump(bst.GLM), 14) |
| 102 |
# also make sure that it works properly for a sparse model where some coefficients |
| 103 |
# are 0 from setting large L1 regularization: |
| 104 |
bst.GLM.sp <- xgb.train( |
| 105 |
data = xgb.DMatrix(sparse_matrix, label = label, nthread = 1), |
| 106 |
nrounds = 1, |
| 107 |
params = xgb.params( |
| 108 |
learning_rate = 1, |
| 109 |
nthread = 2, |
| 110 |
reg_alpha = 2, |
| 111 |
objective = "binary:logistic", |
| 112 |
booster = "gblinear" |
| 113 |
) |
| 114 |
) |
| 115 |
d.sp <- xgb.dump(bst.GLM.sp) |
| 116 |
expect_length(d.sp, 14) |
| 117 |
expect_gt(sum(d.sp == "0"), 0) |
| 118 |
|
| 119 |
# JSON format |
| 120 |
dmp <- xgb.dump(bst.GLM.sp, dump_format = "json") |
| 121 |
expect_length(dmp, 1) |
| 122 |
expect_length(grep('\\d', strsplit(dmp, '\n', fixed = TRUE)[[1]]), 11) |
| 123 |
}) |
| 124 |
|
| 125 |
test_that("predict leafs works", { |
| 126 |
.skip_if_vcd_not_available() |
| 127 |
# no error for gbtree |
| 128 |
expect_error(pred_leaf <- predict(bst.Tree, sparse_matrix, predleaf = TRUE), regexp = NA) |
| 129 |
expect_equal(dim(pred_leaf), c(nrow(sparse_matrix), nrounds)) |
| 130 |
# error for gblinear |
| 131 |
expect_error(predict(bst.GLM, sparse_matrix, predleaf = TRUE)) |
| 132 |
}) |
| 133 |
|
| 134 |
test_that("predict feature contributions works", { |
| 135 |
.skip_if_vcd_not_available() |
| 136 |
# gbtree binary classifier |
| 137 |
expect_error(pred_contr <- predict(bst.Tree, sparse_matrix, predcontrib = TRUE), regexp = NA) |
| 138 |
expect_equal(dim(pred_contr), c(nrow(sparse_matrix), ncol(sparse_matrix) + 1)) |
| 139 |
expect_equal(colnames(pred_contr), c(colnames(sparse_matrix), "(Intercept)")) |
| 140 |
pred <- predict(bst.Tree, sparse_matrix, outputmargin = TRUE) |
| 141 |
expect_lt(max(abs(rowSums(pred_contr) - pred)), 1e-5) |
| 142 |
# must work with data that has no column names |
| 143 |
X <- sparse_matrix |
| 144 |
colnames(X) <- NULL |
| 145 |
expect_error(pred_contr_ <- predict(bst.Tree, X, predcontrib = TRUE), regexp = NA) |
| 146 |
expect_equal(pred_contr, pred_contr_, check.attributes = FALSE, |
| 147 |
tolerance = float_tolerance) |
| 148 |
|
| 149 |
# gbtree binary classifier (approximate method) |
| 150 |
expect_error(pred_contr <- predict(bst.Tree, sparse_matrix, predcontrib = TRUE, approxcontrib = TRUE), regexp = NA) |
| 151 |
expect_equal(dim(pred_contr), c(nrow(sparse_matrix), ncol(sparse_matrix) + 1)) |
| 152 |
expect_equal(colnames(pred_contr), c(colnames(sparse_matrix), "(Intercept)")) |
| 153 |
pred <- predict(bst.Tree, sparse_matrix, outputmargin = TRUE) |
| 154 |
expect_lt(max(abs(rowSums(pred_contr) - pred)), 1e-5) |
| 155 |
|
| 156 |
# gblinear binary classifier |
| 157 |
expect_error(pred_contr <- predict(bst.GLM, sparse_matrix, predcontrib = TRUE), regexp = NA) |
| 158 |
expect_equal(dim(pred_contr), c(nrow(sparse_matrix), ncol(sparse_matrix) + 1)) |
| 159 |
expect_equal(colnames(pred_contr), c(colnames(sparse_matrix), "(Intercept)")) |
| 160 |
pred <- predict(bst.GLM, sparse_matrix, outputmargin = TRUE) |
| 161 |
expect_lt(max(abs(rowSums(pred_contr) - pred)), 1e-5) |
| 162 |
# manual calculation of linear terms |
| 163 |
coefs <- as.numeric(xgb.dump(bst.GLM)[-c(1, 2, 4)]) |
| 164 |
coefs <- c(coefs[-1], coefs[1]) # intercept must be the last |
| 165 |
pred_contr_manual <- sweep(cbind(sparse_matrix, 1), 2, coefs, FUN = "*") |
| 166 |
expect_equal(as.numeric(pred_contr), as.numeric(pred_contr_manual), |
| 167 |
tolerance = float_tolerance) |
| 168 |
|
| 169 |
# gbtree multiclass |
| 170 |
pred <- predict(mbst.Tree, as.matrix(iris[, -5]), outputmargin = TRUE) |
| 171 |
pred_contr <- predict(mbst.Tree, as.matrix(iris[, -5]), predcontrib = TRUE) |
| 172 |
expect_is(pred_contr, "array") |
| 173 |
expect_length(dim(pred_contr), 3) |
| 174 |
for (g in seq_len(dim(pred_contr)[2])) { |
| 175 |
expect_equal(colnames(pred_contr[, g, ]), c(colnames(iris[, -5]), "(Intercept)")) |
| 176 |
expect_lt(max(abs(rowSums(pred_contr[, g, ]) - pred[, g])), 1e-5) |
| 177 |
} |
| 178 |
|
| 179 |
# gblinear multiclass (set base_score = 0, which is base margin in multiclass) |
| 180 |
pred <- predict(mbst.GLM, as.matrix(iris[, -5]), outputmargin = TRUE) |
| 181 |
pred_contr <- predict(mbst.GLM, as.matrix(iris[, -5]), predcontrib = TRUE) |
| 182 |
expect_length(dim(pred_contr), 3) |
| 183 |
coefs_all <- matrix( |
| 184 |
data = as.numeric(xgb.dump(mbst.GLM)[-c(1, 2, 6)]), |
| 185 |
ncol = 3, |
| 186 |
byrow = TRUE |
| 187 |
) |
| 188 |
for (g in seq_along(dim(pred_contr)[2])) { |
| 189 |
expect_equal(colnames(pred_contr[, g, ]), c(colnames(iris[, -5]), "(Intercept)")) |
| 190 |
expect_lt(max(abs(rowSums(pred_contr[, g, ]) - pred[, g])), float_tolerance) |
| 191 |
# manual calculation of linear terms |
| 192 |
coefs <- c(coefs_all[-1, g], coefs_all[1, g]) # intercept needs to be the last |
| 193 |
pred_contr_manual <- sweep(as.matrix(cbind(iris[, -5], 1)), 2, coefs, FUN = "*") |
| 194 |
expect_equal(as.numeric(pred_contr[, g, ]), as.numeric(pred_contr_manual), |
| 195 |
tolerance = float_tolerance) |
| 196 |
} |
| 197 |
}) |
| 198 |
|
| 199 |
test_that("SHAPs sum to predictions, with or without DART", { |
| 200 |
d <- cbind( |
| 201 |
x1 = rnorm(100), |
| 202 |
x2 = rnorm(100), |
| 203 |
x3 = rnorm(100)) |
| 204 |
y <- d[, "x1"] + d[, "x2"]^2 + |
| 205 |
ifelse(d[, "x3"] > .5, d[, "x3"]^2, 2^d[, "x3"]) + |
| 206 |
rnorm(100) |
| 207 |
nrounds <- 30 |
| 208 |
|
| 209 |
for (booster in list("gbtree", "dart")) { |
| 210 |
fit <- xgb.train( |
| 211 |
params = c( |
| 212 |
list( |
| 213 |
nthread = 2, |
| 214 |
booster = booster, |
| 215 |
objective = "reg:squarederror", |
| 216 |
eval_metric = "rmse"), |
| 217 |
if (booster == "dart") |
| 218 |
list(rate_drop = .01, one_drop = TRUE)), |
| 219 |
data = xgb.DMatrix(d, label = y, nthread = 1), |
| 220 |
nrounds = nrounds) |
| 221 |
|
| 222 |
pr <- function(...) { |
| 223 |
predict(fit, newdata = d, ...) |
| 224 |
} |
| 225 |
pred <- pr() |
| 226 |
shap <- pr(predcontrib = TRUE) |
| 227 |
shapi <- pr(predinteraction = TRUE) |
| 228 |
tol <- 1e-5 |
| 229 |
|
| 230 |
expect_equal(rowSums(shap), pred, tol = tol) |
| 231 |
expect_equal(rowSums(shapi), pred, tol = tol) |
| 232 |
for (i in seq_len(nrow(d))) |
| 233 |
for (f in list(rowSums, colSums)) |
| 234 |
expect_equal(f(shapi[i, , ]), shap[i, ], tol = tol) |
| 235 |
} |
| 236 |
}) |
| 237 |
|
| 238 |
test_that("xgb-attribute functionality", { |
| 239 |
.skip_if_vcd_not_available() |
| 240 |
val <- "my attribute value" |
| 241 |
list.val <- list(my_attr = val, a = 123, b = 'ok') |
| 242 |
list.ch <- list.val[order(names(list.val))] |
| 243 |
list.ch <- lapply(list.ch, as.character) |
| 244 |
# note: iter is 0-index in xgb attributes |
| 245 |
list.default <- list() |
| 246 |
list.ch <- c(list.ch, list.default) |
| 247 |
# proper input: |
| 248 |
expect_error(xgb.attr(bst.Tree, NULL)) |
| 249 |
expect_error(xgb.attr(val, val)) |
| 250 |
# set & get: |
| 251 |
expect_null(xgb.attr(bst.Tree, "asdf")) |
| 252 |
expect_equal(xgb.attributes(bst.Tree), list.default) |
| 253 |
bst.Tree.copy <- xgb.copy.Booster(bst.Tree) |
| 254 |
xgb.attr(bst.Tree.copy, "my_attr") <- val |
| 255 |
expect_equal(xgb.attr(bst.Tree.copy, "my_attr"), val) |
| 256 |
xgb.attributes(bst.Tree.copy) <- list.val |
| 257 |
expect_equal(xgb.attributes(bst.Tree.copy), list.ch) |
| 258 |
# serializing: |
| 259 |
fname <- file.path(tempdir(), "xgb.ubj") |
| 260 |
xgb.save(bst.Tree.copy, fname) |
| 261 |
bst <- xgb.load(fname) |
| 262 |
expect_equal(xgb.attr(bst, "my_attr"), val) |
| 263 |
expect_equal(xgb.attributes(bst), list.ch) |
| 264 |
# deletion: |
| 265 |
xgb.attr(bst, "my_attr") <- NULL |
| 266 |
expect_null(xgb.attr(bst, "my_attr")) |
| 267 |
expect_equal(xgb.attributes(bst), list.ch[c("a", "b")]) |
| 268 |
xgb.attributes(bst) <- list(a = NULL, b = NULL) |
| 269 |
expect_equal(xgb.attributes(bst), list.default) |
| 270 |
xgb.attributes(bst) <- list(niter = NULL) |
| 271 |
expect_equal(xgb.attributes(bst), list()) |
| 272 |
}) |
| 273 |
|
| 274 |
if (grepl('Windows', Sys.info()[['sysname']], fixed = TRUE) || |
| 275 |
grepl('Linux', Sys.info()[['sysname']], fixed = TRUE) || |
| 276 |
grepl('Darwin', Sys.info()[['sysname']], fixed = TRUE)) { |
| 277 |
test_that("xgb-attribute numeric precision", { |
| 278 |
.skip_if_vcd_not_available() |
| 279 |
# check that lossless conversion works with 17 digits |
| 280 |
# numeric -> character -> numeric |
| 281 |
X <- 10^runif(100, -20, 20) |
| 282 |
if (capabilities('long.double')) { |
| 283 |
X2X <- as.numeric(format(X, digits = 17)) |
| 284 |
expect_equal(X, X2X, tolerance = float_tolerance) |
| 285 |
} |
| 286 |
# retrieved attributes to be the same as written |
| 287 |
for (x in X) { |
| 288 |
xgb.attr(bst.Tree, "x") <- x |
| 289 |
expect_equal(as.numeric(xgb.attr(bst.Tree, "x")), x, tolerance = float_tolerance) |
| 290 |
xgb.attributes(bst.Tree) <- list(a = "A", b = x) |
| 291 |
expect_equal(as.numeric(xgb.attr(bst.Tree, "b")), x, tolerance = float_tolerance) |
| 292 |
} |
| 293 |
}) |
| 294 |
} |
| 295 |
|
| 296 |
test_that("xgb.Booster serializing as R object works", { |
| 297 |
.skip_if_vcd_not_available() |
| 298 |
fname_rds <- file.path(tempdir(), "xgb.model.rds") |
| 299 |
saveRDS(bst.Tree, fname_rds) |
| 300 |
bst <- readRDS(fname_rds) |
| 301 |
dtrain <- xgb.DMatrix(sparse_matrix, label = label, nthread = 2) |
| 302 |
expect_equal(predict(bst.Tree, dtrain), predict(bst, dtrain), tolerance = float_tolerance) |
| 303 |
expect_equal(xgb.dump(bst.Tree), xgb.dump(bst)) |
| 304 |
|
| 305 |
fname_bin <- file.path(tempdir(), "xgb.model") |
| 306 |
xgb.save(bst, fname_bin) |
| 307 |
bst <- readRDS(fname_rds) |
| 308 |
expect_equal(predict(bst.Tree, dtrain), predict(bst, dtrain), tolerance = float_tolerance) |
| 309 |
}) |
| 310 |
|
| 311 |
test_that("xgb.model.dt.tree works with and without feature names", { |
| 312 |
.skip_if_vcd_not_available() |
| 313 |
names.dt.trees <- c("Tree", "Node", "ID", "Feature", "Split", "Yes", "No", "Missing", "Gain", "Cover") |
| 314 |
dt.tree <- xgb.model.dt.tree(model = bst.Tree) |
| 315 |
expect_equal(names.dt.trees, names(dt.tree)) |
| 316 |
if (!flag_32bit) |
| 317 |
expect_equal(dim(dt.tree), c(188, 10)) |
| 318 |
expect_output(str(dt.tree), 'Feature.*\\"Age\\"') |
| 319 |
|
| 320 |
# when model contains no feature names: |
| 321 |
dt.tree.x <- xgb.model.dt.tree(model = bst.Tree.unnamed) |
| 322 |
expect_output(str(dt.tree.x), 'Feature.*\\"3\\"') |
| 323 |
expect_equal(dt.tree[, -4, with = FALSE], dt.tree.x[, -4, with = FALSE]) |
| 324 |
|
| 325 |
# using integer node ID instead of character |
| 326 |
dt.tree.int <- xgb.model.dt.tree(model = bst.Tree, use_int_id = TRUE) |
| 327 |
expect_equal(as.integer(data.table::tstrsplit(dt.tree$Yes, '-', fixed = TRUE)[[2]]), dt.tree.int$Yes) |
| 328 |
expect_equal(as.integer(data.table::tstrsplit(dt.tree$No, '-', fixed = TRUE)[[2]]), dt.tree.int$No) |
| 329 |
expect_equal(as.integer(data.table::tstrsplit(dt.tree$Missing, '-', fixed = TRUE)[[2]]), dt.tree.int$Missing) |
| 330 |
}) |
| 331 |
|
| 332 |
test_that("xgb.model.dt.tree throws error for gblinear", { |
| 333 |
.skip_if_vcd_not_available() |
| 334 |
expect_error(xgb.model.dt.tree(model = bst.GLM)) |
| 335 |
}) |
| 336 |
|
| 337 |
test_that("xgb.importance works with and without feature names", { |
| 338 |
.skip_if_vcd_not_available() |
| 339 |
importance.Tree <- xgb.importance(feature_names = feature.names, model = bst.Tree.unnamed) |
| 340 |
if (!flag_32bit) |
| 341 |
expect_equal(dim(importance.Tree), c(7, 4)) |
| 342 |
expect_equal(colnames(importance.Tree), c("Feature", "Gain", "Cover", "Frequency")) |
| 343 |
expect_output(str(importance.Tree), 'Feature.*\\"Age\\"') |
| 344 |
|
| 345 |
importance.Tree.0 <- xgb.importance(model = bst.Tree) |
| 346 |
expect_equal(importance.Tree, importance.Tree.0, tolerance = float_tolerance) |
| 347 |
|
| 348 |
# when model contains no feature names: |
| 349 |
importance.Tree.x <- xgb.importance(model = bst.Tree.unnamed) |
| 350 |
expect_equal(importance.Tree[, -1, with = FALSE], importance.Tree.x[, -1, with = FALSE], |
| 351 |
tolerance = float_tolerance) |
| 352 |
|
| 353 |
imp2plot <- xgb.plot.importance(importance_matrix = importance.Tree) |
| 354 |
expect_equal(colnames(imp2plot), c("Feature", "Gain", "Cover", "Frequency", "Importance")) |
| 355 |
xgb.ggplot.importance(importance_matrix = importance.Tree) |
| 356 |
|
| 357 |
# for multiclass |
| 358 |
imp.Tree <- xgb.importance(model = mbst.Tree) |
| 359 |
expect_equal(dim(imp.Tree), c(4, 4)) |
| 360 |
|
| 361 |
trees <- seq(from = 1, by = 2, length.out = 2) |
| 362 |
importance <- xgb.importance(feature_names = feature.names, model = bst.Tree, trees = trees) |
| 363 |
|
| 364 |
importance_from_dump <- function() { |
| 365 |
imp <- xgb.model.dt.tree( |
| 366 |
model = bst.Tree, |
| 367 |
trees = trees |
| 368 |
)[ |
| 369 |
Feature != "Leaf", .( |
| 370 |
Gain = sum(Gain), |
| 371 |
Cover = sum(Cover), |
| 372 |
Frequency = .N |
| 373 |
), |
| 374 |
by = Feature |
| 375 |
][ |
| 376 |
, `:=`( |
| 377 |
Gain = Gain / sum(Gain), |
| 378 |
Cover = Cover / sum(Cover), |
| 379 |
Frequency = Frequency / sum(Frequency) |
| 380 |
) |
| 381 |
][ |
| 382 |
order(Gain, decreasing = TRUE) |
| 383 |
] |
| 384 |
imp |
| 385 |
} |
| 386 |
expect_equal(importance_from_dump(), importance, tolerance = 1e-6) |
| 387 |
|
| 388 |
## decision stump |
| 389 |
m <- xgb.train( |
| 390 |
data = xgb.DMatrix(as.matrix(data.frame(x = c(0, 1))), label = c(1, 2), nthread = 1), |
| 391 |
nrounds = 1, |
| 392 |
params = xgb.params( |
| 393 |
base_score = 0.5, |
| 394 |
nthread = 2 |
| 395 |
) |
| 396 |
) |
| 397 |
df <- xgb.model.dt.tree(model = m) |
| 398 |
expect_equal(df$Feature, "Leaf") |
| 399 |
expect_equal(df$Cover, 2) |
| 400 |
}) |
| 401 |
|
| 402 |
test_that("xgb.importance works with GLM model", { |
| 403 |
.skip_if_vcd_not_available() |
| 404 |
importance.GLM <- xgb.importance(feature_names = feature.names, model = bst.GLM) |
| 405 |
expect_equal(dim(importance.GLM), c(10, 2)) |
| 406 |
expect_equal(colnames(importance.GLM), c("Feature", "Weight")) |
| 407 |
xgb.importance(model = bst.GLM) |
| 408 |
imp2plot <- xgb.plot.importance(importance.GLM) |
| 409 |
expect_equal(colnames(imp2plot), c("Feature", "Weight", "Importance")) |
| 410 |
xgb.ggplot.importance(importance.GLM) |
| 411 |
|
| 412 |
# check that the input is not modified in-place |
| 413 |
expect_false("Importance" %in% names(importance.GLM)) |
| 414 |
|
| 415 |
# for multiclass |
| 416 |
imp.GLM <- xgb.importance(model = mbst.GLM) |
| 417 |
expect_equal(dim(imp.GLM), c(12, 3)) |
| 418 |
expect_equal(imp.GLM$Class, rep(0:2, each = 4)) |
| 419 |
}) |
| 420 |
|
| 421 |
test_that("xgb.model.dt.tree and xgb.importance work with a single split model", { |
| 422 |
.skip_if_vcd_not_available() |
| 423 |
bst1 <- xgb.train( |
| 424 |
data = xgb.DMatrix(sparse_matrix, label = label, nthread = 1), |
| 425 |
nrounds = 1, verbose = 0, |
| 426 |
params = xgb.params( |
| 427 |
max_depth = 1, |
| 428 |
learning_rate = 1, |
| 429 |
nthread = 2, |
| 430 |
objective = "binary:logistic" |
| 431 |
) |
| 432 |
) |
| 433 |
expect_error(dt <- xgb.model.dt.tree(model = bst1), regexp = NA) # no error |
| 434 |
expect_equal(nrow(dt), 3) |
| 435 |
expect_error(imp <- xgb.importance(model = bst1), regexp = NA) # no error |
| 436 |
expect_equal(nrow(imp), 1) |
| 437 |
expect_equal(imp$Gain, 1) |
| 438 |
}) |
| 439 |
|
| 440 |
test_that("xgb.plot.importance de-duplicates features", { |
| 441 |
importances <- data.table( |
| 442 |
Feature = c("col1", "col2", "col2"), |
| 443 |
Gain = c(0.4, 0.3, 0.3) |
| 444 |
) |
| 445 |
imp2plot <- xgb.plot.importance(importances) |
| 446 |
expect_equal(nrow(imp2plot), 2L) |
| 447 |
expect_equal(imp2plot$Feature, c("col2", "col1")) |
| 448 |
}) |
| 449 |
|
| 450 |
test_that("xgb.plot.tree works with and without feature names", { |
| 451 |
.skip_if_vcd_not_available() |
| 452 |
expect_silent(xgb.plot.tree(model = bst.Tree.unnamed)) |
| 453 |
expect_silent(xgb.plot.tree(model = bst.Tree)) |
| 454 |
|
| 455 |
## Categorical |
| 456 |
y <- rnorm(100) |
| 457 |
x <- sample(3, size = 100 * 3, replace = TRUE) |> matrix(nrow = 100) |
| 458 |
x <- x - 1 |
| 459 |
dm <- xgb.DMatrix(data = x, label = y, nthread = 1) |
| 460 |
setinfo(dm, "feature_type", c("c", "c", "c")) |
| 461 |
model <- xgb.train( |
| 462 |
data = dm, |
| 463 |
params = list(tree_method = "hist"), |
| 464 |
nrounds = 2 |
| 465 |
) |
| 466 |
expect_silent(xgb.plot.tree(model = model)) |
| 467 |
}) |
| 468 |
|
| 469 |
test_that("xgb.plot.multi.trees works with and without feature names", { |
| 470 |
.skip_if_vcd_not_available() |
| 471 |
xgb.plot.multi.trees(model = bst.Tree.unnamed, features_keep = 3) |
| 472 |
xgb.plot.multi.trees(model = bst.Tree, features_keep = 3) |
| 473 |
expect_true(TRUE) |
| 474 |
}) |
| 475 |
|
| 476 |
test_that("xgb.plot.deepness works", { |
| 477 |
.skip_if_vcd_not_available() |
| 478 |
d2p <- xgb.plot.deepness(model = bst.Tree) |
| 479 |
expect_equal(colnames(d2p), c("ID", "Tree", "Depth", "Cover", "Weight")) |
| 480 |
xgb.plot.deepness(model = bst.Tree, which = "med.depth") |
| 481 |
xgb.ggplot.deepness(model = bst.Tree) |
| 482 |
}) |
| 483 |
|
| 484 |
test_that("xgb.shap.data works when top_n is provided", { |
| 485 |
.skip_if_vcd_not_available() |
| 486 |
data_list <- xgb.shap.data(data = sparse_matrix, model = bst.Tree, top_n = 2) |
| 487 |
expect_equal(names(data_list), c("data", "shap_contrib")) |
| 488 |
expect_equal(NCOL(data_list$data), 2) |
| 489 |
expect_equal(NCOL(data_list$shap_contrib), 2) |
| 490 |
expect_equal(NROW(data_list$data), NROW(data_list$shap_contrib)) |
| 491 |
expect_gt(length(colnames(data_list$data)), 0) |
| 492 |
expect_gt(length(colnames(data_list$shap_contrib)), 0) |
| 493 |
|
| 494 |
# for multiclass without target class provided |
| 495 |
data_list <- xgb.shap.data(data = as.matrix(iris[, -5]), model = mbst.Tree, top_n = 2) |
| 496 |
expect_equal(dim(data_list$shap_contrib), c(nrow(iris), 2)) |
| 497 |
# for multiclass with target class provided |
| 498 |
data_list <- xgb.shap.data(data = as.matrix(iris[, -5]), model = mbst.Tree, top_n = 2, target_class = 0) |
| 499 |
expect_equal(dim(data_list$shap_contrib), c(nrow(iris), 2)) |
| 500 |
}) |
| 501 |
|
| 502 |
test_that("xgb.shap.data works with subsampling", { |
| 503 |
.skip_if_vcd_not_available() |
| 504 |
data_list <- xgb.shap.data(data = sparse_matrix, model = bst.Tree, top_n = 2, subsample = 0.8) |
| 505 |
expect_equal(NROW(data_list$data), as.integer(0.8 * nrow(sparse_matrix))) |
| 506 |
expect_equal(NROW(data_list$data), NROW(data_list$shap_contrib)) |
| 507 |
}) |
| 508 |
|
| 509 |
test_that("xgb.shap.data works with data frames", { |
| 510 |
data(mtcars) |
| 511 |
df <- mtcars |
| 512 |
df$cyl <- factor(df$cyl) |
| 513 |
x <- df[, -1] |
| 514 |
y <- df$mpg |
| 515 |
dm <- xgb.DMatrix(x, label = y, nthread = 1L) |
| 516 |
model <- xgb.train( |
| 517 |
data = dm, |
| 518 |
params = list( |
| 519 |
max_depth = 2, |
| 520 |
nthread = 1 |
| 521 |
), |
| 522 |
nrounds = 2 |
| 523 |
) |
| 524 |
data_list <- xgb.shap.data(data = df[, -1], model = model, top_n = 2, subsample = 0.8) |
| 525 |
expect_equal(NROW(data_list$data), as.integer(0.8 * nrow(df))) |
| 526 |
expect_equal(NROW(data_list$data), NROW(data_list$shap_contrib)) |
| 527 |
}) |
| 528 |
|
| 529 |
test_that("prepare.ggplot.shap.data works", { |
| 530 |
.skip_if_vcd_not_available() |
| 531 |
data_list <- xgb.shap.data(data = sparse_matrix, model = bst.Tree, top_n = 2) |
| 532 |
plot_data <- prepare.ggplot.shap.data(data_list, normalize = TRUE) |
| 533 |
expect_s3_class(plot_data, "data.frame") |
| 534 |
expect_equal(names(plot_data), c("id", "feature", "feature_value", "shap_value")) |
| 535 |
expect_s3_class(plot_data$feature, "factor") |
| 536 |
# Each observation should have 1 row for each feature |
| 537 |
expect_equal(nrow(plot_data), nrow(sparse_matrix) * 2) |
| 538 |
}) |
| 539 |
|
| 540 |
test_that("xgb.plot.shap works", { |
| 541 |
.skip_if_vcd_not_available() |
| 542 |
sh <- xgb.plot.shap(data = sparse_matrix, model = bst.Tree, top_n = 2, col = 4) |
| 543 |
expect_equal(names(sh), c("data", "shap_contrib")) |
| 544 |
}) |
| 545 |
|
| 546 |
test_that("xgb.plot.shap.summary works", { |
| 547 |
.skip_if_vcd_not_available() |
| 548 |
expect_silent(xgb.plot.shap.summary(data = sparse_matrix, model = bst.Tree, top_n = 2)) |
| 549 |
expect_silent(xgb.ggplot.shap.summary(data = sparse_matrix, model = bst.Tree, top_n = 2)) |
| 550 |
}) |
| 551 |
|
| 552 |
test_that("xgb.plot.shap.summary ignores categorical features", { |
| 553 |
.skip_if_vcd_not_available() |
| 554 |
data(mtcars) |
| 555 |
df <- mtcars |
| 556 |
df$cyl <- factor(df$cyl) |
| 557 |
levels(df$cyl) <- c("a", "b", "c") |
| 558 |
x <- df[, -1] |
| 559 |
y <- df$mpg |
| 560 |
dm <- xgb.DMatrix(x, label = y, nthread = 1L) |
| 561 |
model <- xgb.train( |
| 562 |
data = dm, |
| 563 |
params = list( |
| 564 |
max_depth = 2, |
| 565 |
nthread = 1 |
| 566 |
), |
| 567 |
nrounds = 2 |
| 568 |
) |
| 569 |
expect_warning({ |
| 570 |
xgb.ggplot.shap.summary(data = x, model = model, top_n = 2) |
| 571 |
}) |
| 572 |
|
| 573 |
x_num <- mtcars[, -1] |
| 574 |
x_num$gear <- as.numeric(x_num$gear) - 1 |
| 575 |
x_num <- as.matrix(x_num) |
| 576 |
dm <- xgb.DMatrix(x_num, label = y, feature_types = c(rep("q", 8), "c", "q"), nthread = 1L) |
| 577 |
model <- xgb.train( |
| 578 |
data = dm, |
| 579 |
params = list( |
| 580 |
max_depth = 2, |
| 581 |
nthread = 1 |
| 582 |
), |
| 583 |
nrounds = 2 |
| 584 |
) |
| 585 |
expect_warning({ |
| 586 |
xgb.ggplot.shap.summary(data = x_num, model = model, top_n = 2) |
| 587 |
}) |
| 588 |
}) |
| 589 |
|
| 590 |
test_that("check.deprecation works", { |
| 591 |
data(mtcars) |
| 592 |
dm <- xgb.DMatrix(mtcars[, -1L], label = mtcars$mpg, nthread = 1) |
| 593 |
params <- xgb.params(nthread = 1, max_depth = 2, eval_metric = "rmse") |
| 594 |
args_train <- list( |
| 595 |
data = dm, |
| 596 |
params = params, |
| 597 |
nrounds = 10, |
| 598 |
verbose = 0 |
| 599 |
) |
| 600 |
|
| 601 |
# with exact name |
| 602 |
options("xgboost.strict_mode" = TRUE) |
| 603 |
expect_error({ |
| 604 |
model <- xgb.train( |
| 605 |
data = dm, |
| 606 |
params = params, |
| 607 |
nrounds = 10, |
| 608 |
watchlist = list(tr = dm), |
| 609 |
verbose = 0 |
| 610 |
) |
| 611 |
}, regexp = "watchlist") |
| 612 |
options("xgboost.strict_mode" = FALSE) |
| 613 |
expect_warning({ |
| 614 |
model <- xgb.train( |
| 615 |
data = dm, |
| 616 |
params = params, |
| 617 |
nrounds = 10, |
| 618 |
watchlist = list(tr = dm), |
| 619 |
verbose = 0 |
| 620 |
) |
| 621 |
}, regexp = "watchlist") |
| 622 |
expect_true(hasName(attributes(model), "evaluation_log")) |
| 623 |
expect_equal(names(attributes(model)$evaluation_log), c("iter", "tr_rmse")) |
| 624 |
|
| 625 |
# with partial name match |
| 626 |
expect_warning({ |
| 627 |
model <- xgb.train( |
| 628 |
data = dm, |
| 629 |
params = params, |
| 630 |
nrounds = 10, |
| 631 |
watchlis = list(train = dm), |
| 632 |
verbose = 0 |
| 633 |
) |
| 634 |
}, regexp = "watchlist") |
| 635 |
expect_true(hasName(attributes(model), "evaluation_log")) |
| 636 |
expect_equal(names(attributes(model)$evaluation_log), c("iter", "train_rmse")) |
| 637 |
|
| 638 |
# error/warning is thrown if argument cannot be matched |
| 639 |
options("xgboost.strict_mode" = TRUE) |
| 640 |
expect_error({ |
| 641 |
model <- xgb.train( |
| 642 |
data = dm, |
| 643 |
params = params, |
| 644 |
nrounds = 10, |
| 645 |
watchlistt = list(train = dm), |
| 646 |
verbose = 0 |
| 647 |
) |
| 648 |
}, regexp = "unrecognized") |
| 649 |
options("xgboost.strict_mode" = FALSE) |
| 650 |
expect_warning({ |
| 651 |
model <- xgb.train( |
| 652 |
data = dm, |
| 653 |
params = params, |
| 654 |
nrounds = 10, |
| 655 |
watchlistt = list(train = dm), |
| 656 |
verbose = 0 |
| 657 |
) |
| 658 |
}, regexp = "unrecognized") |
| 659 |
|
| 660 |
# error should suggest to put under 'params' if it goes there |
| 661 |
options("xgboost.strict_mode" = TRUE) |
| 662 |
expect_error({ |
| 663 |
model <- xgb.train( |
| 664 |
data = dm, |
| 665 |
nthread = 1, max_depth = 2, eval_metric = "rmse", |
| 666 |
nrounds = 10, |
| 667 |
evals = list(train = dm), |
| 668 |
verbose = 0 |
| 669 |
) |
| 670 |
}, regexp = "should be passed as a list to argument 'params'") |
| 671 |
options("xgboost.strict_mode" = FALSE) |
| 672 |
expect_warning({ |
| 673 |
model <- xgb.train( |
| 674 |
data = dm, |
| 675 |
nthread = 1, max_depth = 2, eval_metric = "mae", |
| 676 |
nrounds = 10, |
| 677 |
evals = list(train = dm), |
| 678 |
verbose = 0 |
| 679 |
) |
| 680 |
}, regexp = "should be passed as a list to argument 'params'") |
| 681 |
expect_true(hasName(attributes(model), "evaluation_log")) |
| 682 |
expect_equal(names(attributes(model)$evaluation_log), c("iter", "train_mae")) |
| 683 |
|
| 684 |
# can take more than one deprecated parameter |
| 685 |
expect_warning({ |
| 686 |
model <- xgb.train( |
| 687 |
training.data = dm, |
| 688 |
params = params, |
| 689 |
nrounds = 10, |
| 690 |
watchlis = list(tr = dm), |
| 691 |
verbose = 0 |
| 692 |
) |
| 693 |
}, regexp = "training.data") |
| 694 |
expect_true(hasName(attributes(model), "evaluation_log")) |
| 695 |
expect_equal(names(attributes(model)$evaluation_log), c("iter", "tr_rmse")) |
| 696 |
}) |
| 697 |
|
| 698 |
test_that('convert.labels works', { |
| 699 |
y <- c(0, 1, 0, 0, 1) |
| 700 |
for (objective in c('binary:logistic', 'binary:logitraw', 'binary:hinge')) { |
| 701 |
res <- xgboost:::convert.labels(y, objective_name = objective) |
| 702 |
expect_s3_class(res, 'factor') |
| 703 |
expect_equal(res, factor(res)) |
| 704 |
} |
| 705 |
y <- c(0, 1, 3, 2, 1, 4) |
| 706 |
for (objective in c('multi:softmax', 'multi:softprob', 'rank:pairwise', 'rank:ndcg', |
| 707 |
'rank:map')) { |
| 708 |
res <- xgboost:::convert.labels(y, objective_name = objective) |
| 709 |
expect_s3_class(res, 'factor') |
| 710 |
expect_equal(res, factor(res)) |
| 711 |
} |
| 712 |
y <- c(1.2, 3.0, -1.0, 10.0) |
| 713 |
for (objective in c('reg:squarederror', 'reg:squaredlogerror', 'reg:logistic', |
| 714 |
'reg:pseudohubererror', 'count:poisson', 'survival:cox', 'survival:aft', |
| 715 |
'reg:gamma', 'reg:tweedie')) { |
| 716 |
res <- xgboost:::convert.labels(y, objective_name = objective) |
| 717 |
expect_equal(class(res), 'numeric') |
| 718 |
} |
| 719 |
}) |
| 720 |
|
| 721 |
test_that("validate.features works as expected", { |
| 722 |
data(mtcars) |
| 723 |
y <- mtcars$mpg |
| 724 |
x <- as.matrix(mtcars[, -1]) |
| 725 |
dm <- xgb.DMatrix(x, label = y, nthread = 1) |
| 726 |
model <- xgb.train( |
| 727 |
params = list(nthread = 1), |
| 728 |
data = dm, |
| 729 |
nrounds = 3 |
| 730 |
) |
| 731 |
|
| 732 |
# result is output as-is when needed |
| 733 |
res <- validate.features(model, x) |
| 734 |
expect_equal(res, x) |
| 735 |
res <- validate.features(model, dm) |
| 736 |
expect_identical(res, dm) |
| 737 |
res <- validate.features(model, as(x[1, ], "dsparseVector")) |
| 738 |
expect_equal(as.numeric(res), unname(x[1, ])) |
| 739 |
res <- validate.features(model, "file.txt") |
| 740 |
expect_equal(res, "file.txt") |
| 741 |
|
| 742 |
# columns are reordered |
| 743 |
res <- validate.features(model, mtcars[, rev(names(mtcars))]) |
| 744 |
expect_equal(names(res), colnames(x)) |
| 745 |
expect_equal(as.matrix(res), x) |
| 746 |
res <- validate.features(model, as.matrix(mtcars[, rev(names(mtcars))])) |
| 747 |
expect_equal(colnames(res), colnames(x)) |
| 748 |
expect_equal(res, x) |
| 749 |
res <- validate.features(model, mtcars[1, rev(names(mtcars)), drop = FALSE]) |
| 750 |
expect_equal(names(res), colnames(x)) |
| 751 |
expect_equal(unname(as.matrix(res)), unname(x[1, , drop = FALSE])) |
| 752 |
res <- validate.features(model, as.data.table(mtcars[, rev(names(mtcars))])) |
| 753 |
expect_equal(names(res), colnames(x)) |
| 754 |
expect_equal(unname(as.matrix(res)), unname(x)) |
| 755 |
|
| 756 |
# error when columns are missing |
| 757 |
expect_error({ |
| 758 |
validate.features(model, mtcars[, 1:3]) |
| 759 |
}) |
| 760 |
expect_error({ |
| 761 |
validate.features(model, as.matrix(mtcars[, 1:ncol(x)])) # nolint |
| 762 |
}) |
| 763 |
expect_error({ |
| 764 |
validate.features(model, xgb.DMatrix(mtcars[, 1:3], nthread = 1)) |
| 765 |
}) |
| 766 |
expect_error({ |
| 767 |
validate.features(model, as(x[, 1:3], "CsparseMatrix")) |
| 768 |
}) |
| 769 |
|
| 770 |
# error when it cannot reorder or subset |
| 771 |
expect_error({ |
| 772 |
validate.features(model, xgb.DMatrix(mtcars, nthread = 1)) |
| 773 |
}, "Feature names") |
| 774 |
expect_error({ |
| 775 |
validate.features(model, xgb.DMatrix(x[, rev(colnames(x))], nthread = 1)) |
| 776 |
}, "Feature names") |
| 777 |
|
| 778 |
# no error about types if the booster doesn't have types |
| 779 |
expect_error({ |
| 780 |
validate.features(model, xgb.DMatrix(x, feature_types = c(rep("q", 5), rep("c", 5)), nthread = 1)) |
| 781 |
}, NA) |
| 782 |
tmp <- mtcars |
| 783 |
tmp[["vs"]] <- factor(tmp[["vs"]]) |
| 784 |
expect_error({ |
| 785 |
validate.features(model, tmp) |
| 786 |
}, NA) |
| 787 |
|
| 788 |
# error when types do not match |
| 789 |
setinfo(model, "feature_type", rep("q", 10)) |
| 790 |
expect_error({ |
| 791 |
validate.features(model, xgb.DMatrix(x, feature_types = c(rep("q", 5), rep("c", 5)), nthread = 1)) |
| 792 |
}, "Feature types") |
| 793 |
tmp <- mtcars |
| 794 |
tmp[["vs"]] <- factor(tmp[["vs"]]) |
| 795 |
expect_error({ |
| 796 |
validate.features(model, tmp) |
| 797 |
}, "Feature types") |
| 798 |
}) |
| 799 |
|
| 800 |
test_that("Parameters constructor works as expected", { |
| 801 |
empty_list <- list() |
| 802 |
names(empty_list) <- character() |
| 803 |
|
| 804 |
params <- xgb.params() |
| 805 |
expect_equal(params, empty_list) |
| 806 |
|
| 807 |
params <- xgb.params(max_depth = 2) |
| 808 |
expect_equal(params, list(max_depth = 2)) |
| 809 |
|
| 810 |
params <- xgb.params(max_depth = NULL) |
| 811 |
expect_equal(params, empty_list) |
| 812 |
|
| 813 |
max_depth <- 3 |
| 814 |
params <- xgb.params(max_depth = max_depth) |
| 815 |
expect_equal(params, list(max_depth = 3)) |
| 816 |
|
| 817 |
four <- 4L |
| 818 |
params <- xgb.params(max_depth = four) |
| 819 |
expect_equal(params, list(max_depth = 4L)) |
| 820 |
|
| 821 |
params <- xgb.params(objective = "binary:logistic", nthread = 10) |
| 822 |
expect_equal(params, list(objective = "binary:logistic", nthread = 10)) |
| 823 |
|
| 824 |
expect_error({ |
| 825 |
xgb.params(max_xgboost = 10) |
| 826 |
}) |
| 827 |
expect_error({ |
| 828 |
xgb.params(max_depth = 2, max_depth = 3) |
| 829 |
}) |
| 830 |
}) |