Debian Codegraph @

tests/testthat/test_interactions.R

raw
1 context('Test prediction of feature interactions')
2
3 set.seed(123)
4 n_threads <- 2
5
6 test_that("predict feature interactions works", {
7 # simulate some binary data and a linear outcome with an interaction term
8 N <- 1000
9 P <- 5
10 X <- matrix(rbinom(N * P, 1, 0.5), ncol = P, dimnames = list(NULL, letters[1:P]))
11 # center the data (as contributions are computed WRT feature means)
12 X <- scale(X, scale = FALSE)
13
14 # outcome without any interactions, without any noise:
15 f <- function(x) 2 * x[, 1] - 3 * x[, 2]
16 # outcome with interactions, without noise:
17 f_int <- function(x) f(x) + 2 * x[, 2] * x[, 3]
18 # outcome with interactions, with noise:
19 #f_int_noise <- function(x) f_int(x) + rnorm(N, 0, 0.3)
20
21 y <- f_int(X)
22
23 dm <- xgb.DMatrix(X, label = y, nthread = n_threads)
24 param <- xgb.params(
25 learning_rate = 0.1,
26 max_depth = 4,
27 base_score = mean(y),
28 reg_lambda = 0,
29 nthread = n_threads
30 )
31 b <- xgb.train(param, dm, 100)
32
33 pred <- predict(b, dm, outputmargin = TRUE)
34
35 # SHAP contributions:
36 cont <- predict(b, dm, predcontrib = TRUE)
37 expect_equal(dim(cont), c(N, P + 1))
38 # make sure for each row they add up to marginal predictions
39 expect_lt(max(abs(rowSums(cont) - pred)), 0.001)
40 # Hand-construct the 'ground truth' feature contributions:
41 gt_cont <- cbind(
42 2. * X[, 1],
43 -3. * X[, 2] + 1. * X[, 2] * X[, 3], # attribute a HALF of the interaction term to feature #2
44 1. * X[, 2] * X[, 3] # and another HALF of the interaction term to feature #3
45 )
46 gt_cont <- cbind(gt_cont, matrix(0, nrow = N, ncol = P + 1 - 3))
47 # These should be relatively close:
48 expect_lt(max(abs(cont - gt_cont)), 0.05)
49
50
51 # SHAP interaction contributions:
52 intr <- predict(b, dm, predinteraction = TRUE)
53 expect_equal(dim(intr), c(N, P + 1, P + 1))
54 # check assigned colnames
55 cn <- c(letters[1:P], "(Intercept)")
56 expect_equal(dimnames(intr), list(NULL, cn, cn))
57
58 # check the symmetry
59 expect_lt(max(abs(aperm(intr, c(1, 3, 2)) - intr)), 0.00001)
60
61 # sums WRT columns must be close to feature contributions
62 expect_lt(max(abs(apply(intr, c(1, 2), sum) - cont)), 0.00001)
63
64 # diagonal terms for features 3,4,5 must be close to zero
65 expect_lt(Reduce(max, sapply(3:P, function(i) max(abs(intr[, i, i])))), 0.05)
66
67 # Intercept must have no interactions
68 expect_lt(max(abs(intr[, 1:P, P + 1])), 0.00001)
69
70 # interactions other than 2 x 3 must be close to zero
71 intr23 <- intr
72 intr23[, 2, 3] <- 0
73 expect_lt(
74 Reduce(max, sapply(1:P, function(i) max(abs(intr23[, i, (i + 1):(P + 1)])))),
75 0.05
76 )
77
78 # Construct the 'ground truth' contributions of interactions directly from the linear terms:
79 gt_intr <- array(0, c(N, P + 1, P + 1))
80 gt_intr[, 2, 3] <- 1. * X[, 2] * X[, 3] # attribute a HALF of the interaction term to each symmetric element
81 gt_intr[, 3, 2] <- gt_intr[, 2, 3]
82 # merge-in the diagonal based on 'ground truth' feature contributions
83 intr_diag <- gt_cont - apply(gt_intr, c(1, 2), sum)
84 for (j in seq_len(P)) {
85 gt_intr[, j, j] <- intr_diag[, j]
86 }
87 # These should be relatively close:
88 expect_lt(max(abs(intr - gt_intr)), 0.1)
89 })
90
91 test_that("SHAP contribution values are not NAN", {
92 d <- data.frame(
93 x1 = c(-2.3, 1.4, 5.9, 2, 2.5, 0.3, -3.6, -0.2, 0.5, -2.8, -4.6, 3.3, -1.2,
94 -1.1, -2.3, 0.4, -1.5, -0.2, -1, 3.7),
95 x2 = c(291.179171, 269.198331, 289.942097, 283.191669, 269.673332,
96 294.158346, 287.255835, 291.530838, 285.899586, 269.290833,
97 268.649586, 291.530841, 280.074593, 269.484168, 293.94042,
98 294.327506, 296.20709, 295.441669, 283.16792, 270.227085),
99 y = c(9, 15, 5.7, 9.2, 22.4, 5, 9, 3.2, 7.2, 13.1, 7.8, 16.9, 6.5, 22.1,
100 5.3, 10.4, 11.1, 13.9, 11, 20.5),
101 fold = c(2, 2, 2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2))
102
103 ivs <- c("x1", "x2")
104
105 fit <- xgb.train(
106 verbose = 0,
107 params = list(
108 objective = "reg:squarederror",
109 eval_metric = "rmse",
110 nthread = n_threads
111 ),
112 data = xgb.DMatrix(as.matrix(subset(d, fold == 2)[, ivs]), label = subset(d, fold == 2)$y, nthread = 1),
113 nrounds = 3
114 )
115
116 shaps <- as.data.frame(predict(fit,
117 newdata = as.matrix(subset(d, fold == 1)[, ivs]),
118 predcontrib = TRUE))
119 result <- cbind(shaps, sum = rowSums(shaps), pred = predict(fit,
120 newdata = as.matrix(subset(d, fold == 1)[, ivs])))
121
122 expect_true(identical(TRUE, all.equal(result$sum, result$pred, tol = 1e-6)))
123 })
124
125
126 test_that("multiclass feature interactions work", {
127 dm <- xgb.DMatrix(
128 as.matrix(iris[, -5]), label = as.numeric(iris$Species) - 1, nthread = n_threads
129 )
130 param <- xgb.params(
131 learning_rate = 0.1,
132 max_depth = 4,
133 objective = 'multi:softprob',
134 num_class = 3,
135 nthread = n_threads
136 )
137 b <- xgb.train(param, dm, 40)
138 pred <- predict(b, dm, outputmargin = TRUE)
139
140 # SHAP contributions:
141 cont <- predict(b, dm, predcontrib = TRUE)
142 expect_length(dim(cont), 3)
143
144 # make sure for each row they add up to marginal predictions
145 expect_lt(max(abs(apply(cont, c(1, 2), sum) - pred)), 0.001)
146
147 # SHAP interaction contributions:
148 intr <- predict(b, dm, predinteraction = TRUE)
149 expect_length(dim(intr), 4)
150
151 # check the symmetry
152 expect_lt(max(abs(aperm(intr, c(1, 2, 4, 3)) - intr)), 0.00001)
153 # sums WRT columns must be close to feature contributions
154 expect_lt(max(abs(apply(intr, c(1, 2, 3), sum) - cont)), 0.00001)
155 })
156
157
158 test_that("SHAP single sample works", {
159 train <- agaricus.train
160 test <- agaricus.test
161 booster <- xgb.train(
162 data = xgb.DMatrix(train$data, label = train$label, nthread = 1),
163 nrounds = 4,
164 params = xgb.params(
165 max_depth = 2,
166 objective = "binary:logistic",
167 nthread = n_threads
168 )
169 )
170
171 predt <- predict(
172 booster,
173 newdata = train$data[1, , drop = FALSE], predcontrib = TRUE
174 )
175 expect_equal(dim(predt), c(1, dim(train$data)[2] + 1))
176
177 predt <- predict(
178 booster,
179 newdata = train$data[1, , drop = FALSE], predinteraction = TRUE
180 )
181 expect_equal(dim(predt), c(1, dim(train$data)[2] + 1, dim(train$data)[2] + 1))
182 })