inst/doc/adaptive-models.R

## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 3.5
)

## ----setup, message = FALSE---------------------------------------------------
library(daltoolbox)
library(heimdall)

## -----------------------------------------------------------------------------
set.seed(1)
n <- 1500
x <- data.frame(x1 = rnorm(n), x2 = rnorm(n))
new_concept <- seq_len(n) > 750
target <- ifelse(new_concept, x$x1 - x$x2 > 0, x$x1 + x$x2 > 0)
y <- data.frame(target = factor(target, levels = c(FALSE, TRUE)))

batch <- (seq_len(n) - 1) %/% 50 + 1

## -----------------------------------------------------------------------------
run_stream <- function(detector) {
  model <- adp_retrain(cla_nb("target", c("FALSE", "TRUE")), detector, warmup_size = 100)
  results <- NULL
  for (b in 2:max(batch)) {
    train <- batch == (b - 1)
    test <- batch == b
    model <- fit(model, x[train, ], y[train, , drop = FALSE])

    accuracy <- NA
    if (model$fitted) {
      prediction <- predict(model, x[test, ])
      accuracy <- mean((prediction[, 2] > 0.5) == (y$target[test] == "TRUE"))
    }
    results <- rbind(results, data.frame(batch = b, drifted = model$drifted, accuracy = accuracy))
  }
  results
}

## -----------------------------------------------------------------------------
without_detector <- run_stream(dfr_inactive())
with_ddm <- run_stream(dfr_ddm())

with_ddm[with_ddm$drifted, ]

## -----------------------------------------------------------------------------
plot(without_detector$batch, without_detector$accuracy,
  type = "b", pch = 16,
  ylim = c(0.4, 1), col = "grey50", xlab = "batch", ylab = "accuracy"
)
lines(with_ddm$batch, with_ddm$accuracy, type = "b", pch = 16, col = "steelblue")
abline(v = 750 / 50 + 0.5, lty = 2, col = "grey70")
legend("bottomleft", c("dfr_inactive()", "dfr_ddm()"),
  col = c("grey50", "steelblue"),
  pch = 16, bty = "n", cex = 0.8
)

## -----------------------------------------------------------------------------
after <- with_ddm$batch > 16
c(
  without_detector = mean(without_detector$accuracy[after], na.rm = TRUE),
  with_ddm = mean(with_ddm$accuracy[after], na.rm = TRUE)
)

Try the heimdall package in your browser

Any scripts or data that you put into this service are public.

heimdall documentation built on Dec. 2, 2026, 5:08 p.m.