|
| 1 | +# Model with non-linearities and interactions |
| 2 | +y <- iris$Sepal.Length |
| 3 | +Y <- as.matrix(iris[, c("Sepal.Length", "Sepal.Width")]) |
| 4 | + |
| 5 | +fit_y <- lm(y ~ poly(Petal.Width, degree = 2L) * Species, data = iris) |
| 6 | +fit_Y <- lm(Y ~ poly(Petal.Width, degree = 2L) * Species, data = iris) |
| 7 | + |
| 8 | +x <- c("Petal.Width", "Species") |
| 9 | +J <- c(1L, 51L, 101L) |
| 10 | + |
| 11 | +preds_y <- unname(predict(fit_y, iris)) |
| 12 | +preds_Y <- unname(predict(fit_Y, iris)) |
| 13 | + |
| 14 | +shap_y <- list( |
| 15 | + kernelshap(fit_y, iris[J, x], bg_X = iris, verbose = FALSE), |
| 16 | + permshap(fit_y, iris[J, x], bg_X = iris, verbose = FALSE) |
| 17 | +) |
| 18 | + |
| 19 | +shap_Y <- list( |
| 20 | + kernelshap(fit_Y, iris[J, x], bg_X = iris, verbose = FALSE), |
| 21 | + permshap(fit_Y, iris[J, x], bg_X = iris, verbose = FALSE) |
| 22 | +) |
| 23 | + |
| 24 | +test_that("Baseline equals average prediction on background data", { |
| 25 | + for (i in 1:2) { |
| 26 | + expect_equal(shap_Y[[i]]$baseline, unname(colMeans(Y))) |
| 27 | + } |
| 28 | +}) |
| 29 | + |
| 30 | +test_that("SHAP + baseline = prediction", { |
| 31 | + for (i in 1:2) { |
| 32 | + s <- shap_Y[[i]] |
| 33 | + expect_equal(rowSums(s$S[[1L]]) + s$baseline[1L], preds_Y[J, 1L]) |
| 34 | + expect_equal(rowSums(s$S[[2L]]) + s$baseline[2L], preds_Y[J, 2L]) |
| 35 | + } |
| 36 | +}) |
| 37 | + |
| 38 | +test_that("First dimension of multioutput model equals single output", { |
| 39 | + for (i in 1:2) { |
| 40 | + expect_equal(shap_Y[[i]]$baseline[1L], shap_y[[i]]$baseline) |
| 41 | + expect_equal(shap_Y[[i]]$S[[1L]], shap_y[[i]]$S) |
| 42 | + } |
| 43 | +}) |
| 44 | + |
| 45 | + |
0 commit comments