| 1 |
require(xgboost) |
| 2 |
|
| 3 |
context("interaction constraints") |
| 4 |
|
| 5 |
n_threads <- 2 |
| 6 |
|
| 7 |
set.seed(1024) |
| 8 |
x1 <- rnorm(1000, 1) |
| 9 |
x2 <- rnorm(1000, 1) |
| 10 |
x3 <- sample(c(1, 2, 3), size = 1000, replace = TRUE) |
| 11 |
y <- x1 + x2 + x3 + x1 * x2 * x3 + rnorm(1000, 0.001) + 3 * sin(x1) |
| 12 |
train <- matrix(c(x1, x2, x3), ncol = 3) |
| 13 |
|
| 14 |
test_that("interaction constraints for regression", { |
| 15 |
# Fit a model that only allows interaction between x1 and x2 |
| 16 |
bst <- xgb.train( |
| 17 |
data = xgb.DMatrix(train, label = y, nthread = 1), |
| 18 |
nrounds = 100, verbose = 0, |
| 19 |
params = xgb.params( |
| 20 |
max_depth = 3, |
| 21 |
learning_rate = 0.1, |
| 22 |
nthread = 2, |
| 23 |
interaction_constraints = list(c(0, 1)) |
| 24 |
) |
| 25 |
) |
| 26 |
|
| 27 |
# Set all observations to have the same x3 values then increment |
| 28 |
# by the same amount |
| 29 |
preds <- lapply(c(1, 2, 3), function(x) { |
| 30 |
tmat <- matrix(c(x1, x2, rep(x, 1000)), ncol = 3) |
| 31 |
return(predict(bst, tmat)) |
| 32 |
}) |
| 33 |
|
| 34 |
# Check incrementing x3 has the same effect on all observations |
| 35 |
# since x3 is constrained to be independent of x1 and x2 |
| 36 |
# and all observations start off from the same x3 value |
| 37 |
diff1 <- preds[[2]] - preds[[1]] |
| 38 |
test1 <- all(abs(diff1 - diff1[1]) < 1e-4) |
| 39 |
|
| 40 |
diff2 <- preds[[3]] - preds[[2]] |
| 41 |
test2 <- all(abs(diff2 - diff2[1]) < 1e-4) |
| 42 |
|
| 43 |
expect_true({ |
| 44 |
test1 & test2 |
| 45 |
}, "Interaction Contraint Satisfied") |
| 46 |
}) |
| 47 |
|
| 48 |
test_that("interaction constraints scientific representation", { |
| 49 |
rows <- 10 |
| 50 |
## When number exceeds 1e5, R paste function uses scientific representation. |
| 51 |
## See: https://github.com/dmlc/xgboost/issues/5179 |
| 52 |
cols <- 1e5 + 10 |
| 53 |
|
| 54 |
d <- matrix(rexp(rows, rate = .1), nrow = rows, ncol = cols) |
| 55 |
y <- rnorm(rows) |
| 56 |
|
| 57 |
dtrain <- xgb.DMatrix(data = d, label = y, nthread = n_threads) |
| 58 |
inc <- list(c(seq.int(from = 0, to = cols, by = 1))) |
| 59 |
|
| 60 |
with_inc <- xgb.train( |
| 61 |
data = dtrain, |
| 62 |
nrounds = 10, |
| 63 |
params = xgb.params( |
| 64 |
tree_method = 'hist', |
| 65 |
interaction_constraints = inc, |
| 66 |
nthread = n_threads |
| 67 |
) |
| 68 |
) |
| 69 |
without_inc <- xgb.train( |
| 70 |
data = dtrain, |
| 71 |
nrounds = 10, |
| 72 |
params = xgb.params( |
| 73 |
tree_method = 'hist', |
| 74 |
nthread = n_threads |
| 75 |
) |
| 76 |
) |
| 77 |
expect_equal(xgb.save.raw(with_inc), xgb.save.raw(without_inc)) |
| 78 |
}) |