Package {heimdall}


Title: Drift Adaptable Models
Version: 1.5.707
Description: In streaming data analysis, it is crucial to detect significant shifts in the data distribution or the accuracy of predictive models over time, a phenomenon known as concept drift. The package aims to identify when concept drift occurs and provide methodologies for adapting models in non-stationary environments. It offers a range of state-of-the-art techniques for detecting concept drift and maintaining model performance. Additionally, the package provides tools for adapting models in response to these changes, ensuring continuous and accurate predictions in dynamic contexts. Methods for concept drift detection are described in Tavares (2022) <doi:10.1007/s12530-021-09415-z>.
License: MIT + file LICENSE
URL: https://cefet-rj-dal.github.io/heimdall/, https://github.com/cefet-rj-dal/heimdall
BugReports: https://github.com/cefet-rj-dal/heimdall/issues
Encoding: UTF-8
Depends: R (≥ 3.5.0)
Imports: stats, utils, daltoolbox, pROC
Suggests: daltoolboxdp, randomForest, reticulate, testthat (≥ 3.0.0), knitr, rmarkdown
VignetteBuilder: knitr
Config/testthat/edition: 3
Config/roxygen2/version: 8.1.1
NeedsCompilation: no
Packaged: 2026-12-02 08:21:31 UTC; gpca
Author: Lucas Tavares [aut], Leonardo Carvalho [aut], Rodrigo Machado [aut], Diego Carvalho [ctb], Esther Pacitti [ctb], Fabio Porto [ctb], Eduardo Ogasawara ORCID iD [aut, ths, cre], CEFET/RJ [cph]
Maintainer: Eduardo Ogasawara <eogasawara@ieee.org>
Repository: CRAN
Date/Publication: 2026-12-02 09:20:02 UTC

Baseline: incremental model

Description

Drift baseline that updates a single model incrementally with each batch (train_incremental()), with no drift reaction and no concept reuse (online learning).

Usage

adapt_incremental(
  method,
  train_size,
  epochs = 5L,
  memory = memory_undersampling(),
  warmup_size = 100L,
  th = NULL
)

Arguments

method

Classifier (e.g. cla_nb, torch_cla_mlp).

train_size

Rows needed to train and the sliding-window size.

epochs

Epochs of each incremental update (default 5).

memory

Memory prototype (default memory_undersampling()).

warmup_size

Minimum rows to train (default 100).

th

Decision threshold; NULL (default) learns the F1-optimal threshold.

Value

An adp_recurrent object.


Baseline: detect-and-reset

Description

Drift baseline that trains a fresh model and freezes it, and starts a new one whenever the detector flags a drift (detect-and-reset). No concept reuse (concept_pool_inactive()).

Usage

adapt_reset(
  method,
  train_size,
  detector = dfr_ddm(),
  memory = memory_undersampling(),
  warmup_size = 100L,
  th = NULL
)

Arguments

method

Classifier (e.g. cla_nb, torch_cla_mlp).

train_size

Rows needed to train and the sliding-window size.

detector

Drift detector that triggers the reset (default dfr_ddm()).

memory

Memory prototype (default memory_undersampling()).

warmup_size

Minimum rows to train (default 100).

th

Decision threshold; NULL (default) learns the F1-optimal threshold.

Value

An adp_recurrent object.


Baseline: periodic retraining

Description

Drift baseline that retrains a single model from scratch on its sliding window at every batch (train_retrain()), with no drift reaction and no concept reuse.

Usage

adapt_retrain(
  method,
  train_size,
  memory = memory_undersampling(),
  warmup_size = 100L,
  th = NULL
)

Arguments

method

Classifier (e.g. cla_nb, torch_cla_mlp).

train_size

Rows needed to train and the sliding-window size.

memory

Memory prototype (default memory_undersampling()).

warmup_size

Minimum rows to train (default 100).

th

Decision threshold; NULL (default) learns the F1-optimal threshold.

Value

An adp_recurrent object.


Baseline: static model

Description

Drift baseline that trains a model once and never adapts (lower bound). A degenerate adp_recurrent(): no drift reaction (dfr_inactive()), no concept reuse (concept_pool_inactive()), frozen model (train_static()).

Usage

adapt_static(
  method,
  train_size,
  memory = memory_undersampling(),
  warmup_size = 100L,
  th = NULL
)

Arguments

method

Classifier (e.g. cla_nb, torch_cla_mlp).

train_size

Rows needed to train and the sliding-window size.

memory

Memory prototype (default memory_undersampling()).

warmup_size

Minimum rows to train (default 100).

th

Decision threshold; NULL (default) learns the F1-optimal threshold.

Value

An adp_recurrent object.


Store a concept in the pool

Description

Generic called on drift: store the concept that was active into the pool (a no-op for concept_pool_inactive(), which never reuses concepts).

Usage

add_concept(obj, concept)

Arguments

obj

A concept_pool() (or concept_pool_inactive()) object.

concept

The new_concept() to store.

Value

The updated pool.


Recurrent-concept adaptive model

Description

Drift-adaptive classifier with concept management (the model formerly named REMIND). A concept holds a model, its preprocessors (one-hot and normalization), a data memory and a decision threshold. At every labeled batch, fit() runs the drift detector, lets the concept_pool keep, reuse or create a concept, and trains the active concept. predict() answers with the active concept or, with check, with the concept chosen from the batch features alone.

A batch is usable when at least 1% of its rows are positive. A drift on a non-usable batch postpones the adaptation: the batch only enters the data windows.

Usage

adp_recurrent(
  method,
  drift_method,
  model_manager = concept_pool_inactive(),
  memory = memory_basic(),
  trainer = train_static(),
  train_size,
  th = NULL,
  check = NULL,
  warmup_size = 100,
  rare_policy = rare_keep(),
  record_policy = rec_stable(),
  check_rank = rank_ratio(),
  preprocess = NULL,
  verbose = FALSE
)

Arguments

method

Classifier used by every concept (e.g. torch_cla_mlp).

drift_method

Drift detector.

model_manager

Concept concept_pool: concept_pool() stores and reuses concepts; concept_pool_inactive() never reuses them (every drift creates a new concept).

memory

Memory prototype: stores the data window of each concept and balances the training data of every full training (first training and retrain).

trainer

Training activity: how a concept's model evolves after its first (full) training (a variation point of the line). A model_trainer() object: train_static() (default; frozen), train_retrain() (retrained from scratch on the concept memory at every batch) or train_incremental() (updated with the current batch only, keeping weights and preprocessing).

train_size

Number of rows needed to train a new concept. It is also the size of the sliding windows: the buffer of recent rows and the memory of each concept.

th

Decision threshold. NULL (default): each concept uses the threshold in {0.05, ..., 0.95} with the highest F1 on its own memory, recomputed when its model or data change. A number fixes the threshold for every concept.

check

NULL (default) disables the check. A slct_psi() object enables it: predict() picks, from the batch features only, the concept with the smallest ratio between its PSI and its limit; fit() records the PSI of each labeled batch in the check history of the active concept. The limit is the fixed max_psi of the object or, when NULL, learned from the check history (quantile tol_quantile). Uses also the n_tiles and numerical_cols of the object.

warmup_size

Minimum number of rows to train a model, to run the drift detector and to apply the check.

rare_policy

Admission activity for labeled batches with < 1% positives (an optional activity of the line). A rare_policy() object: rare_keep() (default, neutral; the batch is used and only the drift adaptation is postponed) or rare_drop() (the batch is ignored).

record_policy

Recording activity: which labeled batches enter the learned limits (an optional activity of the line). A record_policy() object: rec_stable() (default; a batch flagged by a real detector does not record, but a passive detector never blocks it) or rec_always() (neutral; every batch that reaches the concept pool records, used in the experiments).

check_rank

How the check picks the concept (a variation point of the line). A concept_ranker() object: rank_ratio() (default; smallest PSI/limit) or rank_psi() (smallest PSI). Both pick a concept even above its limit (no new concept at predict time).

preprocess

Preprocessing of each concept: a trans_pipeline() (or any fitted-able dal_transform) applied to the features before the model. NULL (default) uses trans_pipeline(list(one_hot(), zscore())) (one-hot encoding then z-score normalization). Pass another sequence to change or drop steps.

verbose

If TRUE, prints drift messages.

Value

A adp_recurrent object. After each fit() it exposes drifted, trained, postponed, dropped, act_concept and the times time_drifter, time_adaptation, time_training, time_threshold and total_time.

Examples

## Not run: 
library(daltoolboxdp)
model <- adp_recurrent(
 method = torch_cla_mlp("class", c("FALSE", "TRUE"), input_size = 10, hidden_sizes = 32L),
 drift_method = dfr_passive(),
 model_manager = concept_pool(slct_psi(n_tiles = 5), evt_least_used(), n_slots = 20),
 memory = memory_undersampling(),
 trainer = train_incremental(epochs = 5),
 train_size = 5000,
 check = slct_psi(n_tiles = 5, tol_quantile = 0.8)
)

## End(Not run)

Retrain-on-drift adaptive model

Description

Drift-adaptive model (formerly named stealthy). It wraps a predictive model and a drift detector, retraining the model whenever a drift is reported. For reuse of recurrent concepts, see adp_recurrent().

Usage

adp_retrain(
  model,
  drift_method,
  norm_class = daltoolbox::zscore(),
  warmup_size = 100,
  th = 0.5,
  target_uni_drifter = FALSE,
  incremental_memory = FALSE,
  active_warmup = FALSE,
  class_balance = "inactive",
  obsolete_model = "null",
  reporting = FALSE,
  history_size = NULL,
  verbose = FALSE
)

Arguments

model

The algorithm object to be used for predictions

drift_method

The algorithm object to detect drifts

norm_class

Class used to perform normalization

warmup_size

Number of rows used to warmup the drifter. No drift will be detected during this phase

th

The threshold to be used with classification algorithms

target_uni_drifter

Passes the prediction target to the drifts as the target feat when the drifter is univariate and dist_based. The target must be binary (logical, 0/1 or a factor with those labels).

incremental_memory

If true, the model will retrain with all available data whenever the fit is called. If false, it only retrains when a drift is detected.

active_warmup

If true, the models will be retrained for each batch while the number of rows for the warmup_size is not met.

class_balance

Class balancing strategy. "buffer" sets a buffer with the last warmup_size/2 rows for each class. "inactive" does nothing.

obsolete_model

Strategy used by predict() while no model is fitted. One of "null" (default, returns all FALSE), "majority" (majority class of the data the previous model was trained on) or "last_model" (keeps using the previous model).

reporting

If TRUE, every batch given to fit() (x and y) is accumulated in drifter_input.

history_size

Maximum number of rows kept in drifter_output and drifter_input; the oldest rows are dropped first. NULL (the default) keeps the whole stream, so set it on long streams to bound memory.

verbose

if TRUE shows drift messages

Details

The drifter decides what it monitors through its own target_feat, given in terms of the one-hot encoded and normalized columns: a univariate drifter with a target_feat receives that column, a univariate drifter without one receives the row mean of every column, and multivariate, multi-criteria and dummy drifters receive the selected columns (every column when their target_feat is NULL).

The batch is evaluated before the model is updated: error-based detectors see prequential residuals, computed with the model as it was at the beginning of the call, and the detector is fed the incoming batch exactly once per call.

obj$drifter_output holds the diagnostics reported by the drifter (for example the window width of ADWIN or the p-values of KSWIN; see the drifter_output of each detector), with one row per row of x across every call to fit(). Rows are NA while the drifter is not monitoring (during the warmup, or after a drift until the model is retrained) and for observations it skipped, such as error-based rows without a prediction.

Value

An adp_retrain object

Examples

# See ?dfr_ddm for a drift detector that can be plugged here, and the
# online prediction walkthroughs at
# https://github.com/cefet-rj-dal/heimdall/tree/main/examples/2_online_prediction

Evolve an existing concept with a labeled batch

Description

Generic of the training activity: given a concept that already has a model, evolve it with the current batch as the chosen model_trainer() prescribes. The first full training of a new concept is handled by the line's backbone, not here.

Usage

advance_concept(trainer, concept, x, y, usable, rsrc)

Arguments

trainer

A model_trainer() object.

concept

The active new_concept() (with a fitted model).

x, y

Features and labels of the current batch.

usable

TRUE when the batch has enough positives to update a model.

rsrc

Training resources: a list with method, memory, preprocess, train_size and warmup_size (see the recurrent line's internals).

Value

⁠list(concept = <updated concept>, trained = <logical: whether the model changed>)⁠.


Reuse a stored concept for the current batch

Description

Generic called on drift: ask the pool's selector for a stored concept that fits the current batch, or none (so a new concept is created). concept_pool_inactive() never reuses.

Usage

check_concept(obj, X, y)

Arguments

obj

A concept_pool() (or concept_pool_inactive()) object.

X

Features of the current batch.

y

Labels of the current batch.

Value

⁠list(mm = <updated pool>, sc = <chosen concept or NULL>)⁠.


Metrics from a confusion matrix

Description

Metrics of a batch from the counts of its confusion matrix, vectorised over batches. A metric whose denominator is zero comes back as NA.

Usage

cm_metrics(TP, FP, TN, FN)

Arguments

TP

True positives, one value per batch.

FP

False positives, one value per batch.

TN

True negatives, one value per batch.

FN

False negatives, one value per batch.

Value

A list with accuracy, precision, recall and f1, one value per batch.

Examples

cm_metrics(TP = 8, FP = 2, TN = 85, FN = 5)

Concept pool

Description

Stores concepts in slots and, on drift, asks its selector for a stored concept that fits the current batch (check_concept()). It also decides when the selector records the current batch in the learned limits of the active concept (history_order) and how the limits of a new concept start (history_init). Both only apply to learned limits: with a fixed limit (e.g. slct_psi(max_psi = 0.25)) the selector keeps no history.

Usage

concept_pool(
  model_selector,
  model_deleter,
  n_slots = 1,
  history_order = c("before", "after"),
  history_init = c("none", "blocks")
)

Arguments

model_selector

Selector that chooses the stored concept to reuse.

model_deleter

Evictor that chooses the slot to replace when every slot is used.

n_slots

Number of slots.

history_order

"before" (default): the active concept records the batch before the drift decision. "after": the decision uses the previous batches only; the batch is then recorded in the concept that stays active (if it already has a model). Requires history_init = "blocks" (the learned limits must start with values from the training window).

history_init

"none" (default): the history of a new concept starts empty. "blocks": it starts with the PSI of each batch-sized block of the concept's training window against the rest of the window. Applies to the PSI limits of the selector and of the REMIND check, and requires a REMIND train_size of at least two batches. The error tolerance of slct_error_metrics() (alone or inside slct_psi_then_error()) also starts by blocks only when the selector is created with init_blocks = TRUE (one model per block; see init_history.slct_error_metrics).

Value

A concept_pool object.


Inactive concept pool

Description

Never stores nor reuses concepts: every drift creates a new concept.

Usage

concept_pool_inactive()

Value

A concept_pool_inactive object.


Concept ranker

Description

Base class of the concept rankers: how the check of adp_recurrent() picks, at predict time, the concept to answer among the candidates it scored by PSI against their memory. The variants are rank_ratio() (smallest PSI/limit) and rank_psi() (smallest PSI). New criteria plug in by subclassing and implementing rank_criterion().

Usage

concept_ranker()

Value

A concept_ranker object.


Average cosine similarity to a baseline of embeddings

Description

Scores every new observation (an embedding vector, such as the sentence embedding of a text) by its average cosine similarity with the embeddings of a baseline, the data drift check of the custom Amazon SageMaker Model Monitor for NLP models of Nigenda et al. (2022):

s(x) = \frac{1}{N}\sum_{i=1}^{N} \frac{x \cdot e_i}{\|x\| \|e_i\|}.

Inputs far from the baseline distribution get low scores.

Usage

cosine_score(reference, x)

Arguments

reference

The baseline embeddings: a numeric matrix or data frame, one row per embedding.

x

The embeddings to score, with the same columns (or a single embedding as a numeric vector).

Details

The average of the cosine similarities equals the inner product of the normalised input with the mean of the normalised baseline embeddings, so scoring costs one inner product per input instead of one per baseline embedding (the reference code loops over the baseline). Baseline embeddings with zero norm are left out, and an input with zero norm gets NA (the cosine is undefined; the reference code gets NaN).

Value

A numeric vector with the score of every row of x.

References

Nigenda, D., Karnin, Z., Zafar, M. B., Ramesha, R., Tan, A., Donini, M. and Kenthapadi, K. (2022). Amazon SageMaker Model Monitor: A system for real-time insights into deployed machine learning models. In Proceedings of the 28th ACM SIGKDD Conference on Knowledge Discovery and Data Mining, 3671-3681. https://doi.org/10.1145/3534678.3539145

See Also

dfr_cosine() to monitor a stream.

Examples

set.seed(1)
baseline <- matrix(stats::rnorm(2000, mean = 1), ncol = 20)
near <- matrix(stats::rnorm(100, mean = 1), ncol = 20)
far <- matrix(stats::rnorm(100, mean = -1), ncol = 20)
cosine_score(baseline, near)
cosine_score(baseline, far)

Calibration of change point models

Description

Post-hoc calibration of the scores of a change point model (indid(), tscp2(), ts2vec()) or of every member of an ensemble (cpd_ensemble()) on labelled sequences, as the WWAggr pipeline does before aggregating: beta calibration (Kull et al., 2017, the method of the paper) or temperature scaling (Guo et al., 2017).

Usage

cpd_calibrate(
  model,
  x,
  labels,
  method = c("beta", "temperature"),
  parameters = c("abm", "am", "ab", "a")
)

Arguments

model

A change point model or a cpd_ensemble.

x

Calibration sequences, in the formats accepted by indid().

labels

Their labels, a 0/1 matrix ⁠[sequence, time]⁠ (1 from the change on).

method

"beta" (default) or "temperature".

parameters

Parameters of the beta calibration: "abm" (default), "am", "ab" or "a".

Details

Every score of every step (the steps without score of the representation models excluded) is a sample, labelled by the label of its step. The beta calibration follows the betacal package used by the reference (https://github.com/betacal/python): a logistic regression of the label on log(s) and -log(1 - s) ("abm"; when one coefficient is negative, the regression is refitted on the other feature alone), on the logit of s ("am"), on ⁠log(2 s)⁠ and log(2 (1 - s)) without intercept ("ab"), or on the logit without intercept ("a"). Scores are clipped to ⁠[eps, 1 - eps]⁠ with the machine epsilon of single precision (the reference scores are float32). The regressions are unpenalised (glm; the reference uses scikit-learn's LogisticRegression with C = 1e11).

Temperature scaling divides the logit of the score by the temperature that minimises the log-loss on the calibration data. In the reference code the fitted temperature is stored on the model wrapper and does not change its predictions, so this option follows Guo et al. (2017) rather than the code.

Value

A cpd_calibrated model (the model and its calibration map), or a cpd_ensemble of calibrated members.

References

Kull, M., Silva Filho, T. M. and Flach, P. (2017). Beyond sigmoids: How to obtain well-calibrated probabilities from binary classifiers with beta calibration. Electronic Journal of Statistics, 11(2), 5052-5080. https://doi.org/10.1214/17-EJS1338SI

Guo, C., Pleiss, G., Sun, Y. and Weinberger, K. Q. (2017). On calibration of modern neural networks. Proceedings of the 34th International Conference on Machine Learning, 1321-1330.

Examples

set.seed(1)
make <- function(n) {
  change <- sample(5:24, n, replace = TRUE)
  x <- t(vapply(change, function(c) stats::rnorm(24, ifelse(seq_len(24) < c, 0, 3)), numeric(24)))
  list(x = x, labels = t(vapply(change, function(c) (seq_len(24) >= c) * 1, numeric(24))))
}
train <- make(64)
model <- indid(train$x, train$labels, loss = "bce", epochs = 5, seed = 1)
calibrated <- cpd_calibrate(model, train$x, train$labels)
calibrated$calibrator$map

Ensembles of change point models

Description

cpd_ensemble() groups trained change point models (indid() with BCE or InDiD loss, tscp2(), ts2vec(), or calibrated ones) into an ensemble, possibly mixing types; cpd_ensemble_fit() trains the members of an ensemble of one type. The scores of the members (cpd_scores()) are aggregated by wwaggr() or monitored on a stream by dfr_wwaggr().

Usage

cpd_ensemble(members)

cpd_ensemble_fit(
  x,
  labels = NULL,
  model = c("bce", "indid", "tscp2", "ts2vec"),
  n_models = 10,
  boot_sample_size = NULL,
  seed = NULL,
  ...
)

Arguments

members

A list of trained change point models with the same input features.

x

Training sequences, in the formats accepted by indid().

labels

Their labels (0/1 matrix ⁠[sequence, time]⁠), for the supervised models.

model

Type of the members: "bce" and "indid" (indid() with that loss), "tscp2" or "ts2vec".

n_models

Number of members.

boot_sample_size

NULL (default): every member is trained on all the sequences and the members differ only by their seeds (the "naive" ensembles of the paper). Otherwise every member is trained on a bootstrap sample of boot_sample_size sequences.

seed

Seed of the ensemble: member i is trained with seed seed + i - 1, and the bootstrap samples are drawn with seed. NULL draws one from the session.

...

Settings of the members, passed to indid(), tscp2() or ts2vec().

Details

The paper also compares ensembles trained with stochastic gradient Langevin dynamics; the reference code has no implementation of them and they are not provided.

Value

A cpd_ensemble object (members).

References

Stepikin, A., Romanenkova, E. and Zaytsev, A. (2025). WWAggr: A window Wasserstein-based aggregation for ensemble change point detection. 2025 IEEE International Conference on Data Mining (ICDM), 1535-1544. https://doi.org/10.1109/ICDM65498.2025.00163

Examples

set.seed(1)
make <- function(n) {
  change <- sample(5:24, n, replace = TRUE)
  x <- t(vapply(change, function(c) stats::rnorm(24, ifelse(seq_len(24) < c, 0, 3)), numeric(24)))
  list(x = x, labels = t(vapply(change, function(c) (seq_len(24) >= c) * 1, numeric(24))))
}
train <- make(64)
ensemble <- cpd_ensemble_fit(train$x, train$labels, model = "bce", n_models = 3,
                             epochs = 5, seed = 1)
dim(cpd_scores(ensemble, train$x[1:2, ]))

Change point scores of a sequence model

Description

Scores in ⁠[0, 1]⁠ of every time step of every sequence: the probability of change of an indid() model, or the processed similarity of consecutive windows of a tscp2() or ts2vec() model. For calibrated models (cpd_calibrate()) the calibrated scores, and for ensembles (cpd_ensemble()) the scores of every member.

Usage

cpd_scores(model, x, ...)

Arguments

model

A model: indid, tscp2, ts2vec, cpd_calibrated or cpd_ensemble.

x

Sequences, in the formats accepted by indid().

...

Unused.

Value

A matrix ⁠[sequence, time]⁠; for an ensemble an array ⁠[member, sequence, time]⁠. The representation models (TS-CP2 and SN-TS2Vec) have no score for the first 2 * window - 1 steps (NA).

Examples

set.seed(1)
# 8 sequences of 12 steps with 2 features; the mean moves at step 7.
x <- array(stats::rnorm(8 * 12 * 2), c(8, 12, 2))
x[, 7:12, ] <- x[, 7:12, ] + 3
model <- ts2vec(x, window = 3, output_dim = 4, hidden_dim = 8, depth = 2, epochs = 5, seed = 1)
round(cpd_scores(model, x[1:2, , ]), 2)

DDE probability curve

Description

Computes the DDE probability curve and the DDE probability lift curve of a drift (Szucs and Nemeth, 2025, Section 2).

Usage

dde_curve(data, drifting, thresholds = seq(0, 0.9, by = 0.1))

Arguments

data

Data frame or matrix with the features in the reference window, where the Pearson correlations are measured.

drifting

Names (or a logical vector over the columns of data) of the features that drift.

thresholds

Correlation thresholds z.

Details

For each threshold z, B(z) is the number of feature pairs with |\rho_{ij}| \ge z (Eq. 14) and b(z) the number of those pairs in which both features drift (Eq. 15). With m features of which k drift, the DDE probability is

r_{n/N}(z) = \frac{m}{k} \frac{b(z)}{B(z)}

(Eqs. 16 and 20), the probability that a neighbour of a drifting feature drifts too, and the lift divides it by its value at z = 0, (k - 1)/(m - 1) (Eqs. 21 to 24). A flat lift curve means that the features drift independently of their correlation; an increasing one, that the drift affects groups of correlated features (the domino drift effect). Features without variance have no correlation with the others and are treated as uncorrelated.

Value

data frame with one row per threshold and the columns threshold, pairs (B(z)), drifting_pairs (b(z)), probability (r_{n/N}(z), NA when no pair reaches the threshold) and lift.

Examples

set.seed(1)
a <- stats::rnorm(200)
b <- stats::rnorm(200)
data <- data.frame(a1 = a, a2 = a + stats::rnorm(200, sd = 0.2),
                   a3 = a + stats::rnorm(200, sd = 0.5),
                   b1 = b, b2 = b + stats::rnorm(200, sd = 0.2),
                   b3 = b + stats::rnorm(200, sd = 0.5))
# The correlated group "a" drifts: the lift grows with the correlation.
dde_curve(data, c("a1", "a2", "a3"))

Feature-wise drift tests between two windows

Description

Tests every feature for drift between a reference window and an analysis window, with the univariate tests used by Szucs and Nemeth (2025).

Usage

dde_feature_drift(reference, current, test = "js", threshold = NULL)

Arguments

reference

Data frame or matrix with the reference window.

current

Data frame or matrix with the analysis window, with the same columns.

test

One of "js", "ks" or "wasserstein".

threshold

Drift threshold. NULL uses the default of the test.

Details

The tests follow the definitions and defaults of the Evidently library:

Missing values are dropped; features with fewer than two values in either window are not tested.

The distances of the "js" test do not shrink to 0 between two samples of the same distribution: with a few hundred observations per window the Jensen-Shannon distance of identical distributions is often close to the default threshold. Use windows of about a thousand observations, or a higher threshold, with small windows.

Value

data frame with one row per feature and the columns feature, statistic (the distance, or the p-value for "ks") and drift.

Examples

set.seed(1)
reference <- data.frame(x = stats::rnorm(300), y = stats::rnorm(300))
current <- data.frame(x = stats::rnorm(300, mean = 1), y = stats::rnorm(300))
dde_feature_drift(reference, current, test = "ks")

DDE drift scores

Description

Predicts the drift score of unmonitored features from the drifting monitored features (Szucs and Nemeth, 2025, Eq. 25).

Usage

dde_score(curve, data, drifting, unmonitored)

Arguments

curve

DDE curve, as returned by dde_curve().

data

Data frame or matrix with the features in the reference window, where the Pearson correlations are measured.

drifting

Names of the monitored features that drift.

unmonitored

Names of the features to score.

Details

The score of an unmonitored feature f_i is the mean, over the drifting monitored features f_j, of the DDE probability at |\rho_{ij}|: the probability of the largest threshold that does not exceed the correlation. Thresholds without pairs take the probability of the previous threshold. Scores are limited to [0, 1]; they are 0 when no monitored feature drifts.

Value

named numeric vector of scores, one per unmonitored feature.

Examples

set.seed(1)
a <- stats::rnorm(200)
b <- stats::rnorm(200)
data <- data.frame(a1 = a, a2 = a + stats::rnorm(200, sd = 0.2),
                   a3 = a + stats::rnorm(200, sd = 0.5),
                   b1 = b, b2 = b + stats::rnorm(200, sd = 0.2),
                   b3 = b + stats::rnorm(200, sd = 0.5))
curve <- dde_curve(data, c("a1", "a2", "a3"))
# a1 drifts: its neighbours get high scores, the "b" features low ones.
dde_score(curve, data, drifting = "a1", unmonitored = c("a2", "a3", "b2", "b3"))

ADWIN method

Description

ADWIN (Adaptive Windowing) is a sequential change detector that maintains a variable-length window and tests whether the means of two subwindows differ significantly. In this package, the implementation is primarily used for virtual concept drift when it monitors a numeric feature stream, although the same mechanism can also detect real concept drift if applied to an error or loss stream. The theoretical basis follows Bifet and Gavalda (2007) https://doi.org/10.1137/1.9781611972771.42.

Usage

dfr_adwin(target_feat = NULL, delta = 2e-05)

Arguments

target_feat

Feature to be monitored.

delta

The significance parameter for the ADWIN algorithm.

Details

The implementation is written in pure R and follows the exponential-histogram version of ADWIN distributed with scikit-multiflow. The window is compressed into buckets of exponentially growing size (at most five buckets per size), and the cut points are checked every 32 observations, once the window holds more than 10 observations. All the state lives in the object itself, so a dfr_adwin object can be serialized with base::saveRDS().

Value

dfr_adwin object

References

Bifet, A., and Gavalda, R. (2007). Learning from time-changing data with adaptive windowing. In Proceedings of the 2007 SIAM International Conference on Data Mining, 443-448. https://doi.org/10.1137/1.9781611972771.42

Examples

library(daltoolbox)
library(heimdall)

data(st_drift_examples)
data <- st_drift_examples$uv_virtual_drift
data$event <- NULL

model <- dfr_adwin(target_feat = "serie")

detection <- NULL
output <- list(obj = model, drift = FALSE)
for (i in seq_along(data$serie)) {
  output <- update_state(output$obj, data$serie[i])
  if (output$drift) {
    type <- "drift"
    output$obj <- reset_state(output$obj)
  } else {
    type <- ""
  }
  detection <- rbind(detection, data.frame(idx = i, event = output$drift, type = type))
}

print(detection[detection$type == "drift", ])

Autoencoder-Based Drift Detection method

Description

AEDD is an unsupervised multivariate detector that compares reconstruction errors produced by an autoencoder on reference and recent windows. Because it monitors changes in the input distribution rather than classifier performance, this implementation is primarily aimed at virtual concept drift. The method follows Kaminskyi, Li, and Muller (2022) https://doi.org/10.1109/ICDMW58026.2022.00109.

Usage

dfr_aedd(
  encoding_size,
  ae_class = NULL,
  ae_params = list(batch_size = 32, num_epochs = 1000, learning_rate = 0.001,
    error_function = "mae"),
  window_size = 100,
  window_type = "sliding",
  monitoring_step = floor(window_size/2),
  criteria = "mann_whitney",
  alpha = 0.01,
  threshold = 0.01,
  column_threshold = NULL,
  target_feat = NULL
)

Arguments

encoding_size

Encoding Size

ae_class

Autoencoder constructor. When NULL (the default), daltoolboxdp::autoenc_ed is used, which requires the suggested package daltoolboxdp and its Python backend.

ae_params

Named list of arguments forwarded to ae_class, plus error_function, which selects how the reconstruction error is summarised. One of "mae" (default) or "rmse".

window_size

Number of most recent rows kept by the detector. The oldest half is the reference window and the newest half the recent window.

window_type

Window policy. "sliding" (default) keeps at most window_size rows, so both halves move with the stream. "anchored" keeps every row, which pins the reference half to the beginning of the stream and makes memory grow with the stream length.

monitoring_step

Number of rows between two consecutive checks. The default checks twice per window.

criteria

The method used to check for a drift. One of "mann_whitney" (default), "kolmogorov_smirnov", "levene", "psi", "parametric_threshold", "nonparametric_threshold" or "diff_threshold".

alpha

Significance level of the hypothesis-test criteria ("mann_whitney", "kolmogorov_smirnov" and "levene").

threshold

Drift threshold of the "psi" and "diff_threshold" criteria, compared directly against the divergence or the median error difference. It is a raw threshold, not a probability.

column_threshold

NULL (the default) or a proportion between 0 and 1. When set, the criterion is evaluated separately on every monitored column (one per latent dimension for an encoder, a single one for an encoder-decoder), and a drift is signalled only when the proportion of columns flagged as changed is strictly greater than column_threshold. For example, with column_threshold = 0.5, 3 changed columns out of 5 (60%) signal a drift. The hypothesis tests flag a column when its uncorrected p-value is below alpha.

target_feat

Names of the columns to be monitored. NULL (the default) monitors every numeric column.

Details

The autoencoder expects inputs in the ⁠[0, 1]⁠ range. Values outside that range are clipped to it, and the detector warns the first time this happens, so the data should be normalized beforehand (for example with daltoolbox::minmax()). ae_class must be a constructor accepting the arguments input_size and encoding_size plus the entries of ae_params, whose objects implement fit() and transform().

The autoencoder is trained on the reference window the first time the window is full, and again after every drift or whenever new columns appear.

With an encoder-decoder, the reconstruction error of each row is summarised into a single value, so every criterion sees one column. With an encoder, the latent representation is monitored directly and there is one column per latent dimension (encoding_size).

When column_threshold is NULL, the hypothesis-test criteria ("mann_whitney", "kolmogorov_smirnov" and "levene") test every column and combine the per-column p-values with a Bonferroni correction, instead of pooling all columns into a single sample.

Value

dfr_aedd object

References

Kaminskyi, D., Li, B., and Muller, E. (2022). Reconstruction-based unsupervised drift detection over multivariate streaming data. In 2022 IEEE International Conference on Data Mining Workshops (ICDMW). https://doi.org/10.1109/ICDMW58026.2022.00109

Examples

# Training an autoencoder is too slow for an inline example. A rendered
# walkthrough is available at
# https://github.com/cefet-rj-dal/heimdall/blob/main/examples/1_detection/dfr_aedd.md

Cosine similarity drift detector for embeddings

Description

Monitors a stream of embeddings (for instance BERT sentence embeddings of the texts sent to an NLP model) with the custom Model Monitor of Nigenda et al. (2022): every observation is scored by its average cosine similarity with the baseline embeddings (cosine_score()), the scores are averaged over monitoring windows of window_size observations, and a drift is reported when the average falls below threshold. Since it monitors the distribution of the inputs, it is used for virtual concept drift.

Usage

dfr_cosine(
  target_feat = NULL,
  reference = NULL,
  n_reference = 1000,
  window_size = 1,
  threshold = 0.5
)

Arguments

target_feat

Names of the columns holding the embedding. NULL (the default) uses every numeric column.

reference

Optional baseline embeddings (a matrix or data frame with the monitored columns), such as the embeddings of the training texts. When NULL, the first n_reference observations of the stream form the baseline.

n_reference

Size of the baseline taken from the stream when reference is NULL.

window_size

Number of observations whose scores are averaged before the comparison with threshold (the monitoring window, an hour of traffic in the paper). With 1, every observation is checked on its own, as the reference code does.

threshold

A window whose average score is below it is a drift (0.5 in the reference code).

Details

The windows do not overlap; the drift is reported on the last observation of the window. Observations with missing values or zero norm are skipped. reset_state() keeps a baseline given in reference and empties the window; a baseline taken from the stream is forgotten, and the next n_reference observations form a new one.

Value

dfr_cosine object. After fit(), drifter_output holds the score of every observation (score) and the average of the window on its last observation (window_score).

References

Nigenda, D., Karnin, Z., Zafar, M. B., Ramesha, R., Tan, A., Donini, M. and Kenthapadi, K. (2022). Amazon SageMaker Model Monitor: A system for real-time insights into deployed machine learning models. In Proceedings of the 28th ACM SIGKDD Conference on Knowledge Discovery and Data Mining, 3671-3681. https://doi.org/10.1145/3534678.3539145

Examples

library(daltoolbox)
library(heimdall)
set.seed(1)
baseline <- matrix(stats::rnorm(2000, mean = 2), ncol = 20)
# From row 21 half of the coordinates change sign.
flipped <- matrix(stats::rnorm(400, mean = 2), ncol = 20) %*% diag(rep(c(1, -1), each = 10))
stream <- as.data.frame(rbind(matrix(stats::rnorm(400, mean = 2), ncol = 20), flipped))
detector <- dfr_cosine(reference = baseline, window_size = 10, threshold = 0.5)
model <- fit(detector, stream)
model$drifter_output[!is.na(model$drifter_output$window_score), ]

Cumulative Sum for Concept Drift Detection (CUSUM) method

Description

CUSUM is a sequential analysis procedure that accumulates deviations in a monitored signal and raises an alarm when the cumulative evidence exceeds a threshold. In this package, the detector is implemented as an error-based monitor, so it is primarily intended for real concept drift affecting predictive performance. The concept-drift adaptation follows the sequential change-detection literature discussed by Muthukrishnan, Berg, and Wu (2007) https://doi.org/10.1109/ICDMW.2007.89.

Usage

dfr_cusum(lambda = 50, delta = 0.005, min_instances = 30)

Arguments

lambda

Detection threshold: a drift is reported when the cumulative sum exceeds it. Lower values react faster at the cost of more false alarms.

delta

Tolerance subtracted at every step, i.e. the increase of the error rate that is still considered acceptable.

min_instances

Minimum number of observations before a drift can be reported.

Details

The detector follows the CusumDM detector of MOA: it accumulates max(0, sum + x - mean - delta), where mean is the running error rate, so it reacts to an increase of the error rate whatever its level. After a drift is reported the statistics restart from scratch. Missing values are treated as correct predictions (0).

Up to version 1.3.0, dfr_cusum() accumulated +1 for every error and -1 for every correct prediction, so it could only detect error rates above 50%.

Value

dfr_cusum object

References

Muthukrishnan, S., Berg, E., and Wu, Y. (2007). Sequential change detection on data streams. In Seventh IEEE International Conference on Data Mining Workshops (ICDMW 2007). https://doi.org/10.1109/ICDMW.2007.89

Examples

# Load Heimdall and the synthetic benchmark stream.
library(heimdall)

# Fix the seed for reproducibility.
seed <- 1
set.seed(seed)

# Load the stream and derive a simple binary error-like signal.
data(st_drift_examples)
data <- st_drift_examples$uv_virtual_drift
data$prediction <- st_drift_examples$uv_virtual_drift$serie > 4

# Plot the binary monitored stream used by CUSUM.
plot(x=seq_len(nrow(data)), y=data$prediction)

# Instantiate the CUSUM detector.
model <- dfr_cusum()

# Update the detector sequentially over the binary stream.
detection <- NULL
output <- list(obj=model, drift=FALSE)
for (i in seq_len(nrow(data))){
  output <- update_state(output$obj, data$prediction[i])
  if (output$drift){
    type <- 'drift'
    output$obj <- reset_state(output$obj)
  } else {
    type <- ''
  }
  detection <- rbind(detection, data.frame(idx=i, event=output$drift, type=type))
}

# Print the drift alarms produced by the detector.
detection[detection$type == 'drift',]

# Map the drift alarms back onto the original numeric series.
plot(x=seq_len(nrow(data)), y=data$serie)
for (drift_index in detection[detection$type == 'drift', 'idx']) {
  abline(v=drift_index, col='red', lty=2)
}

Domino drift effect (DDE) detector

Description

Feature drift detector that monitors only a subset of the features and estimates the probability that each of the other features drifts, from the correlation between the features (Szucs and Nemeth, 2025). The method relies on the domino drift effect: when features drift together, the neighbours (strongly correlated features) of a drifting feature are more likely to drift as well.

Usage

dfr_dde(
  target_feat = NULL,
  monitored = NULL,
  n_monitored = NULL,
  test = "js",
  threshold = NULL,
  window_size = 500,
  monitoring_step = 1,
  confirmation_delay = NULL,
  thresholds = seq(0, 0.9, by = 0.1),
  score_threshold = 0.5,
  update_curve = TRUE,
  delta = 2e-05,
  seed = NULL
)

Arguments

target_feat

Names of the features. NULL (the default) uses every numeric column.

monitored

Names of the monitored features, S_{check}.

n_monitored

Number of monitored features, drawn at random when monitored is NULL. When both are NULL every feature is monitored and no score is predicted.

test

Univariate drift test applied to each monitored feature: one of "js" (Jensen-Shannon distance), "ks" (Kolmogorov-Smirnov), "wasserstein" (normalized Wasserstein distance) or "adwin". See dde_feature_drift().

threshold

Drift threshold of the test. NULL uses the default of dde_feature_drift().

window_size

Size of the reference and of the analysis windows (r = q).

monitoring_step

Number of observations between two consecutive tests of the window-based tests.

confirmation_delay

Number of observations between the first drift signal and the decision on which features drift. NULL (the default) uses half a window. See Details.

thresholds

Correlation thresholds z at which the DDE curve is evaluated.

score_threshold

Score from which an unmonitored feature is predicted to drift.

update_curve

Whether to refine the DDE curve with the drifts detected after the initialization, by averaging it with the curves of the monitored features (Algorithm 1, line 29).

delta

Confidence of ADWIN, used when test = "adwin".

seed

Seed of the random draw of the monitored features.

Details

The detector compares, for each feature, a reference window with the following analysis window, both of window_size observations (Algorithm 1). It starts in an initialization phase in which every feature is monitored. The first drift with at least two drifting features fixes the DDE curve, computed with dde_curve() from the Pearson correlations in the reference window. From then on only the monitored features are tested. When some of them drift, every unmonitored feature gets a drift score with dde_score(), the mean of the DDE curve over its correlations with the drifting monitored features (Eq. 25).

A drift is reported when at least one monitored feature drifts. The features do not cross their thresholds at the same observation, so the first signal opens a confirmation period of confirmation_delay observations, after which the windows are tested again: the drifting features are those of this confirmation test (with ADWIN, every feature signalled during the period), and no drift is reported if none remains. The correlations are measured in the reference window of the first signal. After a drift the analysis window becomes the new reference window.

The fitted object exposes:

The paper's repository (github.com/marcellnemeth/DominoDriftEffect) is not public, so the implementation follows the paper. The window tests use the definitions and default thresholds of the Evidently library.

Value

dfr_dde object

References

Szucs, G. and Nemeth, M. (2025). Domino drift effect approach for probability estimation of feature drift in high-dimensional data. Knowledge and Information Systems, 67, 4597-4621. https://doi.org/10.1007/s10115-025-02362-0

Examples

library(daltoolbox)
library(heimdall)

# Six features in two correlated groups; the first group drifts.
set.seed(1)
n <- 600
make <- function(n, shift) {
  a <- stats::rnorm(n, shift)
  b <- stats::rnorm(n)
  data.frame(a1 = a + stats::rnorm(n, sd = 0.3), a2 = a + stats::rnorm(n, sd = 0.3),
             a3 = a + stats::rnorm(n, sd = 0.3), b1 = b + stats::rnorm(n, sd = 0.3),
             b2 = b + stats::rnorm(n, sd = 0.3), b3 = b + stats::rnorm(n, sd = 0.3))
}
stream <- rbind(make(n, 0), make(n, 3), make(n, 3), make(n, 6))

model <- dfr_dde(monitored = c("a1", "b1"), test = "ks", threshold = 1e-3,
                 window_size = 300, monitoring_step = 50)
model <- fit(model, stream)
model$curve
model$feature_drift

Adapted Drift Detection Method (DDM) method

Description

DDM monitors the online error rate of a predictive model under the PAC-learning assumption that, in a stationary environment, the error should decrease or remain stable as more samples are observed. Because it operates on the classifier error stream, it is primarily a detector of real concept drift. The method follows Gama et al. (2004) https://doi.org/10.1007/978-3-540-28645-5_29.

Usage

dfr_ddm(min_instances = 30, warning_level = 2, out_control_level = 3)

Arguments

min_instances

The minimum number of instances before detecting change

warning_level

Necessary level for warning zone (2 standard deviation)

out_control_level

Necessary level for a positive drift detection

Details

The detector only reacts to an increase of the error rate (a degradation of the model); improvements are not reported. Values must be 1 (error) or 0 (correct prediction), and missing values are treated as correct predictions (0).

Value

dfr_ddm object

References

Gama, J., Medas, P., Castillo, G., and Rodrigues, P. P. (2004). Learning with drift detection. In Advances in Artificial Intelligence - SBIA 2004, 286-295. https://doi.org/10.1007/978-3-540-28645-5_29

Examples

# Load Heimdall and the built-in synthetic data stream.
library(heimdall)

# Fix the seed to make the example reproducible.
seed <- 1
set.seed(seed)

# Load the univariate stream and derive the binary monitored signal.
data(st_drift_examples)
data <- st_drift_examples$uv_virtual_drift
data$prediction <- st_drift_examples$uv_virtual_drift$serie > 4

# Plot the binary stream monitored by DDM.
plot(x=seq_len(nrow(data)), y=data$prediction)

# Instantiate the DDM detector.
model <- dfr_ddm()

# Process the stream sequentially and store the drift alarms.
detection <- NULL
output <- list(obj=model, drift=FALSE)
for (i in seq_len(nrow(data))){
  output <- update_state(output$obj, data$prediction[i])
  if (output$drift){
    type <- 'drift'
    output$obj <- reset_state(output$obj)
  } else {
    type <- ''
  }
  detection <- rbind(detection, data.frame(idx=i, event=output$drift, type=type))
}

# Print the positions where DDM detected drift.
detection[detection$type == 'drift',]

# Show the detected drifts over the original numeric signal.
plot(x=seq_len(nrow(data)), y=data$serie)
for (drift_index in detection[detection$type == 'drift', 'idx']) {
  abline(v=drift_index, col='red', lty=2)
}

Adapted EWMA for Concept Drift Detection (ECDD) method

Description

ECDD applies an exponentially weighted moving average (EWMA) control chart to the online classification error stream. Since it monitors predictive errors directly, it is primarily designed to detect real concept drift. The method follows Ross et al. (2012), who adapted EWMA charts for concept-drift detection in streaming classifiers https://doi.org/10.1016/j.patrec.2011.08.019.

Usage

dfr_ecdd(lambda = 0.2, min_run_instances = 30, average_run_length = 400)

Arguments

lambda

EWMA smoothing parameter

min_run_instances

The minimum number of instances before detecting change

average_run_length

Desired Average Run Length (ARL), i.e. the expected number of observations between two false alarms. The published control-limit polynomials exist for 100, 400 and 1000; other values use the next one up, and values above 1000 are rejected. The default changed from 100 to 400 in the development version, which reduced false alarms about sevenfold.

Details

Missing values are treated as correct predictions (0).

Value

dfr_ecdd object

References

Ross, G. J., Adams, N. M., Tasoulis, D. K., and Hand, D. J. (2012). Exponentially weighted moving average charts for detecting concept drift. Pattern Recognition Letters, 33(2), 191-198. https://doi.org/10.1016/j.patrec.2011.08.019

Examples

# Load Heimdall and the synthetic example stream.
library(heimdall)

# Fix the seed for reproducibility.
seed <- 1
set.seed(seed)

# Load the stream and derive the binary monitored signal.
data(st_drift_examples)
data <- st_drift_examples$uv_virtual_drift
data$prediction <- st_drift_examples$uv_virtual_drift$serie > 4

# Plot the binary stream that ECDD will monitor.
plot(x=seq_len(nrow(data)), y=data$prediction)

# Instantiate the ECDD detector.
model <- dfr_ecdd()

# Update the detector sequentially and store the detected alarms.
detection <- NULL
output <- list(obj=model, drift=FALSE)
for (i in seq_len(nrow(data))){
  output <- update_state(output$obj, data$prediction[i])
  if (output$drift){
    type <- 'drift'
    output$obj <- reset_state(output$obj)
  } else {
    type <- ''
  }
  detection <- rbind(detection, data.frame(idx=i, event=output$drift, type=type))
}

# Print the drift points signaled by ECDD.
detection[detection$type == 'drift',]

# Overlay the alarms on the original numeric signal.
plot(x=seq_len(nrow(data)), y=data$serie)
for (drift_index in detection[detection$type == 'drift', 'idx']) {
  abline(v=drift_index, col='red', lty=2)
}

Adapted Early Drift Detection Method (EDDM) method

Description

EDDM extends DDM by monitoring the distance between classification errors instead of only the error rate, which makes it more sensitive to gradual degradation. Because it operates on the model error stream, it is primarily intended for real concept drift. The method follows Baena-Garcia et al. (2006), who proposed EDDM for improved detection of gradual drift.

Usage

dfr_eddm(
  min_instances = 30,
  min_num_errors = 30,
  warning_level = 0.95,
  out_control_level = 0.9
)

Arguments

min_instances

The minimum number of instances before detecting change

min_num_errors

The minimum number of errors before detecting change

warning_level

Necessary level for warning zone

out_control_level

Necessary level for a positive drift detection

Details

EDDM monitors the distance between consecutive errors, which makes it sensitive to gradual drifts but also prone to false alarms when the error rate is high. warning_level must not be lower than out_control_level. Values must be 1 (error) or 0 (correct prediction), and missing values are treated as correct predictions (0).

Value

dfr_eddm object

References

Baena-Garcia, M., del Campo-Avila, J., Fidalgo, R., Bifet, A., Gavalda, R., and Morales-Bueno, R. (2006). Early drift detection method. In Fourth International Workshop on Knowledge Discovery from Data Streams.

Examples

# Load Heimdall and the built-in synthetic stream.
library(heimdall)

# Fix the seed so the results are reproducible.
seed <- 1
set.seed(seed)

# Load the stream and derive the binary monitored signal.
data(st_drift_examples)
data <- st_drift_examples$uv_virtual_drift
data$prediction <- st_drift_examples$uv_virtual_drift$serie > 4

# Visualize the binary stream that EDDM will monitor.
plot(x=seq_len(nrow(data)), y=data$prediction)

# Instantiate the EDDM detector.
model <- dfr_eddm()

# Process the stream sequentially and store each detected alarm.
detection <- NULL
output <- list(obj=model, drift=FALSE)
for (i in seq_len(nrow(data))){
  output <- update_state(output$obj, data$prediction[i])
  if (output$drift){
    type <- 'drift'
    output$obj <- reset_state(output$obj)
  } else {
    type <- ''
  }
  detection <- rbind(detection, data.frame(idx=i, event=output$drift, type=type))
}

# Print the drift alarms returned by EDDM.
detection[detection$type == 'drift',]

# Show those alarms on top of the original numeric series.
plot(x=seq_len(nrow(data)), y=data$serie)
for (drift_index in detection[detection$type == 'drift', 'idx']) {
  abline(v=drift_index, col='red', lty=2)
}

EI-kMeans stream detector

Description

Monitors a stream with an EI-kMeans partitioning (eikmeans()): the first n_train observations form the training sample, and every later window of window_size observations is tested against it. Since it monitors the distribution of the observed features, it is primarily used for virtual concept drift.

Usage

dfr_eikmeans(target_feat = NULL, n_train = 2000, window_size = 200, ...)

Arguments

target_feat

Names of the columns to be monitored. NULL (the default) monitors every numeric column.

n_train

Size of the training sample.

window_size

Size of the tested windows (non-overlapping).

...

Further arguments for eikmeans() (k, alpha, min_points, n_build, thetas).

Details

A drift is reported on the last observation of every window whose p-value is below alpha. reset_state() forgets the partitioning, and the next n_train observations train a new one, which is the adaptation the paper recommends after a drift. Rows with missing values are skipped.

Value

dfr_eikmeans object. After fit(), drifter_output holds the chi-square statistic and the p-value of every tested window (on its last observation), and obj$model the partitioning.

References

Liu, A., Lu, J. and Zhang, G. (2021). Concept drift detection via equal intensity k-means space partitioning. IEEE Transactions on Cybernetics, 51(6), 3198-3211. https://doi.org/10.1109/TCYB.2020.2983962

Examples

library(daltoolbox)
library(heimdall)
# Two clusters; after 700 rows the right one moves.
set.seed(1)
cluster <- function(n, x) data.frame(x1 = stats::rnorm(n, x), x2 = stats::rnorm(n))
stream <- rbind(cluster(350, 0), cluster(350, 5))[sample(700), ]
drifted <- rbind(cluster(150, 0), cluster(150, 6))[sample(300), ]
model <- fit(dfr_eikmeans(n_train = 500, window_size = 100, k = 10, min_points = 20),
             rbind(stream, drifted))
which(model$drifter_output$p_value < 0.05)

Ensemble drift detector (CEDD and FEDD)

Description

Combines the detections of several drift detectors by voting (Giusti Tavares et al., 2025). At every time step the vote is the sum of the members' scores, and the ensemble reports a drift when the vote passes the voting rule:

With tolerance k <= 1 the scores are crisp: 1 when the member detects a drift at that time step, 0 otherwise (crisp ensemble drift detector, CEDD). With k > 1 they are fuzzy (fuzzy ensemble drift detector, FEDD). A detection at time d gives time t the score ⁠1 - |t - d| / k⁠ when ⁠|t - d| < k⁠. A member's score is the largest over its detections. So detections that are close in time but not simultaneous can still add up to a majority.

Usage

dfr_ensemble(
  drifter_list,
  voting = c("majority", "efer", "threshold"),
  threshold = NULL,
  tolerance = 0,
  lookahead = TRUE
)

Arguments

drifter_list

Named list of drifters (dist_based or mv_dist_based) run in parallel on the stream.

voting

Voting rule: "majority" (default), "efer" or "threshold".

threshold

Vote needed by the "threshold" rule (lambda).

tolerance

Time tolerance k of the fuzzy scores; 0 (default) gives the crisp ensemble.

lookahead

With fuzzy scores, TRUE (default) uses detections on both sides of a time step, as in the paper. The vote of time t is then known only when t + k - 1 has arrived, so drifts are reported k - 1 observations after the time they refer to (obj$events holds those times). FALSE uses only the detections up to the current observation and reports at once.

Details

The combination follows the reference code (https://github.com/cefet-rj-dal/reproduce, fedd/core/4-ensemble-fuzzy.R, with the triangular fuzzification of harbinger):

Members with a target_feat receive that column of each row, the other univariate members the row mean, and multivariate members the row (as dfr_multi_criteria()). The members are not reset by the ensemble. The paper's members are also run as separate detectors, each with its own warm-up and normalisation, before the vote.

ensemble_vote() applies the same voting to detection series computed beforehand.

Value

dfr_ensemble object. After fit(), drifter_output holds, on every observation, the decision of each member, the time step whose vote was decided (time) and the vote (vote). obj$events holds the time steps of the ensemble drifts, including those decided when the stream ended.

References

Giusti Tavares, L., Lima, J., Melo, M., Chen, C., Garibaldi, J., Scatena, G. S., Costa, A. H. R., Gomi, E. S., Salles, R., Pacitti, E., Santos, I., Siqueira, I. G., Carvalho, D., Coutinho, R., Porto, F. and Ogasawara, E. (2025). Fuzzy-based ensemble method for robust concept drift detection in multivariate time series. 2025 International Joint Conference on Neural Networks (IJCNN). https://doi.org/10.1109/IJCNN64981.2025.11228919

See Also

ensemble_vote(), dfr_multi_criteria().

Examples

library(daltoolbox)
library(heimdall)
set.seed(1)
data <- data.frame(serie = c(stats::rnorm(500), stats::rnorm(500, 3)))
members <- list(ph = dfr_page_hinkley(), kswin = dfr_kswin(), adwin = dfr_adwin())
# Crisp majority: the members must agree on the same observation.
crisp <- fit(dfr_ensemble(members, voting = "majority"), data)
crisp$events
# Fuzzy majority with a tolerance of 50 observations.
fuzzy <- fit(dfr_ensemble(members, voting = "majority", tolerance = 50), data)
fuzzy$events

Fast likelihood-based change point detector for binary streams

Description

Error-based detector of Tatti (2019). The entries since the last change are modelled by one Bernoulli variable (M1) or split in two segments with their own Bernoulli variables (M2). After every entry the split that maximises the log-likelihood ratio of M2 over M1 is found among the border indices (blocks maintained by the pool adjacent violators update) with a (1 - \epsilon) approximation in O(\epsilon^{-1} \log^2 n) time; a change is declared when the ratio exceeds \sigma = \tau + \log n (BIC penalty plus tau), and the window then restarts from scratch.

Usage

dfr_fastlr(tau = 6, eps = 0)

Arguments

tau

Threshold parameter \tau (the paper uses 6).

eps

Approximation guarantee \epsilon in [0, 1); 0 tests every border index (exact).

Details

Values must be 1 (error) or 0 (correct prediction); missing values are treated as 0, as in the other error-based detectors. Unlike DDM, changes in both directions are detected. drifter_output has the score (log-likelihood ratio, natural logarithm) after every entry and, when a change is declared, the stream index of the estimated change point (the first entry of the second segment).

Value

dfr_fastlr object

References

Tatti, N. (2019). Fast likelihood-based change point detection. In Machine Learning and Knowledge Discovery in Databases (ECML PKDD 2019), 662-677. https://doi.org/10.1007/978-3-030-46150-8_39. arXiv:2301.08892.

Examples

library(daltoolbox)
library(heimdall)
set.seed(1)
x <- c(rbinom(1000, 1, 0.25), rbinom(1000, 1, 0.75), rbinom(1000, 1, 0.25))
detector <- fit(dfr_fastlr(tau = 6, eps = 0.1), x)
out <- detector$drifter_output
which(!is.na(out$change_point))     # when the changes were declared
out$change_point[!is.na(out$change_point)]   # estimated change points

GreedyKS drift detector

Description

Online one-sample Kolmogorov-Smirnov test of a numeric stream against a reference distribution, with the GreedyKS sketch of Cardoso and Galeno (2023): a drift is signalled when the p-value of the estimated statistic falls to alpha or below. The detector is used for virtual concept drift on a numeric feature, or on the error of a model.

Usage

dfr_greedyks(
  cdf = "norm",
  m = 100,
  alpha = 0.01,
  grace_period = m,
  reference_size = 1000,
  exact = TRUE,
  min_instances = 0,
  target_feat = NULL
)

Arguments

cdf

The reference distribution: a CDF (a function of a numeric vector, kept for the whole stream), or one of "norm", "exp" and "unif", whose parameters are fitted by maximum likelihood (as scipy.stats fit(): mean and standard deviation with divisor n; minimum and mean minus minimum; minimum and range) to the first reference_size observations, and again after every drift.

m

Number of buckets of the sketch (the memory units of the paper).

alpha

Significance level: drift when the p-value is ⁠<= alpha⁠.

grace_period

Number of observations processed before the test is applied (the paper tests once more observations than memory units were seen; the default is m). It counts from the start of the sketch, so with a fitted distribution it includes the reference observations.

reference_size

With a fitted distribution (cdf a name), the number of observations it is fitted to. They are also the first observations of the sketch, as in the call-center experiment of the paper.

exact

Exact distribution of the statistic (TRUE, the default, as the reference code) or the limiting distribution (FALSE); see ks_sf().

min_instances

Passed to greedyks().

target_feat

Feature to be monitored.

Details

After a drift, the sketch restarts empty (and, with a fitted distribution, the reference is fitted again to the next reference_size observations).

The output of each observation (drifter_output after fit()) has the estimated statistic D and its p-value p_value. For speed, when more than 140 observations were processed and ⁠n D^2 < 2.2⁠, the p-value is the Pelz-Good approximation instead of the exact Durbin matrix (its p-value there is above 0.02); with alpha >= 0.02 the exact value is used. The decisions are those of the exact test.

Value

dfr_greedyks object

References

Cardoso, D. O. and Galeno, T. D. (2023). Online evaluation of the Kolmogorov-Smirnov test on arbitrarily large samples. Journal of Computational Science, 67, 101959. https://doi.org/10.1016/j.jocs.2023.101959

Examples

library(daltoolbox)
library(heimdall)
set.seed(1)
x <- c(rnorm(500, 1, 1), rnorm(1000, 1.3, 1))
detector <- fit(dfr_greedyks(cdf = function(q) pnorm(q, 1, 1)), x)
which(detector$drifter_output$drift)
# reference fitted to the first 300 observations
detector <- fit(dfr_greedyks(cdf = "norm", reference_size = 300), x)
which(detector$drifter_output$drift)

Adapted Hoeffding Drift Detection Method (HDDM) method

Description

HDDM_A is a sequential detector based on Hoeffding's inequality that tests whether the mean of the monitored error stream has increased beyond statistically expected fluctuations. Because this implementation is error-based, it is primarily targeted at real concept drift. The theoretical basis follows Frias-Blanco et al. (2015) https://doi.org/10.1109/TKDE.2014.2345382.

Usage

dfr_hddm(
  drift_confidence = 0.001,
  warning_confidence = 0.005,
  two_side_option = TRUE
)

Arguments

drift_confidence

Confidence to the drift

warning_confidence

Confidence to the warning

two_side_option

Option to monitor error increments and decrements (two-sided) or only increments (one-sided)

Details

The detector reports increases of the error rate. With two_side_option = TRUE, a significant decrease restarts the statistics but is not reported as a drift. Values must be 1 (error) or 0 (correct prediction), and missing values are treated as correct predictions (0).

Value

dfr_hddm object

References

Frias-Blanco, I., del Campo-Avila, J., Ramos-Jimenez, G., Morales-Bueno, R., Ortiz-Diaz, A., and Caballero-Mota, Y. (2015). Online and nonparametric drift detection methods based on Hoeffding's bounds. IEEE Transactions on Knowledge and Data Engineering, 27(3), 810-823. https://doi.org/10.1109/TKDE.2014.2345382

Examples

# Load Heimdall and the synthetic stream example.
library(heimdall)

# Fix the seed for reproducibility.
seed <- 1
set.seed(seed)

# Load the stream and derive the binary monitored signal.
data(st_drift_examples)
data <- st_drift_examples$uv_virtual_drift
data$prediction <- st_drift_examples$uv_virtual_drift$serie > 4

# Plot the binary stream that HDDM_A will monitor.
plot(x=seq_len(nrow(data)), y=data$prediction)

# Instantiate the HDDM_A detector.
model <- dfr_hddm()

# Process the stream sequentially and record the detector alarms.
detection <- NULL
output <- list(obj=model, drift=FALSE)
for (i in seq_len(nrow(data))){
  output <- update_state(output$obj, data$prediction[i])
  if (output$drift){
    type <- 'drift'
    output$obj <- reset_state(output$obj)
  } else {
    type <- ''
  }
  detection <- rbind(detection, data.frame(idx=i, event=output$drift, type=type))
}

# Print the detected drift points.
detection[detection$type == 'drift',]

# Overlay the alarms on the original numeric stream.
plot(x=seq_len(nrow(data)), y=data$serie)
for (drift_index in detection[detection$type == 'drift', 'idx']) {
  abline(v=drift_index, col='red', lty=2)
}

Incremental Kolmogorov-Smirnov drift detector

Description

Unsupervised drift detection of dos Reis et al. (2016): for every monitored feature, a two-sample Kolmogorov-Smirnov test between a reference sample and the sliding window of the last window_size observations, computed incrementally with iks(). A drift is signalled when the test rejects the null hypothesis for at least one feature. The detector monitors virtual concept drift (the feature distribution), without labels.

Usage

dfr_iks(
  target_feat = NULL,
  window_size = 100,
  alpha = 0.001,
  ca = iks_ca(alpha),
  reference = c("fixed", "consecutive"),
  tie_break = TRUE,
  seed = NULL
)

Arguments

target_feat

Features to be monitored (by default every numeric column).

window_size

Size W of the reference sample and of the sliding window.

alpha

Significance level of the test.

ca

Coefficient of the critical value ⁠ca sqrt(2 / W)⁠; by default iks_ca(alpha), 1.9495 for alpha = 0.001 (the paper and the reference code use the table value 1.95).

reference

"fixed" (the default, the paper's method): the reference sample is the first W observations (the data the model was trained on) and the window starts as a copy of it; after a drift the reference becomes the current window. "consecutive": the reference is the window of the W observations before the current window (the consecutive sliding windows of Zliobaite, 2010, the CD baseline of the paper).

tie_break

Pair every observation with a random value to break ties (TRUE, the default, as IKSSW of the reference code); otherwise the statistic can be overestimated when values repeat, in particular while the window overlaps the reference.

seed

Seed of the private generator of the sketches.

Details

The output of each observation (drifter_output after fit()) has the statistic of every monitored feature (⁠D_<feature>⁠) and drift. After a drift with reference = "consecutive", both windows restart.

Value

dfr_iks object

References

dos Reis, D. M., Flach, P., Matwin, S. and Batista, G. (2016). Fast unsupervised online drift detection using incremental Kolmogorov-Smirnov test. In Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, 1545-1554. https://doi.org/10.1145/2939672.2939836

Zliobaite, I. (2010). Change with delayed labeling: when is it detectable? In 2010 IEEE International Conference on Data Mining Workshops, 843-850. https://doi.org/10.1109/ICDMW.2010.49

Examples

library(daltoolbox)
library(heimdall)
set.seed(1)
data <- data.frame(a = c(rnorm(600), rnorm(600, 1)), b = rnorm(1200))
detector <- fit(dfr_iks(window_size = 100, seed = 1), data)
which(detector$drifter_output$drift)

Inactive dummy detector

Description

Implements a dummy detector that never reports a drift. Useful as a lower baseline when evaluating adaptation strategies.

Usage

dfr_inactive()

Value

Drifter object

Examples

model <- dfr_inactive()
output <- update_state(model, 1)
output$drift

InDiD stream detector

Description

Monitors a stream with a trained indid() model: the observations are fed one by one to the recurrent network, and a drift is reported when the probability of change exceeds threshold. Since the model is trained on labelled sequences of the monitored features, it detects the kinds of change it was trained on (virtual concept drift of those features).

Usage

dfr_indid(model, threshold = 0.5, target_feat = NULL, horizon = NULL)

Arguments

model

A trained indid object.

threshold

Alarm threshold on the probability of change.

target_feat

Names of the columns fed to the model, in the order of training. NULL (the default) uses the model's feature names, or every numeric column when the model has none.

horizon

If set, the state of the network is reset every horizon observations, so that the stream is read as consecutive sequences of the training length (model$seq_len is a natural choice). NULL (default) never resets it except after a drift.

Details

After a drift the state of the network is reset, so the data after the change are read as the start of a new sequence. The model has learned what the beginning of a sequence without change looks like, so it keeps raising alarms if the new regime does not resemble it. Rows with missing values are skipped.

Value

dfr_indid object. After fit(), drifter_output holds the probability of change of every observation (probability).

References

Romanenkova, E., Stepikin, A., Morozov, M. and Zaytsev, A. (2022). InDiD: Instant disorder detection via a principled neural network. Proceedings of the 30th ACM International Conference on Multimedia, 3152-3162. https://doi.org/10.1145/3503161.3548182

Examples

library(daltoolbox)
library(heimdall)
set.seed(1)
make <- function(n) {
  change <- sample(2:32, n, replace = TRUE)
  change[seq_len(n / 2)] <- 33
  x <- t(vapply(change, function(c) stats::rnorm(32, ifelse(seq_len(32) < c, 1, 6)), numeric(32)))
  labels <- t(vapply(change, function(c) (seq_len(32) >= c) * 1, numeric(32)))
  list(x = x, labels = labels)
}
train <- make(200)
model <- indid(train$x, train$labels, T = 8, learning_rate = 0.02, epochs = 30, seed = 1)
stream <- data.frame(value = c(stats::rnorm(20, 1), stats::rnorm(10, 6)))
detector <- fit(dfr_indid(model), stream)
which(detector$drifter_output$probability > 0.5)[1]

KL Distance method

Description

This detector compares a reference and a recent window through the symmetrised Kullback-Leibler divergence of their binned empirical distributions, sum((p - q) * log(p / q)), which is the quantity also known as the Jeffreys divergence or, in the credit-risk literature, the Population Stability Index. It is multivariate: every monitored column contributes to the score. Because it monitors the distribution of the observed features rather than predictive error, it is primarily used for virtual concept drift. The statistical foundation is the divergence introduced by Kullback and Leibler (1951).

Usage

dfr_kldist(
  target_feat = NULL,
  window_size = 100,
  threshold = 0.12,
  window_type = "sliding",
  breaks = 20,
  monitoring_step = 1,
  data = NULL,
  p_th = NULL
)

Arguments

target_feat

Names of the columns to be monitored. NULL (the default) monitors every numeric column.

window_size

Size of the window

threshold

Drift threshold applied to the divergence. The default (0.12) was calibrated by simulation for the default window: on stationary normal data the divergence stayed below 0.1, while a shift of two standard deviations exceeded 0.13 in 90% of the runs. Shifts smaller than about one standard deviation are not separable from noise with 50-row halves; use a larger window to detect them.

window_type

Window policy. "sliding" (default) keeps at most window_size rows, so both halves move with the stream. "anchored" keeps every row, which pins the reference half to the beginning of the stream and makes memory grow with the stream length.

breaks

Number of bins used to discretise each feature before the divergence is computed.

monitoring_step

Number of rows between two consecutive evaluations. The default (1) evaluates at every row; larger values reduce the computational cost on long streams.

data

Already collected data to avoid cold start.

p_th

Deprecated name of threshold.

Details

Bins are built over the reference and recent halves together, so the two histograms are always comparable. Empty bins are smoothed before the logarithm is taken, and the score is averaged over bins and over features.

The detector consumes one row of a data frame at a time (a single value is also accepted). Rows whose monitored values are all missing are skipped instead of being imputed.

Value

dfr_kldist object

References

Kullback, S., and Leibler, R. A. (1951). On information and sufficiency. The Annals of Mathematical Statistics, 22(1), 79-86. https://doi.org/10.1214/aoms/1177729694

Examples

# Load Heimdall and the example data stream.
library(heimdall)

# Fix the seed to keep the example reproducible.
seed <- 1
set.seed(seed)

# Load the univariate stream monitored in this walkthrough.
data(st_drift_examples)
serie <- st_drift_examples$uv_virtual_drift

# Plot the monitored numeric signal before detection.
plot(x=seq_len(nrow(serie)), y=serie$serie)

# Instantiate the KL-divergence-based detector.
model <- dfr_kldist(window_size=100, threshold=0.10)

# Update the detector sequentially and store drift alarms.
detection <- NULL
output <- list(obj=model, drift=FALSE)
for (i in seq_len(nrow(serie))){
  output <- update_state(output$obj, serie[i, 'serie', drop=FALSE])
  if (output$drift){
    type <- 'drift'
    output$obj <- reset_state(output$obj)
  } else {
    type <- ''
  }
  detection <- rbind(detection, data.frame(idx=i, event=output$drift, type=type))
}

# Print the points where KLDIST detected drift.
detection[detection$type == 'drift',]
# Overlay the detected drifts on the original numeric stream.
plot(x=seq_len(nrow(serie)), y=serie$serie)
for (drift_index in detection[detection$type == 'drift', 'idx']) {
  abline(v=drift_index, col='red', lty=2)
}

KSWIN method

Description

KSWIN applies a Kolmogorov-Smirnov test between a recent window and a reference sample drawn from older observations. In this package, the method is primarily used for virtual concept drift, because it monitors distributional changes in a numeric feature stream. The method follows Raab et al. (2020) https://doi.org/10.1016/j.neucom.2019.11.111.

Usage

dfr_kswin(
  target_feat = NULL,
  window_size = 300,
  stat_size = 100,
  alpha = 1e-04,
  window_type = "sliding",
  monitoring_step = 1,
  exact = NULL,
  data = NULL,
  seed = NULL
)

Arguments

target_feat

Feature to be monitored.

window_size

Size of the sliding window. It must be greater than stat_size, and at least 2 * stat_size is recommended so that the reference sample is as large as the recent one.

stat_size

Size of the statistic window

alpha

Probability for the test statistic of the Kolmogorov-Smirnov-Test The alpha parameter is very sensitive, therefore should be set below 0.01.

window_type

Window policy. "sliding" (default) keeps at most window_size observations, so both the reference and the statistic halves move with the stream. "anchored" keeps every observation, which pins the reference sample to the beginning of the stream and makes memory grow with the stream length.

monitoring_step

Number of observations between two consecutive tests. The default (1) tests at every observation; larger values reduce the computational cost on long streams.

exact

Passed to stats::ks.test(). The default (NULL) lets R choose between the exact and the asymptotic test, which is much faster for windows of this size. Up to version 1.3.0 the default was TRUE.

data

Already collected data to avoid cold start.

seed

Seed of the random number stream used to subsample the reference window. When NULL (the default) it is drawn from the global random number generator once, when the detector is created.

Details

The reference window is randomly subsampled to stat_size observations. The detector keeps its own random number stream, so it does not change the global random state while it runs; set seed (or call base::set.seed() before creating the detector) for reproducible results.

A drift requires both a significant p-value and a KS statistic above sqrt(-log(alpha) / stat_size), as defined by Raab et al. Missing observations are skipped instead of being imputed.

Value

dfr_kswin object

References

Raab, C., Heusinger, M., and Schleif, F.-M. (2020). Reactive soft prototype computing for concept drift streams. Neurocomputing, 416, 340-351. https://doi.org/10.1016/j.neucom.2019.11.111

Examples

# Load Heimdall and the synthetic univariate stream.
library(heimdall)

# Fix the seed for reproducibility.
seed <- 1
set.seed(seed)

# Load the numeric stream used by the detector.
data(st_drift_examples)
serie <- st_drift_examples$uv_virtual_drift

# Plot the monitored variable before detection.
plot(x=seq_len(nrow(serie)), y=serie$serie)

# Instantiate KSWIN with explicit window parameters.
model <- dfr_kswin(target_feat='serie', window_size=100, stat_size=50)

# Update the detector sequentially and store the alarm positions.
detection <- NULL
output <- list(obj=model, drift=FALSE)
for (i in seq_len(nrow(serie))){
  output <- update_state(output$obj, serie$serie[i])
  if (output$drift){
    type <- 'drift'
    output$obj <- reset_state(output$obj)
  } else {
    type <- ''
  }
  detection <- rbind(detection, data.frame(idx=i, event=output$drift, type=type))
}

# Print the points where KSWIN raised drift alarms.
detection[detection$type == 'drift',]

# Overlay the detected drifts on the original stream.
plot(x=seq_len(nrow(serie)), y=serie$serie)
for (drift_index in detection[detection$type == 'drift', 'idx']) {
  abline(v=drift_index, col='red', lty=2)
}

Levene Based Drift Detection Method method

Description

LBDD is a window-based detector that compares the variability of a reference and a recent sample using Levene's test. Because it monitors changes in the distribution of an observed feature rather than model performance, it is primarily aimed at virtual concept drift. In this package, the detector follows the statistical-testing approach discussed by Giusti et al. (2021) for drift analysis, using Levene's variance test as its core mechanism.

Usage

dfr_lbdd(
  target_feat = NULL,
  alpha = 0.001,
  window_size = 300,
  window_type = "sliding",
  monitoring_step = 1,
  data = NULL
)

Arguments

target_feat

Feature to be monitored

alpha

Probability threshold for the test statistic

window_size

Size of the window

window_type

Window policy. "sliding" (default) keeps at most window_size observations, so both halves move with the stream. "anchored" keeps every observation, which pins the reference half to the beginning of the stream and makes memory grow with the stream length.

monitoring_step

Number of observations between two consecutive tests. The default (1) tests at every observation; larger values reduce the computational cost on long streams.

data

Already collected data to avoid cold start.

Details

LBDD only reacts to changes of spread (variance); a shift of the mean with the same spread is not detected, so combine it with dfr_mcdd() when both kinds of change matter. The test runs at every observation, so alpha should be small to keep false alarms rare.

Levene's test is computed with the group spread centred on the median (the Brown-Forsythe variant).

Missing observations are skipped instead of being imputed. When a drift is reported the window is trimmed to its most recent half; reset_state() empties it.

Value

dfr_lbdd object

References

Giusti, L., Carvalho, L., Gomes, A. T., Coutinho, R., Soares, J., and Ogasawara, E. (2021). Analysing flight delay under concept drift. Evolving Systems. https://doi.org/10.1007/s12530-021-09415-z

Examples

# Load Heimdall and the synthetic univariate stream.
library(heimdall)

# Fix the seed for reproducibility.
seed <- 1
set.seed(seed)

# Load the numeric stream monitored by the detector.
data(st_drift_examples)
serie <- st_drift_examples$uv_virtual_drift

# Plot the series before starting drift detection.
plot(x=seq_len(nrow(serie)), y=serie$serie)

# Instantiate the Levene-based detector.
model <- dfr_lbdd(target_feat='serie', window_size=100)

# Update the detector over the stream and record each drift alarm.
detection <- NULL
output <- list(obj=model, drift=FALSE)
for (i in seq_len(nrow(serie))){
  output <- update_state(output$obj, serie$serie[i])
  if (output$drift){
    type <- 'drift'
    output$obj <- reset_state(output$obj)
  } else {
    type <- ''
  }
  detection <- rbind(detection, data.frame(idx=i, event=output$drift, type=type))
}

# Print the positions where LBDD detected drift.
detection[detection$type == 'drift',]

# Overlay those drift points on the original numeric stream.
plot(x=seq_len(nrow(serie)), y=serie$serie)
for (drift_index in detection[detection$type == 'drift', 'idx']) {
  abline(v=drift_index, col='red', lty=2)
}

LLR2 drift detector

Description

Fully unsupervised drift detector of Sojo, Bielza and LarraƱaga (2027). A semiparametric Bayesian network (spbn()) is learned on a baseline of the stream. For every node i, the statistic ⁠Lambda_i = mean log f(x_i | pa_i)⁠ over the most recent sliding window minus the same mean over a fixed reference window is compared with the chi-square distribution with one degree of freedom, ⁠p_i = 1 - F(2 |Lambda_i|)⁠; a drift is reported when some p_i < alpha (or, with fdr = TRUE, when the Benjamini-Hochberg procedure rejects some node at level alpha: LLR2-BH). The nodes that drift are reported, and the network is updated.

Usage

dfr_llr2(
  target_feat = NULL,
  n_baseline = 4096,
  window_size = 250,
  step = 50,
  alpha = 0.05,
  fdr = FALSE,
  update = c("parameter", "parameter_sliding", "sliding", "none"),
  structure = NULL,
  node_types = NULL,
  max_parents = 4,
  folds = 5
)

Arguments

target_feat

Names of the columns to be monitored. NULL (the default) monitors every numeric column.

n_baseline

Size of the baseline: the first n_baseline - window_size observations learn the network (W_l) and the last window_size form the reference window (W_r).

window_size

Size of the sliding and reference windows (n_samples in the paper).

step

Stride of the sliding window: the test is run on observations whose position in the stream is a multiple of step.

alpha

Significance level.

fdr

TRUE for the Benjamini-Hochberg correction across nodes (LLR2-BH).

update

Update after a drift: "parameter" (default; the CPDs become the weighted geometric mean of CPDs fitted on the sliding window and on the learning window, Eq. 11-13), "parameter_sliding" (CPDs refitted on the sliding window), "sliding" (structure and CPDs learned again on the sliding window) or "none".

structure, node_types, max_parents, folds

Passed to spbn() for the baseline network.

Details

After a drift the reference window is emptied; the first full sliding window after the drift becomes the new reference window (its mean log-likelihood under the updated network) and tests resume at the next stride. This reproduces the spacing of the detections of the reference results (at least window_size + step observations between two drifts).

The "parameter" update follows Section 4.3: for every node, the CPD fitted on the sliding window (target, weight ⁠eta = window_size / |W_l|⁠) is combined with the CPD fitted on the learning window (source, weight 1 - eta); if the risk ⁠|L_T| - |L_S|⁠ (cross-validated log-likelihood of the sliding window under the target CPD against its log-likelihood under the source) is not positive, the source is dropped (eta = 1). The structure is kept; the paper also relearns the structure around the drifted nodes by hill climbing with transfer learning (HC-TL), which is not implemented. Its ablation (Fig. 12) shows that detection is driven by the statistic, with equivalent results for the parameter and sliding updates.

Value

dfr_llr2 object. After fit(), drifter_output holds, for every observation, its log-likelihood under the network in use (loglik) and, on tested observations, the p-value of every node (⁠p_<node>⁠); obj$drifts lists the drifts with their nodes, and obj$network the current network.

References

Sojo, R., Bielza, C. and LarraƱaga, P. (2027). A fully unsupervised concept drift detector via Bayesian networks for machine condition monitoring. Expert Systems with Applications, 332, 133634. https://doi.org/10.1016/j.eswa.2026.133634

See Also

spbn()

Examples

library(daltoolbox)
library(heimdall)
set.seed(1)
n <- 3000
a <- stats::rnorm(n)
b <- a + stats::rnorm(n, sd = 0.5)
b[2001:n] <- b[2001:n] + 2
detector <- dfr_llr2(n_baseline = 1000, window_size = 200, step = 50)
model <- fit(detector, data.frame(a, b))
model$drifts

Maximum Concept Discrepancy drift detector (MCD-DD)

Description

Unsupervised online drift detector of Wan, Liang and Yoon (2024). A sliding window of window_size observations is split into n_sub sub-windows. Sets of m points sampled from a sub-window are embedded by a small neural network as the mean of the point encodings (the concept representation), and the maximum concept discrepancy (MCD) between two sub-windows is the distance between their representations. Every time a new sub-window arrives, its MCD to the previous sub-window is compared with a threshold; then the encoder is trained on the window by contrastive learning: sets from the same sub-window are pulled together, and sets with noise added (weak negatives, same sub-window; strong negatives, first and last sub-windows) pushed apart. The threshold is the percentile quantile of the MCD between sets of the same sub-window. Since it monitors the distribution of the observed features, it is used for virtual concept drift.

Usage

dfr_mcd(
  target_feat = NULL,
  window_size = 3000,
  n_sub = 10,
  m = 30,
  k = 10,
  hidden_size = 100,
  output_size = 100,
  eps_small = 1,
  eps_big = 10,
  learning_rate = 0.005,
  epochs = 1,
  temperature = 0.1,
  lambda = 1,
  percentile = 0.95,
  seed = NULL
)

Arguments

target_feat

Names of the columns to be monitored. NULL (the default) monitors every numeric column.

window_size

Size of the sliding window (a multiple of n_sub).

n_sub

Number of sub-windows in a window; the window slides by one sub-window (window_size / n_sub observations).

m

Number of points in a sample set.

k

Number of sample sets drawn from a sub-window (even).

hidden_size, output_size

Sizes of the hidden and output layers of the encoder.

eps_small, eps_big

Standard deviations of the Gaussian noise of the weak and strong negative sets.

learning_rate

Learning rate of the Adam optimiser.

epochs

Optimisation steps per window.

temperature

Temperature of the InfoNCE-like loss.

lambda

Weight of the gradient penalty that keeps the encoder close to 1-Lipschitz.

percentile

Quantile of the within-sub-window MCD used as threshold.

seed

Seed of the private random stream (initial weights, sampling and noise). NULL draws one from the session.

Details

The detector follows the reference code (https://github.com/LiangYiAnita/mcd-dd, mcd.py, encoder.py and main.py), which differs from the paper in some points:

The data are not scaled, as in the reference; the noise levels refer to the units of the data. The network, its gradients (including the second derivatives of the gradient penalty) and Adam are written in R.

Value

dfr_mcd object. After fit(), drifter_output holds, on the last observation of every tested sub-window, its MCD to the previous sub-window (mcd) and the threshold (threshold); obj$distances has one row per tested sub-window with its MCD to each earlier sub-window of the window (the heatmaps of the paper).

References

Wan, K., Liang, Y. and Yoon, S. (2024). Online drift detection with maximum concept discrepancy. Proceedings of the 30th ACM SIGKDD Conference on Knowledge Discovery and Data Mining, 2924-2935. https://doi.org/10.1145/3637528.3672016

See Also

dfr_mcdd() is a different detector (mean comparison).

Examples


library(daltoolbox)
library(heimdall)
# Mixture of two Gaussians whose weight changes at row 4001.
set.seed(1)
mixture <- function(n, p) {
  wide <- stats::runif(n) > p
  matrix(stats::rnorm(n * 3, 20, ifelse(wide, 50, 10)), n)
}
stream <- as.data.frame(rbind(mixture(4000, 0.2), mixture(2000, 0.8)))
detector <- dfr_mcd(window_size = 1000, m = 30, seed = 1)
model <- fit(detector, stream)
output <- model$drifter_output
which(output$mcd > output$threshold)


Mean Comparison Distance method

Description

MCDD is a window-based detector that compares the location of a reference and a recent sample by means of a hypothesis test on their central tendency. Because it monitors the distribution of an observed feature rather than predictive errors, it is primarily intended for virtual concept drift. In this package, the detector follows the statistical-testing perspective adopted by Giusti et al. (2021) for drift analysis.

Usage

dfr_mcdd(
  target_feat = NULL,
  alpha = 1e-04,
  normality_alpha = 0.05,
  window_size = 300,
  window_type = "sliding",
  monitoring_step = 1,
  data = NULL
)

Arguments

target_feat

Feature to be monitored

alpha

Probability threshold for the comparison test

normality_alpha

Significance level of the Shapiro-Wilk normality test used to decide between the parametric and the nonparametric comparison. It is deliberately separate from alpha, since the two thresholds answer different questions.

window_size

Size of the window

window_type

Window policy. "sliding" (default) keeps at most window_size observations, so both halves move with the stream. "anchored" keeps every observation, which pins the reference half to the beginning of the stream and makes memory grow with the stream length.

monitoring_step

Number of observations between two consecutive tests. The default (1) tests at every observation; larger values reduce the computational cost on long streams.

data

Already collected data to avoid cold start.

Details

MCDD only reacts to changes of location (mean or median); a change of spread with the same centre is not detected, so combine it with dfr_lbdd() when both kinds of change matter.

Normality of both halves of the window is checked with stats::shapiro.test(); when it holds, a t-test is applied, otherwise a Wilcoxon rank-sum test is used. Shapiro-Wilk is only defined for samples of at most 5000 observations, so larger windows always fall back to the nonparametric test.

Missing observations are skipped instead of being imputed.

Value

dfr_mcdd object

References

Giusti, L., Carvalho, L., Gomes, A. T., Coutinho, R., Soares, J., and Ogasawara, E. (2021). Analysing flight delay under concept drift. Evolving Systems. https://doi.org/10.1007/s12530-021-09415-z

Examples

# Load Heimdall and the synthetic stream.
library(heimdall)

# Fix the seed to keep the walkthrough reproducible.
seed <- 1
set.seed(seed)

# Load the univariate series monitored in this example.
data(st_drift_examples)
serie <- st_drift_examples$uv_virtual_drift

# Plot the monitored signal before running the detector.
plot(x=seq_len(nrow(serie)), y=serie$serie)

# Instantiate the mean-comparison detector.
model <- dfr_mcdd(target_feat='serie', window_size=100)

# Update the detector sequentially and collect the alarm positions.
detection <- NULL
output <- list(obj=model, drift=FALSE)
for (i in seq_len(nrow(serie))){
  output <- update_state(output$obj, serie$serie[i])
  if (output$drift){
    type <- 'drift'
    output$obj <- reset_state(output$obj)
  } else {
    type <- ''
  }
  detection <- rbind(detection, data.frame(idx=i, event=output$drift, type=type))
}

# Print the detected drift points.
detection[detection$type == 'drift',]

# Overlay the detected drifts on the original series.
plot(x=seq_len(nrow(serie)), y=serie$serie)
for (drift_index in detection[detection$type == 'drift', 'idx']) {
  abline(v=drift_index, col='red', lty=2)
}

Multimodal QuantTree stream detector

Description

Monitors a stream with a Multimodal QuantTree (mmqt()): the observations are grouped in consecutive batches of nu rows, the first n_train_batches batches train the model, and every later batch is tested. Since it monitors the distribution of the observed features, it is primarily used for virtual concept drift.

Usage

dfr_mmqt(target_feat = NULL, nu = 128, n_train_batches = 64, model = NULL, ...)

Arguments

target_feat

Names of the columns to be monitored. NULL (the default) monitors every numeric column.

nu

Number of observations per batch.

n_train_batches

Number of batches used for training. Ignored when model is given.

model

A trained mmqt() model. When given, every batch is tested and reset_state() keeps the model.

...

Further arguments for mmqt() (bins, alpha, n_modalities, alpha_modalities, max_modalities, calibration, n_repeats, n_sim, seed).

Details

Each batch is tested on its own (MMQT is a one-shot test, with a false positive rate alpha per batch), so the detector reports a drift on the last observation of every batch whose statistic exceeds the threshold of its modality. reset_state() forgets the model it trained and trains a new one on the next n_train_batches batches. Rows with missing values are skipped.

Value

dfr_mmqt object. After fit(), drifter_output holds, on the last observation of every tested batch, the assigned modality, the statistic and the threshold, and obj$model the trained model.

References

Stucchi, D., Magri, L., Carrera, D. and Boracchi, G. (2023). Multimodal batch-wise change detection. IEEE Transactions on Neural Networks and Learning Systems, 34(10), 6783-6797. https://doi.org/10.1109/TNNLS.2023.3294846

Boracchi, G., Carrera, D., Cervellera, C. and Maccio, D. (2018). QuantTree: histograms for change detection in multivariate data streams. Proceedings of the 35th International Conference on Machine Learning, PMLR 80, 639-648.

Examples

library(daltoolbox)
library(heimdall)
# Batches alternate between two modes; from batch 50 the first mode moves.
set.seed(1)
batch <- function(center) data.frame(x = stats::rnorm(64, center), y = stats::rnorm(64, center))
centers <- c(rep(c(0, 4), 25), rep(c(1.5, 4), 10))
stream <- do.call(rbind, lapply(centers, batch))
detector <- dfr_mmqt(nu = 64, n_train_batches = 40, bins = 8, n_repeats = 2, n_sim = 2000, seed = 1)
model <- fit(detector, stream)
model$model$n_modalities
which(model$drifter_output$statistic > model$drifter_output$threshold) %/% 64

Multi Criteria Drifter sub-class

Description

Combines the output of several drift detectors into a single decision.

Usage

dfr_multi_criteria(drifter_list, combination = "or", fuzzy_window = 10)

Arguments

drifter_list

Named list of drifters to combine. Every element must inherit from either dist_based or mv_dist_based.

combination

How the drifters will be combined. One of 'or' (default), 'and' or 'fuzzy'.

fuzzy_window

Number of observations during which a detection is still taken into account by the 'and' and 'fuzzy' combinations.

Details

After a combined drift is reported, the past detections are forgotten, so a single change is reported once. Detectors with a target_feat receive that column of each row; the other univariate detectors receive the row mean.

obj$detections counts the drifts reported by each detector and obj$last_drifts holds their decisions on the last observation.

Value

Drifter object

Examples

library(daltoolbox)
library(heimdall)

set.seed(1)
data <- data.frame(serie = c(stats::rnorm(100), stats::rnorm(100, mean = 10)))

model <- dfr_multi_criteria(
  drifter_list = list(
    ph = dfr_page_hinkley(),
    ph_sensitive = dfr_page_hinkley(threshold = 10)
  ),
  combination = "or"
)

model <- fit(model, data)
model$drifted
model$detections

onlineBcp stream detector

Description

Monitors a univariate stream with the online Bayesian change point detection of online_bcp(): every observation updates the posterior of the location of the last change point, and a drift is reported when the largest posterior exceeds threshold at a new location. Since it monitors the distribution of a feature, it is used for virtual concept drift.

Usage

dfr_onlinebcp(
  target_feat = NULL,
  theta = 0.9,
  alpha = 1,
  beta = 1,
  threshold = 0.5,
  numerics = c("stable", "reference"),
  max_run = NULL
)

Arguments

target_feat

Feature to be monitored.

theta

Probability that no change occurs at a step.

alpha, beta

Hyperparameters of the inverse-gamma prior of the variance.

threshold

Threshold of the posterior probability (th_cp).

numerics

"stable" (default) computes the weights in log scale with lgamma(). "reference" computes them as onlineBcp 0.1.4 does, with gamma() and powers that overflow for segments longer than about 340 observations; the overflowing weights are set to 0, which forces change points at multiples of about 341 observations (see Details).

max_run

If set, the posterior is kept for at most the last max_run candidate locations (the oldest are dropped), which bounds the cost of a step on long streams without changes. NULL (default) keeps them all, as the reference.

Details

The detector reports a drift on the observation at which a new change point location is found; that location (the last observation before the change) is kept in obj$changepoints with its posterior probability. The data are assumed approximately normal within segments; transform them first otherwise (for counts, sqrt(y + 3/8), as in the paper). Missing values are skipped.

Value

dfr_onlinebcp object. After fit(), drifter_output holds the largest posterior probability (max_prob) and the location found (location, 0 when below the threshold) for every observation.

References

Yigiter, A., Chen, J., An, L. and Danacioglu, N. (2015). An on-line CNV detection method for short sequencing reads. Journal of Applied Statistics, 42(7), 1556-1571. https://doi.org/10.1080/02664763.2014.1001330

Xu, H., Yigiter, A. and Chen, J. (2022). onlineBcp: An R package for online change point detection using a Bayesian approach. SoftwareX, 17, 100999. https://doi.org/10.1016/j.softx.2022.100999

Examples

library(daltoolbox)
library(heimdall)
set.seed(1)
data <- data.frame(serie = c(stats::rnorm(100, 0), stats::rnorm(100, 3)))
model <- fit(dfr_onlinebcp(theta = 0.95, threshold = 0.7), data)
model$changepoints

Parallel Activations Drift Detector (PADD)

Description

Unsupervised batch drift detector of Komorniczak and Ksieniewicz (2024). The data stream is processed in chunks of chunk_size observations, each passed through a randomly initialised, never trained neural network (one hidden ReLU layer of hidden units, outputs ReLU outputs and a softmax, weights drawn from N(0, 0.1)). For every output, replications Student t-tests compare a sample of sample_size activations of the current chunk with a sample of the activations stored since the last drift (both drawn with replacement). A drift is reported when more than threshold * outputs * replications tests are significant at level alpha; the stored activations are then cleared. Since it monitors the inputs only, it is used for virtual concept drift.

Usage

dfr_padd(
  target_feat = NULL,
  chunk_size = 200,
  alpha = 0.05,
  threshold = 0.17,
  outputs = 30,
  replications = 35,
  sample_size = 75,
  hidden = 10,
  seed = NULL,
  weights = NULL
)

Arguments

target_feat

Names of the columns to be monitored. NULL (the default) monitors every numeric column.

chunk_size

Number of observations of a chunk (the batches of the paper, 200 in its experiments).

alpha

Significance level of the t-tests.

threshold

Fraction of significant tests above which a drift is reported.

outputs

Number of outputs of the network (e).

replications

Number of t-tests per output (r).

sample_size

Size of the samples drawn for every test (s).

hidden

Number of units of the hidden layer.

seed

Seed of the network weights and of the samples. NULL draws it from the global generator when the detector is created; the global random state is left unchanged.

weights

Optional fixed network: a list with the hidden layer (⁠(n_features + 1) x hidden⁠, the last row is the bias) and the output layer (⁠hidden x outputs⁠). By default it is drawn on the first chunk.

Details

The defaults are those of the reference implementation (https://github.com/w4k2/padd, methods.py). The paper's experiments use outputs = 12, replications = 12, sample_size = 50, and ⁠alpha = 0.07, threshold = 0.19⁠ for sudden drifts or ⁠alpha = 0.13, threshold = 0.26⁠ for gradual ones.

As in the reference, the first chunk is only stored; after a drift the stored activations are replaced by those of the drifting chunk; the t-test is the pooled-variance (Student) test, and a test whose two samples are constant (undefined p-value) is not significant. The drift is reported on the last observation of the chunk. Rows with missing values are dropped. reset_state() clears the stored activations and keeps the network.

Value

dfr_padd object. After fit(), drifter_output holds, on the last observation of every chunk, the fraction of significant tests (significant), and obj$weights the network.

References

Komorniczak, J. and Ksieniewicz, P. (2024). Unsupervised concept drift detection based on parallel activations of neural network. arXiv:2404.07776.

Examples

library(daltoolbox)
library(heimdall)
set.seed(1)
# 12 chunks of 200 observations; the mean of 3 of the 10 features moves at chunk 7.
x <- matrix(stats::rnorm(2400 * 10), ncol = 10)
x[1201:2400, 1:3] <- x[1201:2400, 1:3] + 1
detector <- dfr_padd(outputs = 12, replications = 12, sample_size = 50,
                     alpha = 0.07, threshold = 0.19, seed = 1)
model <- fit(detector, as.data.frame(x))
which(!is.na(model$drifter_output$significant) & model$drifter_output$significant > 0.19)

Adapted Page Hinkley method

Description

The Page-Hinkley test is a sequential change-point detector that monitors the cumulative deviation of a signal from its running mean and signals a change when that deviation departs from its running minimum by more than a threshold. In this package, the implementation is primarily used for virtual concept drift when it monitors a numeric feature stream, although the same statistic can also be applied to error streams to detect real concept drift. The method is based on Page (1954).

Usage

dfr_page_hinkley(
  target_feat = NULL,
  min_instances = 30,
  delta = 0.005,
  threshold = 50,
  alpha = 1 - 1e-04,
  direction = "increase"
)

Arguments

target_feat

Feature to be monitored.

min_instances

The minimum number of instances before detecting change

delta

The delta factor for the Page Hinkley test

threshold

The change detection threshold (lambda)

alpha

The forgetting factor, used to weight the observed value and the mean

direction

Which changes of the mean are detected: "increase" (the default, as in the reference implementation), "decrease" or "both".

Details

Missing observations are skipped instead of being imputed.

Value

dfr_page_hinkley object

References

Page, E. S. (1954). Continuous inspection schemes. Biometrika, 41(1/2), 100-115. https://doi.org/10.2307/2333009

Examples

# Load Heimdall and the synthetic stream example.
library(heimdall)

# Fix the seed for reproducibility.
seed <- 1
set.seed(seed)

# Load the univariate numeric stream monitored in this example.
data(st_drift_examples)
serie <- st_drift_examples$uv_virtual_drift

# Plot the monitored signal before detection.
plot(x=seq_len(nrow(serie)), y=serie$serie)

# Instantiate the Page-Hinkley detector.
model <- dfr_page_hinkley(target_feat='serie')

# Update the detector sequentially and record every drift alarm.
detection <- NULL
output <- list(obj=model, drift=FALSE)
for (i in seq_len(nrow(serie))){
  output <- update_state(output$obj, serie$serie[i])
  if (output$drift){
    type <- 'drift'
    output$obj <- reset_state(output$obj)
  } else {
    type <- ''
  }
  detection <- rbind(detection, data.frame(idx=i, event=output$drift, type=type))
}

# Print the detected drift points.
detection[detection$type == 'drift',]

# Overlay those alarms on the original numeric stream.
plot(x=seq_len(nrow(serie)), y=serie$serie)
for (drift_index in detection[detection$type == 'drift', 'idx']) {
  abline(v=drift_index, col='red', lty=2)
}

print(paste('Successfull run at', Sys.time()))

Passive dummy detector

Description

Implements a dummy detector that always reports a drift. Useful as an upper baseline, since it forces the model to be retrained at every batch.

Usage

dfr_passive()

Value

Drifter object

Examples

model <- dfr_passive()
output <- update_state(model, 1)
output$drift

PROTON: prototype-based test-time online OOD detection

Description

Online out-of-distribution (OOD) detector for the outputs of a frozen classifier with an embedding space, such as a medical vision-language model (Das et al., 2026). Each observation is one input scored by the model: its embedding and its class probabilities. PROTON keeps a bank of the most recent confidently classified embeddings of each class, scores each input by its cosine distance to the nearest class prototype, and fuses that distance with the Maximum Concept Matching (MCM) score, -max(p), using a weight driven by the running variance of the MCM score. It needs no training data, labels or model changes.

Usage

dfr_proton(
  embedding_cols,
  prob_cols,
  score_col = NULL,
  gamma = 0.7,
  bank_size = 100,
  k_min = 5,
  alpha_min = 0.3,
  alpha_max = 0.7,
  sigma2_0 = 0.02,
  threshold = NULL
)

Arguments

embedding_cols

Names of the columns holding the embedding.

prob_cols

Names of the columns holding the class probabilities (one per in-distribution class), in the same order for every observation.

score_col

Optional column with another base OOD score (higher means more OOD), used instead of the MCM score -max(p). The probabilities are still used by the confidence gate.

gamma

Confidence gate: an embedding enters the bank of its predicted class only when max(p) >= gamma.

bank_size

Maximum number of embeddings kept per class (M); the oldest one is dropped first.

k_min

Number of embeddings every class needs before the prototype distance is used. Until then the score is the base score alone.

alpha_min, alpha_max

Range of the weight of the base score in the fusion.

sigma2_0

Reference variance of the base score on in-distribution data.

threshold

Optional threshold on the fused score. When given, an observation with a score above it is reported as a drift (an OOD input); when NULL (default) no drift is reported and the scores are only exposed through drifter_output.

Details

For each observation x_t, with \ell_2-normalized embedding e_t and probabilities p_t (Algorithm 1 of the paper):

  1. the base score S_{MCM} = -\max_c p_{t,c} updates its running variance \sigma^2_t (Welford's algorithm);

  2. once every class bank holds k_min embeddings, the prototype distance is S_{proto} = 1 - \max_c e_t^\top \mu_c, where \mu_c is the normalized mean of the bank of class c;

  3. the weight is \alpha_t = \alpha_{max} - \mathrm{sigmoid}(100 (\sigma^2_t - \sigma^2_0)) (\alpha_{max} - \alpha_{min}) and the score is S_t = \alpha_t S_{MCM} + (1 - \alpha_t) S_{proto}; before calibration S_t = S_{MCM};

  4. finally, when \max_c p_{t,c} \ge \gamma, e_t enters the bank of the predicted class.

A variance that rises above the in-distribution reference (for instance when confidently misclassified, covariate-shifted inputs arrive) moves the weight towards the prototype distance.

Rows with a missing embedding or probability value are skipped. obj$drifter_output holds, for the rows of the last fit(), the fused score, the base_score, the proto_score, the weight alpha, the running variance, whether the detector was calibrated, the predicted class and whether the embedding was enqueued.

Value

dfr_proton object

References

Das, A., Wasalathilaka, N., Lu, Y., Dukre, A., Mahapatra, D., Khan, S., and Razzak, I. (2026). PROTON: Prototype-Based Test-Time Online OOD Detection for Medical VLMs. arXiv:2606.20913.

Ming, Y., Cai, Z., Gu, J., Sun, Y., Li, W., and Li, Y. (2022). Delving into out-of-distribution detection with vision-language representations. Advances in Neural Information Processing Systems, 35, 35087-35102.

Examples

library(daltoolbox)
library(heimdall)

# Two in-distribution classes in a 3-dimensional embedding space, followed
# by covariate-shifted inputs: they are classified as confidently as the
# in-distribution ones, but their embeddings lie elsewhere.
set.seed(1)
make_rows <- function(n, center, p1) {
  e <- sweep(matrix(stats::rnorm(3 * n, sd = 0.05), n), 2, center, "+")
  data.frame(e1 = e[, 1], e2 = e[, 2], e3 = e[, 3], p1 = p1, p2 = 1 - p1)
}
stream <- rbind(
  make_rows(50, c(1, 0, 0), 0.9),
  make_rows(50, c(0, 1, 0), 0.1),
  make_rows(20, c(0, 0, 1), 0.9)
)

detector <- dfr_proton(embedding_cols = c("e1", "e2", "e3"), prob_cols = c("p1", "p2"))
detector <- fit(detector, stream)
tail(detector$drifter_output[, c("score", "base_score", "proto_score", "alpha")])

PSI stream detector

Description

Monitors a stream with the Population Stability Index (psi()): the first n_reference observations form the baseline, and every later window of window_size observations is compared with it, feature by feature. Since it monitors the distribution of the observed features, it is primarily used for virtual concept drift, and fits the paper's setting of validating the fields of incoming data files against a baseline file.

Usage

dfr_psi(
  target_feat = NULL,
  n_reference = 1000,
  window_size = 1000,
  bins = 10,
  threshold = 0.25
)

Arguments

target_feat

Names of the columns to be monitored. NULL (the default) monitors every numeric column.

n_reference

Size of the baseline.

window_size

Size of the compared windows (non-overlapping).

bins

Number of quantile groups of the baseline (10 for deciles, 20 for demi-deciles).

threshold

A drift is reported when the PSI of some feature exceeds it. The default, 0.25, is the paper's limit of a significant drift; 0.1 also flags the moderate ones. See psi() for the PSI of samples without drift, which grows as the windows get smaller.

Details

A drift is reported on the last observation of every window whose largest PSI exceeds threshold. reset_state() forgets the baseline, and the next n_reference observations form a new one. Missing values are kept: in the windows they count as observations in no bin (see psi()).

Value

dfr_psi object. After fit(), drifter_output holds the PSI of every feature (⁠psi_<feature>⁠) on the last observation of every window, and obj$reference the baseline.

References

Kurian, J. F. and Allali, M. (2024). Detecting drifts in data streams using Kullback-Leibler (KL) divergence measure for data engineering applications. Journal of Data, Information and Management, 6, 207-216. https://doi.org/10.1007/s42488-024-00119-y

Examples

library(daltoolbox)
library(heimdall)
# Scores around 610; from row 3001 half of those above 643 drop by 200.
set.seed(1)
score <- stats::rnorm(5000, 610, 50)
late <- 3001:5000
drop <- late[score[late] > 643 & stats::runif(2000) < 0.5]
score[drop] <- score[drop] - 200
# The PSI reaches about 0.2: a moderate drift, flagged with threshold 0.1.
detector <- dfr_psi(n_reference = 2000, window_size = 500, threshold = 0.1)
model <- fit(detector, data.frame(cbm = score))
model$drifter_output[!is.na(model$drifter_output$psi_cbm), , drop = FALSE]
model$drifted

Quadtree spatial mapping drift detector (QTS)

Description

Unsupervised, model-independent detector that maps the most recent observations onto a height-limited d-dimensional quadtree and monitors its occupancy, the number of occupied leaves, as a univariate curve (Ramos et al., 2024). A drift is signalled when the occupancy moves away from the reference of the current concept or when its first derivative changes. Since it monitors the distribution of the observed features, it is primarily used for virtual concept drift.

Usage

dfr_qts(
  target_feat = NULL,
  height = 4,
  window_size = 500,
  reference_size = 1500,
  recent = 0.1,
  alpha = 1,
  beta = 3,
  lower = 0,
  upper = 1,
  derivative_rule = c("code", "paper")
)

Arguments

target_feat

Names of the columns to be monitored. NULL (the default) monitors every numeric column.

height

Height of the quadtree: the number of times the feature space is halved along every dimension.

window_size

Size of the sliding window W of observations mapped onto the quadtree.

reference_size

Size of the occupancy windows: the reference window Rw, the summarized sliding window Sw and the derivative window ⁠f'(Sw)⁠.

recent

Share of window_size that forms the recent part of the derivative window (RD); the rest is the old part (OD).

alpha

Multiplier of the standard deviation of the old derivatives in the derivative strategy.

beta

Multiplier of the standard deviation of the reference occupancy in the occupancy strategy.

lower, upper

Bounds used to min-max scale the features to ⁠[0, 1]⁠ before they are mapped, one value for every feature or one per monitored feature. The quadtree covers the unit hypercube; values outside it fall in the outermost cells. The defaults assume data already scaled to ⁠[0, 1]⁠.

derivative_rule

Drift condition of the derivative strategy. "code" (the default) follows the reference implementation, ⁠|mean(RD)| > mean(OD) + alpha * sd(OD)⁠; "paper" follows the paper and its pseudocode, ⁠|mean(RD) - mean(OD)| > alpha * sd(OD)⁠.

Details

At each observation the window W is mapped onto a quadtree of height height whose cells are split while they hold more than one observation; the observations of a cell at the maximum height are summarized by their mean. The occupancy is the number of leaves, so it grows when the data spread over the feature space and shrinks when they concentrate.

Once the window is full, the first reference_size occupancy values form the reference window Rw of the concept. Two strategies then run in parallel:

When the window is small compared with the number of cells (⁠2^(height d)⁠), nearly every observation has a leaf of its own, the occupancy rarely changes and the standard deviation of the derivatives is small, so the derivative strategy reacts to noise. Keep the default windows or lower the height in that case.

The occupancy is computed from the cell counts of every level, without building the tree, and gives the same number of leaves as the reference implementation. The implementation follows the reference code (https://github.com/beraram/QTS-method), whose default parameters are used here; the paper recommends a window of 1000 observations for most cases. Rows whose monitored values are all missing are skipped; missing values in the other rows are placed in the lowest cell.

Value

dfr_qts object. After fit(), obj$detections holds the observation and the strategy ("occupancy" or "derivative") of every drift, and drifter_output the occupancy, its moving average and the derivative statistics of every observation.

References

Ramos, B. A., Castro, C. L., Coelho, T. A. and Angelov, P. P. (2024). Unsupervised drift detection using quadtree spatial mapping. ESANN 2024 proceedings, 467-472.

Coelho, R., Torres, L. and Castro, C. (2023). Concept drift detection with quadtree-based spatial mapping of streaming data. Information Sciences, 625, 578-592.

Examples

library(daltoolbox)
library(heimdall)
# Two clusters in the unit square that spread over it after 3000 rows.
set.seed(1)
n <- 3000
before <- data.frame(x = stats::rnorm(n, 0.3, 0.05), y = stats::rnorm(n, 0.3, 0.05))
after <- data.frame(x = stats::runif(n), y = stats::runif(n))
model <- fit(dfr_qts(window_size = 200, reference_size = 600), rbind(before, after))
model$detections
plot(model$drifter_output$occupancy, type = "l", ylab = "Occupancy")
abline(v = model$detections$observation, lty = 2)

Student-Teacher Unsupervised Drift Detection (STUDD)

Description

Unsupervised drift detector of Cerqueira, Gomes, Bifet and Torgo (2023). A classifier (the teacher) is trained on an initial window of window_size labelled observations, and a second classifier (the student) is trained on the same observations to mimic the teacher, with the teacher's predictions as its target. After that no label is used: every new observation is predicted by both models, and the mimicking error (1 when the student disagrees with the teacher, 0 otherwise) feeds a change detector, by default the Page-Hinkley test. When the detector raises an alarm, the labels of the last window_size observations are requested to retrain the teacher, and the student is retrained on the new teacher's predictions. Since the mimicking error does not depend on the labels, it is used for virtual concept drift.

Usage

dfr_studd(
  teacher,
  student = teacher,
  detector = dfr_page_hinkley(delta = 0.001),
  window_size = 500,
  student_memory = "all",
  fit_teacher = TRUE,
  target_feat = NULL,
  seed = NULL
)

Arguments

teacher

A daltoolbox classification object (for example daltoolbox::cla_rf("class", levels)), whose attribute is the label column of the stream.

student

A daltoolbox classification object for the student, with the same attribute and levels. By default the same algorithm as the teacher.

detector

Univariate detector fed with the mimicking errors (a dist_based or error_based object of this package). The default is the Page-Hinkley test with delta = 0.001, as in the paper.

window_size

Number of observations of the initial training window and of the window of labels requested after every drift (W in the paper).

student_memory

Observations used to retrain the student after a drift: "all" (the default, as in the reference code) uses every observation seen since the end of the initial window; "window" only the last window_size ones, which bounds memory.

fit_teacher

If TRUE (the default), the teacher is trained by the detector on the labels of the initial window and retrained after every drift. If FALSE, the teacher must already be fitted, it is never retrained and the stream needs no label column: only the student is trained, on the teacher's predictions.

target_feat

Names of the feature columns. NULL (the default) uses every numeric column except the label column.

seed

Seed of the random number generator used when the models are trained. NULL draws it from the global generator when the detector is created; the global random state is left unchanged.

Details

Labels are read only for the rows used to (re)train the teacher; every other row may have a missing label. The initial window is used only for training: no drift is checked on it. The rows of a drift alarm are included in the window used to retrain the teacher, as in the reference implementation (https://github.com/vcerqueira/experiments-studd, studd_batch.py).

A model is always trained on the classes present in its training data, so that, as in scikit-learn, a class missing from a window does not stop the training. When a single class is present, the model predicts that class. Predictions are the class of highest probability (the first one in case of ties). reset_state() resets the detector and keeps the models.

Value

dfr_studd object. After fit(), drifter_output holds, for every monitored row, the class predicted by the teacher (teacher) and by the student (student), the mimicking error (error) and the detector statistic (statistic), and whether a drift was reported (drift). The classes are given by their position in the levels of the teacher. obj$labels_used counts the labels used to train the teacher.

References

Cerqueira, V., Gomes, H. M., Bifet, A. and Torgo, L. (2023). STUDD: a student-teacher method for unsupervised concept drift detection. Machine Learning, 112, 4351-4378. https://doi.org/10.1007/s10994-022-06188-7

Examples

library(daltoolbox)
library(heimdall)
set.seed(1)
# Two classes separated by x1 + x2 = 0; from row 1201 on, the observations
# concentrate along the class boundary, where the student imitates the
# teacher worse.
n <- 2400
x <- matrix(stats::rnorm(n * 2), ncol = 2)
x[1201:n, 2] <- -x[1201:n, 1] + stats::rnorm(1200, 0, 0.2)
y <- ifelse(x[, 1] + x[, 2] > 0, "a", "b")
stream <- data.frame(x1 = x[, 1], x2 = x[, 2], class = y)
teacher <- cla_rf("class", c("a", "b"), ntree = 20)
detector <- dfr_studd(teacher, window_size = 400, seed = 1)
model <- fit(detector, stream)
which(model$drifter_output$drift == 1)
model$labels_used

WWAggr ensemble drift detector

Description

Monitors a stream with an ensemble of change point models (cpd_ensemble(), preferably calibrated with cpd_calibrate()): every member scores the observations as they arrive, the scores are aggregated by WWAggr (Stepikin et al., 2025) or by a naive aggregation (wwaggr()), and a drift is reported when the aggregated score exceeds threshold. Since the members are trained on sequences of the monitored features, it detects changes of their distribution (virtual concept drift).

Usage

dfr_wwaggr(
  ensemble,
  threshold = 0.5,
  method = c("wasserstein", "mmd", "mean", "min", "max", "median", "quantile"),
  window_size = 3,
  anchor = c("prev", "start", "combined"),
  p = 1,
  kernel = c("rbf", "multiscale"),
  bandwidth = NULL,
  q = 0.5,
  target_feat = NULL,
  horizon = NULL
)

Arguments

ensemble

A cpd_ensemble.

threshold

Alarm threshold on the aggregated score. With calibrated members and the 1-Wasserstein distance, the paper finds that a threshold near 0.5 is close to the best one.

method, window_size, anchor, p, kernel, bandwidth, q

Aggregation, as in wwaggr().

target_feat

Names of the columns fed to the members, in the order of training. NULL (default) uses the feature names of the ensemble, or every numeric column when it has none.

horizon

If set, the members and the aggregation restart every horizon observations, so that the stream is read as consecutive sequences of the training length. NULL (default) restarts them only after a drift.

Details

The members score each observation online, as on whole sequences: the LSTM models (indid()) update their state; the representation models (tscp2(), ts2vec()) compare the embeddings of the last two windows of window observations (every step observations, with the exponential smoothing alpha), so they have no score for the first 2 * window - 1 observations of a sequence. The aggregation starts when all members have a score, and its score at an observation compares the window of the window_size previous scores with the anchor (see wwaggr()). After a drift, the members and the aggregation restart. Rows with missing values are skipped.

Value

dfr_wwaggr object. After fit(), drifter_output holds, for every observation, the aggregated score (score, NA when there is none) and whether a drift was reported (drift).

References

Stepikin, A., Romanenkova, E. and Zaytsev, A. (2025). WWAggr: A window Wasserstein-based aggregation for ensemble change point detection. 2025 IEEE International Conference on Data Mining (ICDM), 1535-1544. https://doi.org/10.1109/ICDM65498.2025.00163

Examples

library(daltoolbox)
library(heimdall)
set.seed(1)
make <- function(n) {
  change <- sample(5:24, n, replace = TRUE)
  change[seq_len(n / 2)] <- 25
  x <- t(vapply(change, function(c) stats::rnorm(24, ifelse(seq_len(24) < c, 0, 3)), numeric(24)))
  list(x = x, labels = t(vapply(change, function(c) (seq_len(24) >= c) * 1, numeric(24))))
}
train <- make(96)
ensemble <- cpd_ensemble_fit(train$x, train$labels, model = "bce", n_models = 3, epochs = 10,
                             learning_rate = 0.01, seed = 1)
ensemble <- cpd_calibrate(ensemble, train$x, train$labels)
stream <- data.frame(value = c(stats::rnorm(15), stats::rnorm(15, 3)))
detector <- fit(dfr_wwaggr(ensemble, window_size = 2), stream)
which(detector$drifter_output$drift == 1)

Distribution Based Drifter sub-class

Description

Implements univariate Distribution Based drift detectors. These detectors monitor a single numeric feature; missing observations are skipped instead of being imputed.

Usage

dist_based(target_feat)

Arguments

target_feat

Feature to be monitored.

Value

Drifter object

Examples

obj <- dist_based(target_feat = "serie")
obj$target_feat

Run the drift detector on a batch

Description

The shared drift step of the drift-adaptation workflows: builds the signal the detector monitors with drifter_input(), feeds the detector, reads whether it drifted and resets it on a drift. It keeps the model wrappers from duplicating the detect-and-reset logic.

Usage

drift_step(drift_method, ctx)

Arguments

drift_method

The drift detector.

ctx

The context passed to drifter_input(): features (the projected batch) and, for error-based detectors, model, y and th (and the wrapper's target_uni).

Value

A list with the updated drift_method (reset when it drifted), the logical drifted, the rows the monitored signal covers and the drifter_output produced on this batch (captured before the reset, for diagnostics).


Drift-adaptation workflow

Description

Ancestor of the drift-adaptation workflows: the family of predictive models that react to concept drift. Each concrete model is an experiment line — a workflow of activities (detect -> manage -> train -> threshold -> record) with its own backbone. This base holds the shared process state (drift_method, warmup_size, verbose, the sticky drifted flag) and the shared drift step (drift_step()); it does not own a concrete backbone. The two concrete lines are:

adp_retrain()

a single model, retrained when a drift is reported (formerly stealthy).

adp_recurrent()

a repository of concepts that are stored and reused across recurring regimes (formerly remind).

Usage

drift_workflow(drift_method, warmup_size = 100, verbose = FALSE)

Arguments

drift_method

The drift detector.

warmup_size

Minimum number of rows before the detector runs.

verbose

If TRUE, prints drift messages.

Value

A drift_workflow object (the shared base; use adp_retrain() or adp_recurrent()).


Drifter

Description

Ancestor class for drift detection.

Every detector in the package follows the same contract:

Usage

drifter()

Value

Drifter object

Examples

model <- drifter()
model$drifted

Drifter monitoring input

Description

Builds the signal a detector monitors from a prepared batch, so that model wrappers (such as adp_retrain() and adp_recurrent()) feed every detector family the same way, without branching on the detector's class. Each family implements its own method; a new detector inherits the right behaviour by belonging to a family (error_based, dist_based, mv_dist_based, multi_criteria) or falls back to the default, which feeds the whole batch (this also covers the dummy baselines dfr_passive() and dfr_inactive(), whose own update_state() decides whether a drift is reported).

Usage

drifter_input(obj, ctx)

Arguments

obj

Drifter object.

ctx

A list with the prepared batch and the prediction context: features (the one-hot encoded, normalized batch) and, for error-based detectors, model, y (labels) and th (threshold). A wrapper may set target_uni = TRUE so a univariate distance detector monitors the binary label instead of a feature.

Value

A list with value, the signal passed to fit(), and rows, the indices of the batch rows that value covers (every row, except error-based detectors, which skip rows without a prediction).

Examples

ctx <- list(features = data.frame(a = rnorm(10), b = rnorm(10)))
drifter_input(dfr_inactive(), ctx)$rows

Induce a drift in a benchmark source

Description

Moves a dsg_source() to another concept and verifies the drift: a virtual drift must make the kernel two-sample test (dsg_mmd_test()) reject at virtual_p_value, and a real drift must change at least real_drift_level of the labels of the same points. Candidates that fail are discarded; after max_tries candidates, the strongest real drift found is used with a warning.

Usage

dsg_drift(source, type = "a")

Arguments

source

dsg_source object

type

"-" (or "_") no drift, "v" pure virtual drift, "r" pure real drift, "c" both, "a" any of them.

Value

list with the updated source, the logical flags virtual and real, and the verification statistics p_value (two-sample test, NA without virtual drift) and label_change (share of changed labels, NA without real drift)

Examples

set.seed(2)
drift <- dsg_drift(dsg_sine(), "r")
drift$real
drift$label_change

Kernel two-sample test (MMD)

Description

Permutation test of whether two samples come from the same distribution, using the maximum mean discrepancy (Gretton et al., 2012) with a random-trees kernel: the similarity of two points is the share of totally random trees in which they fall in the same leaf. This is the test used to verify virtual drift in the reference implementation of Hinder et al. (2026).

Usage

dsg_mmd_test(x1, x2, n_perm = 2500, n_trees = 100, max_depth = 5)

Arguments

x1, x2

Data frames or matrices with the same numeric columns.

n_perm

Number of permutations.

n_trees, max_depth

Size of the random-trees embedding.

Value

list with the MMD statistic and the permutation p_value (share of permutations with a larger statistic)

References

Gretton, A., Borgwardt, K. M., Rasch, M. J., Scholkopf, B., and Smola, A. (2012). A kernel two-sample test. Journal of Machine Learning Research, 13, 723-773.

Examples

set.seed(1)
same <- dsg_mmd_test(matrix(stats::rnorm(200), 100), matrix(stats::rnorm(200), 100), n_perm = 200)
shifted <- dsg_mmd_test(matrix(stats::rnorm(200), 100), matrix(stats::rnorm(200, 1), 100),
                        n_perm = 200)
c(same$p_value, shifted$p_value)

Drift benchmark source

Description

Creates a data source with controlled real and virtual drift, following the pipeline of Hinder et al. (2026), "Real vs. Virtual Drift: Creating Realistic Stream Learning Benchmarks". A source combines nv feature distributions (virtual drift states, given by samplers) with nr labelling rules (real drift states, given by labelers), so it has nv * nr concepts. Moving between two concepts that share the labelling rule is pure virtual drift; moving between two that share the feature distribution is pure real drift.

Most users will create sources with dsg_source_data() (from a real-world stream) or with the synthetic generators dsg_sea(), dsg_agrawal(), dsg_sine() and dsg_mixed(), draw samples with dsg_take(), induce drift with dsg_drift(), and build whole streams with dsg_stream().

Usage

dsg_source(
  samplers,
  labelers,
  real_drift_level = 0.01,
  virtual_p_value = 0.001,
  test_size = 1000,
  n_perm = 2500,
  max_tries = 100
)

Arguments

samplers

List of functions; samplers[[v]](n) returns a data frame (or matrix) with up to n rows drawn from feature distribution v. It may return fewer rows; dsg_take() calls it again until it has enough.

labelers

List of functions; labelers[[r]](x) returns one label per row of the data frame x according to labelling rule r.

real_drift_level

Smallest share of labels that a real drift must change (on test_size points) to be accepted.

virtual_p_value

Largest p-value of the kernel two-sample test (dsg_mmd_test()) for a virtual drift to be accepted.

test_size

Number of points drawn to verify each drift.

n_perm

Number of permutations of the two-sample test.

max_tries

Number of candidate concepts tried by dsg_drift() before it falls back to the strongest real drift found.

Value

dsg_source object

References

Hinder, F., Brinkrolf, J., Lammers, K., and Hammer, B. (2026). Real vs. Virtual Drift: Creating Realistic Stream Learning Benchmarks. In Proceedings of the European Symposium on Artificial Neural Networks, Computational Intelligence and Machine Learning (ESANN 2026), 133-138.

Examples

# Two feature distributions and two labelling rules: four concepts.
source <- dsg_source(
  samplers = list(
    function(n) data.frame(x = stats::runif(n, 0, 1)),
    function(n) data.frame(x = stats::runif(n, 0.5, 1.5))
  ),
  labelers = list(
    function(x) as.integer(x$x > 0.5),
    function(x) as.integer(x$x > 1)
  ),
  test_size = 200, n_perm = 200
)
set.seed(1)
stream <- dsg_stream(source, "-v-r", batch_size = 100)
stream$segments

Benchmark source from a real-world stream

Description

Turns a real-world data stream into a dsg_source() whose real and virtual drift are controlled (Hinder et al., 2026). The stream, assumed to be in time order, is split into blocks twice:

Labelling the data of any feature segment with the model of any label segment separates the virtual drift between segments from the real drift learned by the model, giving (virtual_blocks + 1) * (real_blocks + 1) concepts with known drift between them.

Usage

dsg_source_data(
  data,
  target,
  real_blocks = 5,
  virtual_blocks = 5,
  model = NULL,
  nodesize = 10,
  n_clusters = 0,
  n_ignore = 3,
  ...
)

Arguments

data

Data frame with the stream in time order. Every column but target must be numeric.

target

Name of the label column.

real_blocks, virtual_blocks

Number of segment boundaries (giving one more segment), or the boundaries themselves as relative positions in (0, 1) or as row indices.

model

Function model(x, y) that fits a classifier on the data frame x (with the segment index in column block) and returns a function giving a matrix of class probabilities (one column per class, named after the classes) for new data. NULL uses a random forest from the randomForest package (100 trees, nodesize as given).

nodesize

Minimum leaf size of the default random forest.

n_clusters

When greater than 0, the real drift is enhanced with region-wise label flips: the data are split into (n_ignore + 1) * real_blocks * n_clusters k-means clusters, and in each segment the labels of a segment-specific subset of the clusters are permuted among the classes.

n_ignore

Controls the share of clusters that are never flipped.

...

Further arguments for dsg_source(), such as test_size.

Details

With the default model, obj$quality holds the out-of-bag accuracy of the forest (how well the labelling model fits the data) and the permutation importance of the segment index (how much real drift the model found).

Value

dsg_source object (also of class dsg_source_data)

References

Hinder, F., Brinkrolf, J., Lammers, K., and Hammer, B. (2026). Real vs. Virtual Drift: Creating Realistic Stream Learning Benchmarks. In ESANN 2026, 133-138.

Examples


set.seed(1)
n <- 600
x1 <- c(stats::rnorm(300), stats::rnorm(300, 2))
x2 <- stats::rnorm(n)
y <- as.integer(x2 > c(rep(0, 300), rep(1, 300)))
stream <- data.frame(x1, x2, y)
source <- dsg_source_data(stream, "y", real_blocks = 1, virtual_blocks = 1,
                          test_size = 200, n_perm = 200)
dsg_stream(source, "-v-r", batch_size = 100)$segments


Benchmark source from a synthetic generator

Description

Builds a dsg_source() from a generator of feature vectors and a list of labelling rules (the real drift states). Virtual drift states are made by regional sub-sampling, as in Hinder et al. (2026): the feature space is split into the Voronoi cells of a k-means clustering, the cells are dealt into n_variants groups, and each virtual state keeps only the samples falling in its group.

Usage

dsg_source_regions(
  generator,
  labelers,
  n_clusters = 20,
  n_variants = 2,
  init_size = 1000,
  ...
)

Arguments

generator

Function generator(n) returning a data frame with n feature vectors.

labelers

List of labelling functions, see dsg_source().

n_clusters

Approximate number of k-means clusters; rounded up to the next multiple of n_variants above n_clusters, as in the reference code.

n_variants

Number of virtual drift states.

init_size

Number of samples used to fit the clustering.

...

Further arguments for dsg_source().

Value

dsg_source object

Examples

set.seed(1)
source <- dsg_source_regions(
  generator = function(n) data.frame(a = stats::runif(n), b = stats::runif(n)),
  labelers = list(function(x) as.integer(x$a > x$b), function(x) as.integer(x$a > 0.5)),
  test_size = 200, n_perm = 200
)
source

Generate a benchmark stream with controlled drift

Description

Builds a stream segment by segment. Each character of pattern first induces a drift with dsg_drift() ("-" or "_" none, "v" virtual, "r" real, "c" both, "a" any) and then draws batch_size samples from the resulting concept.

Usage

dsg_stream(source, pattern, batch_size = 500)

Arguments

source

dsg_source object

pattern

Drift pattern, such as "--v--r-".

batch_size

Number of samples per segment.

Value

list with

Examples

set.seed(3)
# small settings keep the example fast; use the defaults for real benchmarks
source <- dsg_sea(n_perm = 200, test_size = 300, init_size = 300, n_clusters = 8)
stream <- dsg_stream(source, "-v-r", batch_size = 100)
head(stream$data)
stream$segments

Synthetic benchmark sources

Description

Synthetic streams commonly used in stream learning, as defined in the river library, turned into dsg_source_regions() sources: their concept functions give the real drift states, and regional sub-sampling gives the virtual drift states (Hinder et al., 2026).

Usage

dsg_sea(...)

dsg_agrawal(...)

dsg_sine(...)

dsg_mixed(...)

Arguments

...

Arguments for dsg_source_regions() and dsg_source(), such as n_clusters, n_variants or test_size.

Value

dsg_source object

References

Agrawal, R., Imielinski, T., and Swami, A. (1993). Database mining: a performance perspective. IEEE Transactions on Knowledge and Data Engineering, 5(6), 914-925.

Street, W. N., and Kim, Y. (2001). A streaming ensemble algorithm (SEA) for large-scale classification. In KDD 2001, 377-382.

Gama, J., Medas, P., Castillo, G., and Rodrigues, P. (2004). Learning with drift detection. In SBIA 2004, 286-295.

Montiel, J. et al. (2021). River: machine learning for streaming data in Python. Journal of Machine Learning Research, 22(110), 1-8.

Examples

set.seed(1)
dsg_take(dsg_agrawal(), 3)

Draw samples from a drift benchmark source

Description

Draws n labelled samples from the current concept of a dsg_source().

Usage

dsg_take(source, n = 1)

Arguments

source

dsg_source object

n

Number of samples.

Value

list with the features x (data frame) and the labels y

Examples

set.seed(1)
sample <- dsg_take(dsg_sea(), 5)
sample$x
sample$y

Dummy Drifter sub-class

Description

Ancestor class for the baseline detectors that ignore the monitored signal, dfr_inactive() and dfr_passive().

Usage

dummy()

Value

Drifter object

Examples

obj <- dummy()
class(obj)

Equal intensity k-means space partitioning (EI-kMeans)

Description

Histogram-based two-sample test for drift detection (Liu et al., 2021). The feature space is partitioned by k-means clusters of (nearly) equal intensity, so that no bin straddles a gap between clusters of the data, and a new sample is compared with the training sample by Pearson's chi-square test on the counts of the two samples in every bin.

Usage

eikmeans(
  training,
  n_test,
  k = 40,
  alpha = 0.05,
  min_points = 50,
  n_build = 2000,
  thetas = seq(0, 0.95, by = 0.05)
)

Arguments

training

The training sample (matrix or data frame of numeric features).

n_test

Size of the samples that will be tested. The number of bins is at most n_test / 5, so that the expected count of every bin in a test sample is at least 5.

k

Largest number of bins.

alpha

Significance level of the chi-square test.

min_points

Smallest number of training points per bin (beta).

n_build

Number of training points used to build the partitioning: the first n_build rows. The counts of the bins are then taken from the whole training sample.

thetas

Values of the shape parameter theta of the amplify-shrink coefficients exp(theta (r - 1)), tried in order.

Details

The partitioning follows the reference code (https://github.com/Anjin-Liu/TCYB2019-EIkMeansDriftDetection):

  1. The number of bins starts at min(k, n_test / 5, n / 50) (n is the training size).

  2. Greedy equal intensity initialization (Algorithm 1): K - 1 times, the point whose n_build / K-th nearest neighbour is farthest is taken together with its n_build / K nearest neighbours as a group, and the group is removed; the remaining points are the last group. The first point of every group starts k-means (Lloyd's algorithm, with the stopping rule of scikit-learn).

  3. Amplify-shrink (Algorithm 2): with intensity ratios r (points per cluster over n_build / K), a point goes to the cluster that minimises its distance times exp(theta (r - 1)), so crowded clusters shrink and sparse ones grow. The ratios are updated after every theta, and the search stops when every cluster has more than min_points points. If no theta is enough, the number of bins is lowered by one and the search repeated.

  4. A test sample is assigned to the bins in the same way, and the 2 x K table of training and test counts is tested with Pearson's chi-square test (Algorithm 3); bins empty in both samples are left out, and the Yates correction is used with one degree of freedom, as in scipy.stats.chi2_contingency.

The reference code differs from the paper in a few points, and the code is followed: theta ranges over 0, 0.05, ..., 0.95 (the paper gives up to 1.5), the initialization uses the distance to the n / K-th neighbour (the paper describes the nearest one) and starts k-means from a point of each group (the paper, from the group mean), the starting number of bins depends on the test size, and the partitioning is built on the first 2000 training points. If the number of bins reaches 1, the reference falls back to k plain k-means clusters; so does this implementation.

Value

An eikmeans object with the centroids (centers), the amplify-shrink coefficients (amplify), the training counts of every bin (counts) and the settings.

References

Liu, A., Lu, J. and Zhang, G. (2021). Concept drift detection via equal intensity k-means space partitioning. IEEE Transactions on Cybernetics, 51(6), 3198-3211. https://doi.org/10.1109/TCYB.2020.2983962

See Also

eikmeans_test() to test a sample and dfr_eikmeans() to monitor a stream.

Examples

# Two clusters; the right one moves.
set.seed(1)
cluster <- function(n, x) cbind(stats::rnorm(n, x), stats::rnorm(n))
training <- rbind(cluster(250, 0), cluster(250, 5))
model <- eikmeans(training, n_test = 100, k = 10, min_points = 20)
nrow(model$centers)
eikmeans_test(model, rbind(cluster(50, 0), cluster(50, 5)))
eikmeans_test(model, rbind(cluster(50, 0), cluster(50, 5.8)))

Test a sample with an EI-kMeans partitioning

Description

Assigns the points of a sample to the bins of an eikmeans() model and compares the counts with those of the training sample by Pearson's chi-square test.

Usage

eikmeans_test(model, sample)

Arguments

model

An eikmeans object.

sample

The sample to test (matrix or data frame with the training features).

Value

A data frame with the chi-square statistic, the degrees of freedom (df), the p_value and whether a drift is detected (drift, p_value < alpha).

Examples

set.seed(1)
model <- eikmeans(matrix(stats::rnorm(1000), ncol = 2), n_test = 100,
                  k = 10, min_points = 20)
eikmeans_test(model, matrix(stats::rnorm(200, 0.5), ncol = 2))

Ensemble vote over detection series

Description

Applies the voting of dfr_ensemble() to detection series computed beforehand, one column per detector (crisp ensemble with tolerance <= 1, fuzzy ensemble otherwise). This is how the paper combines its detectors.

Usage

ensemble_vote(
  detections,
  voting = c("majority", "efer", "threshold"),
  threshold = NULL,
  tolerance = 0,
  lookahead = TRUE
)

Arguments

detections

Logical (or 0/1) matrix or data frame, one row per time step and one column per detector.

voting

Voting rule: "majority" (default), "efer" or "threshold".

threshold

Vote needed by the "threshold" rule (lambda).

tolerance

Time tolerance k of the fuzzy scores; 0 (default) gives the crisp ensemble.

lookahead

With fuzzy scores, TRUE (default) uses detections on both sides of a time step, as in the paper. The vote of time t is then known only when t + k - 1 has arrived, so drifts are reported k - 1 observations after the time they refer to (obj$events holds those times). FALSE uses only the detections up to the current observation and reports at once.

Value

A logical vector with the ensemble drifts, with attribute vote (the vote of every time step, evaluated with the detections left after the earlier ensemble drifts).

Examples

detections <- matrix(FALSE, 100, 3)
detections[c(40, 43, 47), 1:3] <- diag(3) == 1
# No crisp majority: the detections are not simultaneous.
which(ensemble_vote(detections, "majority"))
# A fuzzy majority with a tolerance of 10 time steps.
which(ensemble_vote(detections, "majority", tolerance = 10))

Error Based Drifter sub-class

Description

Implements Error Based drift detectors. These detectors monitor the residuals of a predictive model, where 1 (or TRUE) means a wrong prediction and 0 (or FALSE) a correct one. Missing values are treated as correct predictions.

Usage

error_based()

Value

Drifter object

Examples

obj <- error_based()
class(obj)

Evict a concept

Description

Generic called by the concept pool to choose the slot to replace, implemented by each evictor.

Usage

evict(obj, concept_list)

Arguments

obj

An evictor object.

concept_list

The stored concepts.

Value

The index of the slot to be replaced.


Evictor

Description

Base class of the evictors, the concept pool's model_deleter: when every slot is used and a new concept must be stored, an evictor chooses the slot to replace.

Usage

evictor()

Value

An evictor object.


Least used evictor

Description

Used as the concept pool's model_deleter: returns the slot of the stored concept that was active for the fewest batches (qty).

Usage

evt_least_used()

Value

A evt_least_used object.


Redundant evictor

Description

Used as the concept pool's model_deleter: finds the pair of stored concepts whose memories are the most similar (smallest PSI) and returns the slot of the less used of the two, so the repository keeps one representative of each regime. Concepts active for fewer than min_qty batches are protected. With fewer than two eligible concepts, behaves as evt_least_used().

Usage

evt_redundant(numerical_cols = NULL, n_tiles = 10, min_qty = 5)

Arguments

numerical_cols

Names of the numerical features (see slct_psi()).

n_tiles

Number of quantile bins of the numerical PSI.

min_qty

Minimum number of active batches for a concept to be eligible for removal.

Value

A evt_redundant object.


Aggregate F1

Description

Sums the confusion matrices of several batches and computes the F1 once. Batches therefore weigh by their number of positives, not equally, which is how the F1 of a scenario is reported.

Usage

f1_aggregate(TP, FP, FN)

Arguments

TP

True positives, one value per batch.

FP

False positives, one value per batch.

FN

False negatives, one value per batch.

Value

The aggregate F1, or NA when no batch has a positive, real or predicted.

Examples

f1_aggregate(TP = c(8, 6), FP = c(2, 3), FN = c(5, 4))

Likelihood-ratio change point of a binary sequence

Description

Finds the split of a binary sequence that maximises the log-likelihood ratio between two Bernoulli segments and a single one (problem Change of Tatti, 2019), searching only the border indices, with the (1 - \epsilon) approximation of Algorithm 3 when eps > 0.

Usage

fastlr_split(x, eps = 0)

Arguments

x

Binary vector (0/1 or logical).

eps

Approximation guarantee, in [0, 1): the returned score is at least 1 - \epsilon times the optimum. 0 tests every border index.

Value

A list with score (log-likelihood ratio, natural logarithm), index (the first entry of the second segment; length(x) + 1 or 1 when no split improves the likelihood), tests (number of evaluated change points), candidates (candidates of FindCands, without the FindSegment points) and blocks (number of border indices of the sequence and of the flipped sequence).

References

Tatti, N. (2019). Fast likelihood-based change point detection. In Machine Learning and Knowledge Discovery in Databases (ECML PKDD 2019), 662-677. https://doi.org/10.1007/978-3-030-46150-8_39. arXiv:2301.08892.

Examples

set.seed(1)
x <- c(rbinom(300, 1, 0.2), rbinom(200, 1, 0.6))
fastlr_split(x)
fastlr_split(x, eps = 0.5)$score

Process Batch

Description

Process Batch

Usage

## S3 method for class 'drifter'
fit(obj, data, prediction = NULL, ...)

Arguments

obj

Drifter object

data

data batch in data frame format

prediction

prediction batch as vector format. Optional and unused by the default method; it is kept for compatibility with detectors that need the model output.

...

optional arguments

Value

updated Drifter object

Examples

library(daltoolbox)
model <- dfr_inactive()
model <- fit(model, data.frame(serie = 1:10))
model$drifted

GreedyKS sketch of the one-sample Kolmogorov-Smirnov statistic

Description

Online approximation of the statistic ⁠D = sup |F_n(x) - F(x)|⁠ of the one-sample Kolmogorov-Smirnov test between a stream and a reference distribution with CDF F, in ⁠O(log m)⁠ time per observation and O(m) memory, whatever the number of observations (Cardoso and Galeno, 2023).

Usage

greedyks(cdf, m = 100, min_instances = 0)

greedyks_update(sketch, x)

greedyks_statistic(sketch)

greedyks_pvalue(sketch, exact = TRUE)

Arguments

cdf

Cumulative distribution function of the reference distribution (for example function(x) pnorm(x, 1, 1)).

m

Number of buckets (the memory units of the paper).

min_instances

Number of observations before the statistic is estimated (it is 0 before).

sketch

A greedyks sketch.

x

Numeric vector of observations, processed in order. Missing values are skipped.

exact

Passed to ks_sf(): the exact distribution of the statistic (TRUE, the default, as scipy.stats.kstwo in the reference) or the limiting Kolmogorov distribution (FALSE).

Details

Each observation x is mapped to f = F(x) and to the bucket ⁠b = ceiling(f m)⁠ of ⁠0, ..., m⁠, which keeps the number of observations and the smallest and largest f it received. The largest gaps between the ECDF and the CDF, ⁠D+⁠ and ⁠D-⁠, are updated greedily (Algorithm 2 of the paper): with the bucket just updated and with the buckets that gave the current maxima, re-evaluated at every step. The counts before a bucket come from a Fenwick tree (binary indexed tree). The estimate is ⁠max(D+, D-)⁠.

The reference implementation uses ⁠ceiling(f m)⁠ (the paper writes floor), so there are m + 1 buckets; heimdall does the same.

Value

greedyks() returns a greedyks sketch. greedyks_update() returns the sketch after the observations x, in order. greedyks_statistic() returns the estimate of D, and greedyks_pvalue() its p-value for the number of observations processed (see ks_sf()).

References

Cardoso, D. O. and Galeno, T. D. (2023). Online evaluation of the Kolmogorov-Smirnov test on arbitrarily large samples. Journal of Computational Science, 67, 101959. https://doi.org/10.1016/j.jocs.2023.101959

Examples

set.seed(1)
x <- rnorm(5000, 1.1, 1)
sketch <- greedyks_update(greedyks(function(q) pnorm(q, 1, 1), m = 100), x)
greedyks_statistic(sketch)
unname(ks.test(x, "pnorm", 1, 1)$statistic)   # exact value
greedyks_pvalue(sketch)

Incremental two-sample Kolmogorov-Smirnov test

Description

A sketch of two samples A (group 0) and B (group 1) that supports the insertion and removal of observations in ⁠O(log N)⁠ expected time and gives the two-sample Kolmogorov-Smirnov statistic ⁠D = max |F_A(x) - F_B(x)|⁠ in O(1) (dos Reis et al., 2016).

Usage

iks(ratio = 1, seed = NULL)

iks_add(sketch, x, group, tie = 0)

iks_remove(sketch, x, group, tie = 0)

iks_statistic(sketch)

iks_kuiper(sketch)

iks_test(sketch, ca = 1.95)

iks_ca(alpha)

Arguments

ratio

The constant ratio r = |A| / |B| at which the statistic is computed (1, the default, for samples of equal sizes). Each observation of B weighs r.

seed

Seed of the private generator (Park-Miller) of the priorities of the treap and of the tie-breaking values; NULL draws it from R's generator. The priorities do not change the statistic.

sketch

An iks sketch.

x

The observation.

group

0 for sample A (the reference), 1 for sample B.

tie

Tie-breaking value of the observation (0 by default; a random value, as stats::runif(1), makes keys distinct). An observation is removed with the same x and tie it was inserted with.

ca

Coefficient of the critical value ⁠ca sqrt((n + m) / (n m))⁠; the default 1.95 is the one of the paper and of the reference code (alpha = 0.001).

alpha

Significance level.

Details

Observations are sorted by the key ⁠(x, tie, group)⁠. The treap stores, at every observation, ⁠G = F'_A - F'_B⁠ (the counts of A minus r times the counts of B up to and including it); an insertion adds 1 or -r to every later observation with a lazily propagated bulk operation, and the subtree maxima and minima give ⁠D = max(max G, -min G) / |A|⁠.

As noted by the authors, the statistic is exact only when the observations are distinct: with tied values it can be larger than the one of stats::ks.test(). A random tie value per observation (as IKSSW of the reference code) breaks the ties.

Value

iks() returns an iks sketch; iks_add() and iks_remove() the updated sketch; iks_statistic() the statistic D; iks_kuiper() the Kuiper statistic ⁠(max G - min G) / |A|⁠; iks_test() TRUE when the null hypothesis of equal distributions is rejected; iks_ca() the coefficient c(alpha) = sqrt(-log(alpha / 2) / 2).

References

dos Reis, D. M., Flach, P., Matwin, S. and Batista, G. (2016). Fast unsupervised online drift detection using incremental Kolmogorov-Smirnov test. In Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, 1545-1554. https://doi.org/10.1145/2939672.2939836

Examples

set.seed(1)
a <- rnorm(200)
b <- rnorm(200, 0.3)
sketch <- iks()
for (i in 1:200) sketch <- iks_add(iks_add(sketch, a[i], 0), b[i], 1)
iks_statistic(sketch)
unname(ks.test(a, b)$statistic)
# slide the window of B by one observation
sketch <- iks_add(iks_remove(sketch, b[1], 1), 2, 1)
iks_test(sketch, ca = iks_ca(0.001))

InDiD change point detection model

Description

Trains the sequence-to-sequence change point detector of Romanenkova et al. (2022): a recurrent network (an LSTM layer and a linear layer with sigmoid output) reads a sequence and gives, at every time step, the probability that a change has already happened. The model is trained on labelled sequences with the InDiD loss, a differentiable approximation of the detection delay after a change and of the time to a false alarm before it; with the binary cross-entropy (BCE); or with both in turn (combined).

Usage

indid(
  x,
  labels,
  loss = c("indid", "bce", "combined"),
  hidden_size = 4,
  T = 32,
  learning_rate = 0.001,
  batch_size = 64,
  epochs = 200,
  patience = 10,
  validation = NULL,
  seed = NULL,
  n_layers = 1,
  dropout = 0,
  layer_norm = c("none", "before", "after")
)

Arguments

x

Training sequences: an array ⁠[sequence, time, feature]⁠, a matrix ⁠[sequence, time]⁠ (one feature) or a list of matrices ⁠[time, feature]⁠ of the same size.

labels

Labels of the training sequences, a matrix ⁠[sequence, time]⁠ that is 0 before the change and 1 from the change on (all 0 when the sequence has no change).

loss

"indid" (default), "bce" or "combined" (BCE for half of the epochs, then InDiD for the other half).

hidden_size

Size of the LSTM hidden state.

T

Length of the segment after the change used by the delay part of the InDiD loss.

learning_rate

Learning rate of Adam.

batch_size

Number of sequences per batch.

epochs

Largest number of epochs (for "combined", split in two).

patience

Epochs without a lower validation loss before training stops (early stopping, only with validation data).

validation

Optional validation data, list(x = , labels = ).

seed

Seed of the private random stream (initial weights and order of the batches). NULL draws one from the session.

n_layers

Number of LSTM layers.

dropout

Dropout rate on the outputs of every LSTM layer but the last (training only), as torch.nn.LSTM.

layer_norm

"none" (default, torch.nn.LSTM), or the one-layer LSTM with layer normalisation of the WWAggr code (LayerNormLSTM): "before" or "after" the linear map of every gate.

Details

The model and the training follow the reference code (https://github.com/romanenkova95/InDiD: utils/loss.py, utils/core_models.py (BaseRnn), utils/cpd_models.py, train.py and the ⁠configs/⁠):

The network, the gradients (backpropagation through time) and Adam are written in R. The defaults are those of the 1-D SyntheticNormal experiment (configs/synthetic_1D_seq2seq.yaml).

The architectures of the WWAggr code (BaseRnn of https://github.com/stalex2902/wwagr-ensemble-cpd, src/models/core_models.py), used for the BCE and InDiD members of the ensembles of cpd_ensemble(), are available through n_layers, dropout and layer_norm. In LayerNormLSTM, every gate (forget, input, output, cell) has a linear map of the input and one of the hidden state, each with its own layer normalisation (before the map, on the input or hidden state, or after it); the linear maps are initialised as torch.nn.Linear. Models with more than one layer or with layer normalisation are trained with the automatic differentiation of the package.

Value

An indid object with the network (params), the settings and the training and validation losses of every epoch (history).

References

Romanenkova, E., Stepikin, A., Morozov, M. and Zaytsev, A. (2022). InDiD: Instant disorder detection via a principled neural network. Proceedings of the 30th ACM International Conference on Multimedia, 3152-3162. https://doi.org/10.1145/3503161.3548182

See Also

indid_predict() for the probabilities of change of new sequences and dfr_indid() to monitor a stream.

Examples

# Sequences of 32 steps around 1; half of them move to 6 at a random step.
set.seed(1)
make <- function(n) {
  change <- sample(2:32, n, replace = TRUE)
  change[seq_len(n / 2)] <- 33
  x <- t(vapply(change, function(c) stats::rnorm(32, ifelse(seq_len(32) < c, 1, 6)), numeric(32)))
  labels <- t(vapply(change, function(c) (seq_len(32) >= c) * 1, numeric(32)))
  list(x = x, labels = labels)
}
train <- make(200)
model <- indid(train$x, train$labels, T = 8, learning_rate = 0.02, epochs = 30, seed = 1)
test <- make(4)
round(indid_predict(model, test$x)[, 25:32], 2)
test$labels[, 25:32]

Probabilities of change of an InDiD model

Description

Runs an indid() model on sequences and returns, for every sequence and time step, the probability that a change has happened.

Usage

indid_predict(model, x)

Arguments

model

An indid object.

x

Sequences, in the formats accepted by indid().

Value

A matrix ⁠[sequence, time]⁠ of probabilities.

Examples

set.seed(1)
x <- matrix(stats::rnorm(20 * 16, 1), 20)
labels <- matrix(0, 20, 16)
model <- indid(x, labels, T = 4, epochs = 2, seed = 1)
dim(indid_predict(model, x))

Initial history

Description

Starts the learned limits of a newly trained concept (see history_init).

Usage

init_history(obj, concept, block_size, ...)

Arguments

obj

A concept_pool or selector object.

concept

The newly trained concept.

block_size

Rows per block (the batch size).

...

trainer: function(x, y) that trains a stand-alone concept with the REMIND steps (given by REMIND; used only by slct_error_metrics(init_blocks = TRUE)).

Value

The concept.


Distribution of the Kolmogorov-Smirnov statistic

Description

Upper tail probability P(D_n >= d) of the one-sample, two-sided Kolmogorov-Smirnov statistic ⁠D_n = sup |F_n(x) - F(x)|⁠ of a sample of size n from a continuous distribution.

Usage

ks_sf(d, n, exact = TRUE)

Arguments

d

Value(s) of the statistic, in ⁠[0, 1]⁠.

n

Sample size (a positive integer, recycled with d).

exact

TRUE (the default) for the exact distribution of D_n, as scipy.stats.kstwo; FALSE for the limiting Kolmogorov distribution of ⁠sqrt(n) D_n⁠, as scipy.stats.kstwobign.

Details

The exact distribution is computed as Simard and L'Ecuyer (2011), with the same choices of method as scipy.stats.kstwo: Ruben-Gambino formulas at the ends of the support; for n <= 140 the Durbin matrix (⁠n d^2 <= 0.754693⁠), the Pomeranz recursion (⁠n d^2 <= 4⁠) or twice the one-sided Smirnov tail; for larger n twice the one-sided tail (⁠n d^2 >= 2.2⁠), the Durbin matrix (⁠n d^1.5 <= 1.4⁠, n <= 100000) or the Pelz-Good approximation. The one-sided tail is the Birnbaum-Tingey sum.

Value

The probabilities P(D_n >= d).

References

Simard, R. and L'Ecuyer, P. (2011). Computing the two-sided Kolmogorov-Smirnov distribution. Journal of Statistical Software, 39(11), 1-18. https://doi.org/10.18637/jss.v039.i11

Marsaglia, G., Tsang, W. W. and Wang, J. (2003). Evaluating Kolmogorov's distribution. Journal of Statistical Software, 8(18), 1-4. https://doi.org/10.18637/jss.v008.i18

Examples

ks_sf(0.1, 100)
ks_sf(0.1, 100, exact = FALSE)
# same as the p-value of ks.test()
x <- c(0.61, 0.29, 0.06, 0.59, -1.73, -0.74, 0.51, -0.56, 0.39, 1.64)
ks.test(x, "pnorm")$p.value
ks_sf(unname(ks.test(x, "pnorm")$statistic), 10)

Learned acceptance limit

Description

The acceptance limit a selector compares its statistic against. A fixed number overrides everything; otherwise the limit is learned as the quantile of the statistics a concept recorded on the batches that belonged to it (pooling across all stored concepts while a concept has fewer than min_history of its own values). Each selector composes one; the per-concept statistics are kept in concept$history[[key]], shared storage that the cross-concept pooling needs.

Usage

learned_limit(fixed = NULL, quantile = 0.8, key, min_history = 5)

Arguments

fixed

A fixed limit (a number), or NULL to learn it from the history.

quantile

Quantile of the learned limit.

key

History key under which a concept stores this selector's statistics.

min_history

Own values a concept needs before it stops pooling the other concepts' values.

Value

A learned_limit object.


Balance the training data

Description

Generic that returns the (balanced) training data of a full training from the projected features of a concept's memory. The prototype decides the balancing: memory_basic() (none), memory_undersampling() or memory_oversampling() (SMOTE).

Usage

memory_balance(obj, X, y)

Arguments

obj

A memory_manager() prototype.

X

Projected (numeric) features.

y

Labels.

Value

⁠list(X = <features>, y = <labels>)⁠ after balancing.


Basic memory

Description

No balancing: the training data is the data window itself.

Usage

memory_basic()

Value

A memory_basic object.


Memory

Description

Data of a concept and how its training data is balanced. fit(memory, X, y) stores the concept's data window (X, y). memory_balance(memory, X, y) returns the training data of a full training, from the one-hot encoded window; subclasses only change it.

Usage

memory_manager()

Value

A memory_manager object.


Memory with oversampling (SMOTE)

Description

The training data is the observed data plus synthetic rows of the minority class generated with the SMOTE family until both classes have the same size, through daltoolbox::bal_oversampling(). It receives the one-hot encoded data, so categorical features are interpolated as dummy columns. Needs two classes and at least two rows of the minority class; otherwise the training data is the observed data.

Usage

memory_oversampling()

Value

A memory_oversampling object.


Memory with undersampling

Description

The training data keeps every row of the minority class and the same number of rows of the majority class, drawn at random (kept in temporal order).

Usage

memory_undersampling(min_per_class = 50)

Arguments

min_per_class

Minimum number of rows of each class to balance. Below it, the training data is the observed (unbalanced) data.

Value

A memory_undersampling object.


Metric

Description

Ancestor class for metric calculation

Usage

metric()

Value

Metric object

Examples

obj <- metric()
class(obj)

Multimodal QuantTree (MMQT)

Description

Batch-wise change detector for stationary conditions made of several modalities (Stucchi et al., 2023). Every stationary batch is drawn from one of a set of unknown distributions, for instance the operating modes of a machine, and a change is any batch that comes from none of them. MMQT builds a single QuantTree histogram over the training batches, clusters their bin-probability vectors to find the modalities, and tests each new batch against the modality closest to it with a modality-specific threshold that controls the false positive rate.

Usage

mmqt(
  training,
  nu = NULL,
  bins = 16,
  alpha = 0.05,
  n_modalities = NULL,
  alpha_modalities = 0.05,
  max_modalities = 10,
  calibration = TRUE,
  n_repeats = 10,
  n_sim = 10000,
  partition = NULL,
  seed = NULL
)

Arguments

training

The training set: a list of batches (matrices or data frames with the same columns and nu rows each), or a single matrix or data frame that is cut into consecutive batches of nu rows (an incomplete last batch is dropped).

nu

Number of observations per batch. Taken from the batches when training is a list.

bins

Number of bins K of the histogram, built with uniform target probabilities 1 / K.

alpha

Target false positive rate of the test.

n_modalities

Number of modalities M. NULL (the default) estimates it with Algorithm 1 of the paper: the smallest M whose detector has an empirical false positive rate on the training batches not above alpha_modalities.

alpha_modalities

Target false positive rate ⁠alpha'⁠ used to estimate the number of modalities.

max_modalities

Largest number of modalities tried by the estimation.

calibration

Whether to calibrate the bin probabilities of each modality (Eqs. 12-13), which corrects for a histogram built on the data of all modalities.

n_repeats

Number of times the estimation is repeated, each with a new histogram. The number of modalities is the most frequent estimate, and the histogram the one whose training false positive rate is closest to alpha_modalities among those that gave it. Ignored when n_modalities is given.

n_sim

Number of Monte Carlo simulations used to compute each threshold.

partition

A partitioning from another mmqt model (model$partition) to reuse instead of building a new one.

seed

Seed of a private random number stream, so that training does not change the global one. NULL uses the global generator.

Details

Histogram. The partitioning is a QuantTree (Boracchi et al., 2018), ported from the reference code: each bin is cut from the remaining space along a random coordinate, at the sample quantile that leaves the target share of the remaining training points in the bin. Its bin probabilities have a distribution that does not depend on the data, so the threshold of the total variation statistic ⁠T = 0.5 * sum(|p - pi|)⁠ can be computed by simulation for any data (Frittoli et al., 2022): the bin probabilities of the histogram are drawn from their Dirichlet distribution and the counts of a batch from a multinomial, n_sim times, and the threshold is the 1 - alpha quantile of the simulated statistic.

Modalities. The bin-probability vectors of the training batches are clustered by k-means (k-means++ initialization, ten starts). The centroid of a cluster estimates the bin probabilities pi^m of a modality, which are calibrated as in Eq. 12, and the modality gets the threshold of a QuantTree with probabilities pi^m built on the ⁠nu N_m⁠ points of its N_m batches.

Monitoring. A batch is assigned to the modality whose (calibrated) bin probabilities are closest in Euclidean distance (Eq. 7), and a change is detected when its statistic against that modality exceeds the modality's threshold (Eqs. 8-9).

The calibration needs, for every bin, the training points of the modality closest to the bin boundary inside and outside the bin. When the modality has no point on one of the two sides, g is set to 0.

The reference repository (https://github.com/diegocarrera89/quantTree) implements QuantTree, but its MMQT is announced as "coming soon"; MMQT is therefore implemented from the paper.

Value

An mmqt object with the partitioning (partition), the reference bin probabilities of each modality (reference, one row per modality), their thresholds (thresholds), the number of training batches of each modality (n_batches), the false positive rate on the training batches (training_fpr) and, when the number of modalities was estimated, the estimates of every repetition (estimation).

References

Stucchi, D., Magri, L., Carrera, D. and Boracchi, G. (2023). Multimodal batch-wise change detection. IEEE Transactions on Neural Networks and Learning Systems, 34(10), 6783-6797. https://doi.org/10.1109/TNNLS.2023.3294846

Boracchi, G., Carrera, D., Cervellera, C. and Maccio, D. (2018). QuantTree: histograms for change detection in multivariate data streams. Proceedings of the 35th International Conference on Machine Learning, PMLR 80, 639-648.

See Also

mmqt_test() to test batches and dfr_mmqt() to monitor a stream.

Examples

# Two operating modes; a change moves the first one.
set.seed(1)
mode <- function(n, center) matrix(stats::rnorm(2 * n, center), ncol = 2)
training <- c(lapply(1:20, function(i) mode(64, 0)), lapply(1:20, function(i) mode(64, 4)))
model <- mmqt(training, bins = 8, n_repeats = 2, n_sim = 2000, seed = 1)
model$n_modalities
mmqt_test(model, list(mode(64, 0), mode(64, 4), mode(64, 1.5)))

Test batches with a Multimodal QuantTree

Description

Assigns each batch to the closest modality of an mmqt() model (Eq. 7) and compares its total variation statistic with the threshold of that modality (Eqs. 8-9).

Usage

mmqt_test(model, batches)

Arguments

model

An mmqt object.

batches

A batch (matrix or data frame) or a list of batches, with the columns of the training set and model$nu rows each.

Value

A data frame with one row per batch: the assigned modality, the statistic, the threshold of the modality and whether a change is detected (drift).

Examples

set.seed(1)
training <- lapply(1:40, function(i) matrix(stats::rnorm(128), ncol = 2))
model <- mmqt(training, bins = 8, n_modalities = 1, n_sim = 2000)
mmqt_test(model, list(matrix(stats::rnorm(128), ncol = 2), matrix(stats::rnorm(128, 1), ncol = 2)))

Model-training activity

Description

Base class of the model-training activities: how an existing concept's model evolves at each labeled batch. It is a variation point of the recurrent-concept experiment line (adp_recurrent()) — the first full training of a concept is the shared backbone; from there, the trainer chosen for the line decides the evolution. The variants are:

train_static()

the concept is frozen: neither its data window nor its model change.

train_retrain()

the data window slides with the batch and the model is retrained from scratch on the concept memory.

train_incremental()

the data window slides and the model is updated with the current batch only, keeping its weights and preprocessing.

A trainer is concept-scoped: it depends only on the concept, the batch and the training resources (classifier, memory, pipeline), not on the model that hosts it. New variants plug in by subclassing and implementing advance_concept().

Usage

model_trainer()

Value

A model_trainer object.


Accuracy Calculator

Description

Class for accuracy calculation. Binary labels (logical, 0/1 or factors with those labels) are compared by value; other labels are compared as text.

Usage

mt_accuracy()

Value

Metric object

Examples

library(daltoolbox)
obj <- mt_accuracy()
evaluate(obj, c(TRUE, FALSE, TRUE), c(TRUE, TRUE, TRUE))

FScore Calculator

Description

Class for the F-beta score of one batch. f = 1 (the default) gives the usual F1 score; values below 1 weight precision more heavily and values above 1 weight recall more heavily.

It is computed from the confusion-matrix counts, ⁠(1 + f^2) TP / ((1 + f^2) TP + f^2 FN + FP)⁠, so it returns 0 when the batch has positives yet the prediction gets them all wrong (TP = 0, FP + FN > 0) and NA only when the batch has no positive at all (real or predicted). This is the behaviour needed to score a model in model selection: penalise an all-wrong model (score 0), do not skip it (NA). It is the metric the adp_recurrent() error-based and hybrid selectors (slct_error_metrics(), slct_psi_then_error()) use, and it matches the aggregate f1_aggregate().

Usage

mt_fscore(f = 1)

Arguments

f

The beta parameter of the F-beta score (a single positive number).

Value

Metric object

Examples

library(daltoolbox)
obj <- mt_fscore(f = 1)
evaluate(obj, c(TRUE, FALSE, TRUE), c(TRUE, TRUE, TRUE))

Precision Calculator

Description

Class for precision calculation

Usage

mt_precision()

Value

Metric object

Examples

library(daltoolbox)
obj <- mt_precision()
evaluate(obj, c(TRUE, FALSE, TRUE), c(TRUE, TRUE, TRUE))

Recall Calculator

Description

Class for recall calculation

Usage

mt_recall()

Value

Metric object

Examples

library(daltoolbox)
obj <- mt_recall()
evaluate(obj, c(TRUE, FALSE, TRUE), c(TRUE, TRUE, TRUE))

ROC AUC Calculator

Description

Class for ROC AUC calculation

Usage

mt_rocauc()

Value

Metric object

Examples

library(daltoolbox)
obj <- mt_rocauc()
evaluate(obj, c(0.9, 0.2, 0.8, 0.1), factor(c(TRUE, TRUE, FALSE, FALSE)))

Multivariate Distribution Based Drifter sub-class

Description

Implements Multivariate Distribution Based drift detectors. These detectors consume one row of a data frame at a time and monitor its numeric columns.

Usage

mv_dist_based(target_feat = NULL)

Arguments

target_feat

Names of the columns to be monitored. NULL (the default) monitors every numeric column.

Value

Drifter object

Examples

obj <- mv_dist_based(target_feat = c("serie1", "serie2"))
obj$target_feat

Concept

Description

A concept learned for one regime, created empty and filled at training. It holds the model, its fitted preprocessing pipeline, the data memory window, the decision threshold th, the learned limits (history) and the selectors' state (cache). uid is assigned at the first training, slot is the pool slot it came from (0 = new) and version tracks data/model changes. Projected into the model's input space with project().

Usage

new_concept(memory)

Arguments

memory

A memory_manager() prototype for the concept's data window.

Value

A concept object.


Normalizer base class

Description

Ancestor class for normalization techniques.

Usage

nrm_base(norm_class)

Arguments

norm_class

Normalizer class

Details

This constructor was named norm() up to version 1.2.x. It was renamed to nrm_base() because norm() masks base::norm() once the package is attached.

Value

Norm object

Examples

library(daltoolbox)
obj <- nrm_base(norm_class = minmax())
class(obj)

Memory Normalizer

Description

Normalizer that keeps its own memory of the data seen so far, so that the normalization parameters are estimated over the whole history rather than over the most recent batch alone.

Usage

nrm_memory(norm_class = daltoolbox::minmax(), max_size = NULL)

Arguments

norm_class

Normalizer class

max_size

Maximum number of rows kept in the memory; the oldest rows are dropped first. NULL (the default) keeps the whole history, so set it on long streams to bound memory.

Value

Norm object

Examples

library(daltoolbox)

obj <- nrm_memory(norm_class = minmax())
obj <- fit(obj, data.frame(x = c(1, 2, 3)))
transform(obj, data.frame(x = c(1, 2, 3)))

One-hot encoding (fitted)

Description

A daltoolbox::dal_transform() that one-hot encodes the categorical columns (factor, character or logical) of a data frame. It learns the categories at fit() and, at transform(), always produces the same columns: a category absent from a batch becomes a zero column and an unseen category is ignored. Numeric columns are kept unchanged. It is the default first step of the preprocessing of adp_recurrent().

Usage

one_hot()

Value

A one_hot object.

Examples

library(daltoolbox)
oh <- fit(one_hot(), iris)
head(transform(oh, iris))

Online Bayesian change point detection (onlineBcp)

Description

Online Bayesian change point detection for normal data of Yigiter et al. (2015), as implemented in the R package onlineBcp (Xu, Yigiter and Chen, 2022). The time since the last change (run length) follows a Markov chain with geometric hazard (1 - theta is the probability of a change at each step), and the segments are normal with a normal-inverse-gamma prior on their mean and variance. At every step the posterior of the last change point location is updated; when its largest value exceeds threshold, that location becomes the last change point and the search restarts from it.

Usage

online_bcp(
  x,
  theta = 0.9,
  alpha = 1,
  beta = 1,
  threshold = 0.5,
  numerics = c("stable", "reference"),
  normality = FALSE
)

Arguments

x

A numeric vector without missing values.

theta

Probability that no change occurs at a step.

alpha, beta

Hyperparameters of the inverse-gamma prior of the variance.

threshold

Threshold of the posterior probability (th_cp).

numerics

"stable" (default) computes the weights in log scale with lgamma(). "reference" computes them as onlineBcp 0.1.4 does, with gamma() and powers that overflow for segments longer than about 340 observations; the overflowing weights are set to 0, which forces change points at multiples of about 341 observations (see Details).

normality

TRUE adds the Kolmogorov-Smirnov normality test of each segment.

Details

The update follows online_cp() of onlineBcp 0.1.4 (https://github.com/ElsevierSoftwareX/SOFTX-D-21-00221). At time t, for every candidate location j from the last change point tau to t,

The code differs from Eq. 3 of the paper in the weight of a new segment, (x^2 / 2 + beta) where the paper writes ⁠(x^2 / 2 + 2 beta)⁠; the code is followed. With numerics = "reference", gamma() overflows when ⁠(t - j + 2 alpha + 1) / 2⁠ exceeds about 171.6, and the weight, then NaN or Inf, is set to 0 as in the code. The change points of the paper's aCGH example at 341, 682 and 1023 come from this overflow; "stable" avoids it.

The segments are built as summary.BayesCP() does. A change point is a location whose posterior exceeds threshold at a step where the location differs from that of the previous step. Segments of one observation are merged with the previous segment of more than one, or with the next one at the start. The interval of each segment mean is ⁠mean +- qnorm(0.95) sd / sqrt(n)⁠ (a 90% interval; the paper calls it 95%). With normality = TRUE, the p-value of the Kolmogorov-Smirnov test of each segment against the normal distribution with its mean and standard deviation is added.

The cost of a step grows with the time since the last change point, so a long sequence without changes takes quadratic time.

Value

An online_bcp object: changepoints (location, the last observation before the change, and its posterior probability), segments (begin, end, mean, SD, interval limits and, optionally, the normality p-value), and trace, one row per step with the largest posterior probability (max_prob), the location (location, 0 when below the threshold) and the run of equal locations (run), as max_p of onlineBcp.

References

Yigiter, A., Chen, J., An, L. and Danacioglu, N. (2015). An on-line CNV detection method for short sequencing reads. Journal of Applied Statistics, 42(7), 1556-1571. https://doi.org/10.1080/02664763.2014.1001330

Xu, H., Yigiter, A. and Chen, J. (2022). onlineBcp: An R package for online change point detection using a Bayesian approach. SoftwareX, 17, 100999. https://doi.org/10.1016/j.softx.2022.100999

See Also

dfr_onlinebcp() to monitor a stream.

Examples

set.seed(1)
x <- c(stats::rnorm(100, 0), stats::rnorm(100, 3), stats::rnorm(100, 0))
result <- online_bcp(x, theta = 0.95, threshold = 0.7)
result$changepoints
result$segments

Predict with REMIND

Description

Predict with REMIND

Usage

## S3 method for class 'adp_recurrent'
predict(object, data, type = c("prob", "class"), ...)

Arguments

object

A adp_recurrent object.

data

Batch of features.

type

"prob" (default): class probabilities. "class": logical vector with the positive-class decision, using the threshold of the concept that answers.

...

Not used.

Value

Predictions with the attributes concept_uid (concept that answered) and check_ratio (its PSI/limit ratio when chosen by the check, NA otherwise).


Project a batch through a concept

Description

Projects a batch into a concept's model input space with the concept's fitted preprocessing pipeline (one-hot encoding then normalization, by default). Shared by the model, the drift detector and the selectors, so none of them reaches into the concept's internals.

Usage

project(concept, data, ...)

Arguments

concept

A new_concept() object with a fitted pipeline.

data

Batch of features.

...

Not used.

Value

The projected batch.


Population Stability Index (PSI)

Description

Compares the distribution of a new sample with a baseline sample, feature by feature, through the Population Stability Index, the symmetrised Kullback-Leibler divergence of their binned distributions (Kurian and Allali, 2024):

PSI = \sum_{i=1}^{B} (P_i - Q_i) \ln(P_i / Q_i),

where Q_i and P_i are the shares of the baseline and of the new sample in bin i. The bins are quantile groups of the baseline (deciles for bins = 10, demi-deciles for bins = 20).

Usage

psi(expected, actual, bins = 10, thresholds = c(0.1, 0.25))

Arguments

expected

The baseline sample: a numeric vector, or a data frame or matrix with one column per feature.

actual

The new sample, with the same features as expected.

bins

Number of quantile groups of the baseline.

thresholds

Limits between the drift levels: PSI below the first is "little" drift, between the two "moderate" drift (to be reviewed), and above the second "significant" drift.

Details

The computation follows the SAS macro of the reference code (https://github.com/FrancisKurian/Kullback, PSI_computation.sas):

  1. The baseline is ranked (ties get their mean rank) and split into bins groups as ⁠PROC RANK GROUPS=⁠: group floor(rank * bins / (n + 1)). Tied values always share a group, so heavily tied data may give fewer bins. Bin i covers the baseline values from its smallest to its largest.

  2. New values below the smallest baseline value or above the largest are moved to it (they fall in the first or the last bin).

  3. The shares are the bin counts over the sample sizes. Missing new values count in the size of the new sample but in no bin, so a stream that starts sending missing values lowers every share. Missing baseline values are left out. A new sample whose values are all missing has every share 0, and so a PSI of 0 (step 4): missing data must be checked separately.

  4. A bin without new values contributes 0, as in the reference (where the logarithm of 0 is missing and the missing part is set to 0).

The reference assigns a value through a SAS format built from the bin ranges; a new value that falls strictly between the largest value of a bin and the smallest of the next one matches no range and is dropped from the counts (but kept in the sample size). Here such a value goes to the lower bin. The paper's thresholds are 0.1 and 0.25 (Section 5; Section 3.1 uses 0.2 for the second). The PSI of two samples from the same distribution is not 0: it is about (bins - 1) (1 / n_expected + 1 / n_actual), which matters for small samples.

Value

A psi object: a list with summary, a data frame with one row per feature (feature, psi, level, number of bins), and bins, a data frame with one row per feature and bin (feature, bin, lower and upper baseline values, expected and actual shares, part, the contribution of the bin).

References

Kurian, J. F. and Allali, M. (2024). Detecting drifts in data streams using Kullback-Leibler (KL) divergence measure for data engineering applications. Journal of Data, Information and Management, 6, 207-216. https://doi.org/10.1007/s42488-024-00119-y

See Also

dfr_psi() to monitor a stream, and dfr_kldist() for the same divergence over a sliding window with equal-width bins.

Examples

set.seed(1)
base <- stats::rnorm(10000, 610, 50)
new <- base
top <- new > 643 & stats::runif(10000) < 0.5
new[top] <- new[top] - 200
result <- psi(base, new)
result$summary
head(result$bins)
psi(base, new, bins = 20)$summary

Criterion to minimize when the check picks a concept

Description

Generic of the concept ranker: given, for each candidate, its PSI and its PSI/limit ratio, return the vector the check minimizes to choose the answering concept.

Usage

rank_criterion(ranker, psi, ratio)

Arguments

ranker

A concept_ranker() object.

psi

Numeric vector: the PSI of each candidate.

ratio

Numeric vector: the PSI/limit ratio of each candidate.

Value

The numeric vector to minimize.


Rank by PSI

Description

Ranker that picks the concept with the smallest PSI, ignoring its limit.

Usage

rank_psi()

Value

A rank_psi object.


Rank by PSI/limit ratio

Description

Ranker that picks the concept with the smallest ratio between its PSI and its limit.

Usage

rank_ratio()

Value

A rank_ratio object.


Drop rare batches

Description

Admission activity that discards a rare batch entirely (it is set aside and does not enter the data windows).

Usage

rare_drop()

Value

A rare_drop object.


Is a batch dropped by the admission policy?

Description

Generic of the batch-admission activity: decide whether the current batch is discarded.

Usage

rare_dropped(policy, usable)

Arguments

policy

A rare_policy() object.

usable

TRUE when the batch has enough positives (>= 1%).

Value

TRUE when the batch is dropped.


Keep rare batches (neutral)

Description

Admission activity that never drops a rare batch: it enters the data windows and only its drift adaptation is postponed. The neutral element of batch admission.

Usage

rare_keep()

Value

A rare_keep object.


Rare-batch admission

Description

Base class of the batch-admission activity (scope: drift_workflow()): what the line does with a labeled batch that has too few positives (< 1% of its rows) to drive adaptation. The variants are rare_keep() (neutral: the batch is not dropped) and rare_drop() (the batch is discarded). In both, a rare batch that arrives before any model is trained is only postponed, since no model can be trained on it yet. New admission rules plug in by subclassing and implementing rare_dropped().

Usage

rare_policy()

Value

A rare_policy object.


Record on every batch (neutral)

Description

Recording activity that lets every batch reaching the concept pool enter the learned limits, whatever the detector reported. The neutral element of limit recording.

Usage

rec_always()

Value

A rec_always object.


Record only on stable batches

Description

Recording activity that keeps a batch out of the learned limits when a real (non-passive) detector flagged a drift on it; passive detectors never block recording.

Usage

rec_stable()

Value

A rec_stable object.


Does the current batch record into the learned limits?

Description

Generic of the recording activity: decide whether the current batch's statistics enter the learned limits of the active concept.

Usage

record_limits(policy, drifted, drift_method)

Arguments

policy

A record_policy() object.

drifted

TRUE when the detector flagged a drift on this batch.

drift_method

The drift detector (its family decides whether a drift blocks recording).

Value

TRUE when the batch records.


Learned-limit recording

Description

Base class of the recording activity (scope: concept): which labeled batches enter the learned limits of the active concept (see learned_limit()). The variants are rec_always() (neutral: every batch that reaches the concept pool records) and rec_stable() (a batch flagged by a real, non-passive detector does not record). New recording rules plug in by subclassing and implementing record_limits().

Usage

record_policy()

Value

A record_policy object.


Recurrent-concept method, ensemble (REMIND-E)

Description

The recurrent-concept method with frozen concepts (train_static()): the pool keeps an ensemble of concepts, reusing (never updating) them across recurring regimes. Reproduces REMIND-E with the published defaults; a named derivation of adp_recurrent().

Usage

recurrent_ensemble(
  method,
  train_size,
  numerical_cols = NULL,
  detector = dfr_passive(),
  n_slots = 20L,
  n_tiles = 5L,
  max_psi = NULL,
  tol_quantile = 0.8,
  memory = memory_undersampling(),
  warmup_size = 100L,
  th = NULL,
  check = NULL
)

Arguments

method

Classifier used by every concept (e.g. torch_cla_mlp).

train_size

Rows needed to train a concept and the sliding-window size.

numerical_cols

Numeric columns the PSI is computed on (NULL: all).

detector

Drift detector (default dfr_passive()).

n_slots

Concept pool size (default 20).

n_tiles

PSI bins (default 5).

max_psi

Fixed PSI limit; NULL (default) learns it from the concept history.

tol_quantile

Quantile of the learned PSI limit (default 0.8).

memory

Memory prototype (default memory_undersampling()).

warmup_size

Minimum rows to train, run the detector and apply the check (default 100).

th

Decision threshold; NULL (default) learns the F1-optimal threshold.

check

NULL (default) disables the predict-time check; a slct_psi() enables it.

Value

An adp_recurrent object.


Recurrent-concept method, incremental (REMIND-I)

Description

The recurrent-concept method with incremental training of the active concept (train_incremental()): the drift detector triggers the concept pool, which stores and reuses concepts across recurring regimes via a PSI selector with a learned limit. Reproduces REMIND-I with the published defaults; a named derivation of adp_recurrent().

Usage

recurrent_incremental(
  method,
  train_size,
  numerical_cols = NULL,
  detector = dfr_passive(),
  n_slots = 20L,
  n_tiles = 5L,
  max_psi = NULL,
  tol_quantile = 0.8,
  epochs = 5L,
  memory = memory_undersampling(),
  warmup_size = 100L,
  th = NULL,
  check = NULL
)

Arguments

method

Classifier used by every concept (e.g. torch_cla_mlp).

train_size

Rows needed to train a concept and the sliding-window size.

numerical_cols

Numeric columns the PSI is computed on (NULL: all).

detector

Drift detector (default dfr_passive()).

n_slots

Concept pool size (default 20).

n_tiles

PSI bins (default 5).

max_psi

Fixed PSI limit; NULL (default) learns it from the concept history.

tol_quantile

Quantile of the learned PSI limit (default 0.8).

epochs

Epochs of each incremental update (default 5).

memory

Memory prototype (default memory_undersampling()).

warmup_size

Minimum rows to train, run the detector and apply the check (default 100).

th

Decision threshold; NULL (default) learns the F1-optimal threshold.

check

NULL (default) disables the predict-time check; a slct_psi() enables it.

Value

An adp_recurrent object.


Reset State

Description

Reset Drifter State

Usage

reset_state(obj)

Arguments

obj

Drifter object

Value

updated Drifter object

Examples

model <- dfr_ddm()
model <- reset_state(model)
model$drifted

Select a concept

Description

Generic called by the concept pool, implemented by each selector with its own evidence: among the stored concepts, choose the one that fits the current batch.

Usage

select_model(obj, concept_list, valid_indices, X, y)

Arguments

obj

A selector object.

concept_list

The stored concepts.

valid_indices

Indices of concept_list eligible in this call.

X

Features of the current batch.

y

Labels of the current batch, NULL when no label is available yet (the check, before the prediction). Selectors that use the feature distribution alone ignore it.

Value

list(cl = concept_list, sc = slot), with sc = 0 when no stored concept fits.


Selector

Description

Base class of the selectors, the concept pool's model_selector: on drift, a selector chooses, among the stored concepts, the one that fits the current batch (or none, so a new concept is created). A selector accepts a stored concept when a statistic between the batch and the concept is within a limit (see learned_limit()): either fixed, or the tol_quantile quantile of the statistics recorded on the batches that belonged to the concept (see update_concept() and concept_pool()). Choosing the slot to replace when the pool is full is a different role, the evictor().

Usage

selector()

Value

A selector object.


Autoencoder selector

Description

Each stored concept has an autoencoder trained on its memory (in the concept's one-hot and normalized space). A concept is accepted when the PSI between the reconstruction errors of its autoencoder on the current batch and on its memory is within its limit; the accepted concept with the smallest PSI is selected. With an incremental trainer (train_incremental()), the autoencoder of the active concept is updated with every batch it receives.

Usage

slct_ae(
  encoding_size,
  ae_class = daltoolboxdp::autoenc_ed,
  batch_size = 32,
  num_epochs = 1000,
  num_epochs_incremental = 100,
  learning_rate = 0.001,
  max_psi = NULL,
  tol_quantile = 0.8,
  n_tiles = 10,
  init_blocks = FALSE
)

Arguments

encoding_size

Number of units of the encoding layer.

ae_class

Autoencoder constructor (e.g. daltoolboxdp::autoenc_ed).

batch_size

Batch size of the autoencoder training.

num_epochs

Epochs of a full autoencoder training.

num_epochs_incremental

Epochs of each incremental update. NULL uses num_epochs.

learning_rate

Learning rate of the autoencoder.

max_psi

Fixed PSI limit. NULL (default): learned for each concept as the tol_quantile quantile of the PSI of the batches that belonged to it.

tol_quantile

Quantile of the learned limit.

n_tiles

Number of quantile bins of the PSI.

init_blocks

With history_init = "blocks" in the concept pool, start the learned limit of a new concept by leave-one-block-out: one autoencoder per block, trained on the rest of the training window. FALSE (default): the history starts empty.

Value

A slct_ae object.


Error selector

Description

Accepts a stored concept when its error on the current (labeled) batch is within a tolerance of its error on its own memory (err_batch <= err_concept + tolerance), and selects the accepted concept with the smallest error on the batch. The error is 1 - metric.

Usage

slct_error_metrics(
  tolerance = NULL,
  tol_quantile = 0.8,
  th = NULL,
  metric = mt_accuracy(),
  init_blocks = FALSE
)

Arguments

tolerance

Fixed additive tolerance. NULL (default): learned for each concept as the tol_quantile quantile of its error gaps (err_batch - err_concept) on the batches that belonged to it.

tol_quantile

Quantile of the learned tolerance.

th

Classification threshold. NULL (default): the threshold of each concept.

metric

Metric object (e.g. mt_accuracy()).

init_blocks

With history_init = "blocks" in the concept pool, start the learned tolerance of a new concept by leave-one-block-out: one model per block, trained on the rest of the training window. FALSE (default): the history starts empty.

Value

A slct_error_metrics object.


Inactive selector

Description

Never changes the concept: always reactivates the concept in slot 1 (the first and only one stored).

Usage

slct_inactive()

Value

A slct_inactive object.


PSI selector

Description

Accepts a stored concept when the mean PSI over the features between the current batch and the concept's memory is within its limit, and selects the accepted concept with the smallest PSI (or PSI/limit ratio, see rank_by). No accepted concept: a new one is created.

Usage

slct_psi(
  max_psi = NULL,
  tol_quantile = 0.8,
  numerical_cols = NULL,
  n_tiles = 10,
  rank_by = c("psi", "ratio")
)

Arguments

max_psi

Fixed PSI limit for every concept (e.g. 0.25). NULL (default): learned for each concept as the tol_quantile quantile of the PSI of the batches that belonged to it.

tol_quantile

Quantile of the learned limit.

numerical_cols

Names of the numerical features. NULL: every numeric column; the other columns are treated as categorical.

n_tiles

Number of quantile bins of the numerical PSI.

rank_by

Order of the accepted concepts: "psi" (smallest PSI) or "ratio" (smallest PSI/limit, ties broken by the PSI). Both coincide with a fixed max_psi.

Value

A slct_psi object.


PSI then best selector

Description

The PSI stage (as in slct_psi()) decides whether the repository covers the current batch: when no stored concept is within its PSI limit, a new concept is created. Otherwise, every stored concept predicts the current (labeled) batch and the one with the highest F1 is selected, whether or not it passed the PSI stage. Ties, and batches where F1 is undefined, are broken by the smallest number of errors (FP + FN).

Usage

slct_psi_then_best(
  max_psi = NULL,
  tol_quantile = 0.8,
  numerical_cols = NULL,
  n_tiles = 10,
  among = c("all", "approved")
)

Arguments

max_psi

Fixed PSI limit. NULL (default): learned (see slct_psi()).

tol_quantile

Quantile of the learned PSI limit.

numerical_cols

Names of the numerical features (see slct_psi()).

n_tiles

Number of quantile bins of the numerical PSI.

among

Concepts compared by F1: "all" (default) every stored concept; "approved" (used in the experiments) only those accepted by the PSI stage.

Value

A slct_psi_then_best object.


PSI then error selector

Description

Combines slct_psi() and slct_error_metrics(): among the concepts accepted by the PSI stage, in increasing order of PSI, selects the first one that also passes the error stage. No concept passing both: a new one is created.

Usage

slct_psi_then_error(
  max_psi = NULL,
  tolerance = NULL,
  tol_quantile = 0.8,
  numerical_cols = NULL,
  n_tiles = 10,
  th = NULL,
  metric = mt_accuracy(),
  init_blocks = FALSE,
  pick = c("first", "min_error")
)

Arguments

max_psi

Fixed PSI limit. NULL (default): learned (see slct_psi()).

tolerance

Fixed error tolerance. NULL (default): learned (see slct_error_metrics()).

tol_quantile

Quantile of both learned limits, PSI and error.

numerical_cols

Names of the numerical features (see slct_psi()).

n_tiles

Number of quantile bins of the numerical PSI.

th

Classification threshold. NULL (default): the threshold of each concept.

metric

Metric object (e.g. mt_accuracy()).

init_blocks

Start the error history by blocks (see slct_error_metrics()). FALSE (default): only the PSI stage starts by blocks.

pick

Among the concepts accepted by the PSI stage: "first" (default) selects the first one, in increasing order of PSI, that also passes the error stage; "min_error" (used in the experiments) selects, among those passing both stages, the one with the smallest error on the batch (ties: the smallest PSI).

Value

A slct_psi_then_error object.


Semiparametric Bayesian network

Description

Fits a semiparametric Bayesian network (Atienza et al., 2022) to continuous data: every node has either a linear Gaussian conditional density or a conditional kernel density estimate (CKDE) given its parents. It is the density model of dfr_llr2().

Usage

spbn(data, structure = NULL, node_types = NULL, max_parents = 4, folds = 5)

Arguments

data

A data frame or matrix of numeric variables (no missing values).

structure

Optional structure: a named list giving the parents of every variable (list(B = "A", C = c("A", "B"), A = character(0))) or a two-column matrix of arcs (from, to). NULL (default) learns it by greedy hill climbing.

node_types

Optional named character vector of node types ("lg" for linear Gaussian, "ckde" for conditional KDE). NULL (default) chooses each node's type by cross-validated log-likelihood.

max_parents

Largest number of parents of a node in the learned structure.

folds

Number of folds of the cross-validation used to choose the node types.

Details

Structure learning is a greedy hill climbing (arc addition, removal and reversal) with the BIC score of a Gaussian Bayesian network. The type of each node is then chosen given its parents: the type with the larger log-likelihood over folds contiguous folds (each fold scored by the CPD fitted on the other folds).

A linear Gaussian CPD is the least-squares regression of the node on its parents with the maximum likelihood variance. A CKDE CPD is f(x, pa) / f(pa), the ratio of Gaussian kernel density estimates with the bandwidth matrix of the normal reference rule, ⁠H = (4 / (d + 2))^(2 / (d + 4)) S N^(-2 / (d + 4))⁠ (S the sample covariance of the node and its parents, d their number, N the sample size); the density of the parents uses the corresponding block of H, so the conditional density integrates to one.

The paper uses the binned version (B-SPBN), which speeds up the kernel sums by binning the data on a grid, and learns the structure and the node types together by hill climbing with a cross-validated score. Here the kernel sums are exact and the node types are chosen after the structure.

Value

An spbn object: the variables, their parents, node types and the fitted CPDs.

References

Atienza, D., Bielza, C. and LarraƱaga, P. (2022). Semiparametric Bayesian networks. Information Sciences, 584, 564-582. https://doi.org/10.1016/j.ins.2021.10.074

See Also

spbn_loglik(), dfr_llr2().

Examples

set.seed(1)
a <- stats::rnorm(500)
b <- 2 * a + stats::rnorm(500, sd = 0.5)
c <- ifelse(stats::runif(500) < 0.5, b - 3, b + 3) + stats::rnorm(500)
model <- spbn(data.frame(a, b, c))
model
colMeans(spbn_loglik(model, data.frame(a, b, c)))

Log-likelihood of each node of a semiparametric Bayesian network

Description

Evaluates ⁠log f(x_i | pa_i)⁠ for every observation and node of an spbn() model.

Usage

spbn_loglik(model, data)

Arguments

model

An spbn object.

data

A data frame or matrix with the model's variables.

Value

A matrix with one row per observation and one column per node.

Examples

set.seed(1)
x <- data.frame(a = stats::rnorm(200), b = stats::rnorm(200))
head(spbn_loglik(spbn(x), x))

Synthetic time series for concept drift detection

Description

A list of univariate and multivariate time series for drift detection. Each element is a data frame:

Except for uv_virtual_drift, every data frame holds the series (serie, or serie1 and serie2), a logical target, the index i and a drift column flagging the change point.

Usage

data(st_drift_examples)

Format

A list of six data frames with 500 rows each.

Source

heimdall package

References

heimdall package

Examples

data(st_drift_examples)
dataset <- st_drift_examples$mv_real_drift
which(dataset$drift == 1)

Incremental training

Description

Training activity that slides the concept's data window and updates the model with the current batch only, keeping its weights and preprocessing.

Usage

train_incremental(epochs = NULL)

Arguments

epochs

Epochs of each incremental update. NULL (default) keeps the model's own epochs.

Value

A train_incremental object.


Retraining

Description

Training activity that, at every labeled batch, slides the concept's data window and retrains the model from scratch on the concept memory.

Usage

train_retrain()

Value

A train_retrain object.


Static training (frozen concept)

Description

Training activity that never updates a concept after its first full training: the concept memory and model stay frozen. The neutral element of model evolution.

Usage

train_static()

Value

A train_static object.


Transform pipeline

Description

A daltoolbox::dal_transform() that chains a sequence of transforms. fit() fits each step on the output of the previous one, and transform() applies the fitted steps in order. It lets a model take its preprocessing as a configurable list of transforms instead of a fixed one-hot-plus-normalization.

Usage

trans_pipeline(steps)

Arguments

steps

A list of dal_transform objects (unfitted prototypes), applied in order.

Value

A trans_pipeline object.

Examples

library(daltoolbox)
pipe <- trans_pipeline(list(one_hot(), zscore()))
pipe <- fit(pipe, iris)
head(transform(pipe, iris))

SN-TS2Vec change point model

Description

Trains the unsupervised SN-TS2Vec model of Bazarova et al. (2024), as used in the WWAggr code: the TS2Vec encoder of Yue et al. (2022) (a linear input layer and residual blocks of dilated convolutions with GELU) with spectral normalisation of the convolutions, trained with the hierarchical contrastive loss of TS2Vec on two overlapping random crops of every sequence. The change score of a step is 1 minus the cosine similarity of the max-pooled embeddings of the two consecutive windows that end at it (see cpd_scores()).

Usage

ts2vec(
  x,
  window = 4,
  output_dim = 32,
  hidden_dim = 128,
  depth = 8,
  spectral_norm = TRUE,
  mask = c("binomial", "continuous", "all_true"),
  temporal_unit = 0,
  max_train_length = NULL,
  learning_rate = 0.001,
  weight_decay = 0.2,
  batch_size = 128,
  epochs = 40,
  patience = 40,
  validation = NULL,
  step = 1,
  alpha = 1,
  seed = NULL
)

Arguments

x

Training sequences, in the formats accepted by indid().

window

Length of the history and future windows of the scores.

output_dim, hidden_dim

Sizes of the embedding and of the hidden channels.

depth

Number of hidden residual blocks (one more maps to output_dim).

spectral_norm

Whether the convolutions are spectrally normalised (largest singular value at most 1).

mask

Masking of the input during training: "binomial" (each step kept with probability 0.5), "continuous" (5 masked segments of 10 % of the length) or "all_true" (no masking).

temporal_unit

Smallest level of the hierarchy with a temporal loss.

max_train_length

If set, longer training sequences are cut at a random offset to this length.

learning_rate, weight_decay

Settings of AdamW; the learning rate follows a cosine schedule with warm restarts (periods of 10 epochs, then 1000).

batch_size

Number of sequences per batch.

epochs

Largest number of epochs.

patience

Early stopping on the validation loss (only with validation data).

validation

Optional validation sequences.

step, alpha

Prediction settings, as in tscp2().

seed

Seed of the private random stream (weights, crops, masks, dropout, order of the batches). NULL draws one from the session.

Details

The model follows the reference code (https://github.com/stalex2902/wwagr-ensemble-cpd, src/baselines/ts2vec_sn.py and prediction_utils.py):

The network, its gradients and AdamW are written in R. The defaults are those of the Human Activity configuration of the reference (configs/human_activity_ts2vec.yaml).

Value

A ts2vec object with the parameters, the power iteration vectors, the settings and the losses of every epoch.

References

Bazarova, A., Romanenkova, E. and Zaytsev, A. (2024). Normalizing self-supervised learning for provably reliable change point detection. 2024 IEEE International Conference on Data Mining (ICDM), 21-30.

Yue, Z., Wang, Y., Duan, J., Yang, T., Huang, C., Tong, Y. and Xu, B. (2022). TS2Vec: Towards universal representation of time series. Proceedings of the AAAI Conference on Artificial Intelligence, 36(8), 8980-8987.

Stepikin, A., Romanenkova, E. and Zaytsev, A. (2025). WWAggr: A window Wasserstein-based aggregation for ensemble change point detection. 2025 IEEE International Conference on Data Mining (ICDM), 1535-1544. https://doi.org/10.1109/ICDM65498.2025.00163

See Also

cpd_scores(), cpd_ensemble(), dfr_wwaggr().

Examples

set.seed(1)
x <- array(stats::rnorm(8 * 12 * 2), c(8, 12, 2))
model <- ts2vec(x, window = 3, output_dim = 4, hidden_dim = 6, depth = 2, epochs = 2, seed = 1)
model

TS-CP2 change point model

Description

Trains the unsupervised TS-CP2 model of Deldari et al. (2021), as re-implemented in the WWAggr code: a temporal convolutional network (TCN) embeds windows of window steps; it is trained with a contrastive (InfoNCE-like) loss so that each history window is close to the window that follows it and far from the other windows of the batch. The change score of a step is 1 minus the cosine similarity of the embeddings of the two consecutive windows that end at it (see cpd_scores()).

Usage

tscp2(
  x,
  window = 4,
  nb_filters = 64,
  kernel_size = 5,
  nb_stacks = 2,
  dilations = c(1, 2, 4, 8),
  use_skip_connections = TRUE,
  batch_norm = FALSE,
  n_steps = 8,
  code_size = 4,
  temperature = 0.1,
  learning_rate = 0.001,
  decay_steps = 1000,
  batch_size = 8,
  epochs = 200,
  patience = 5,
  min_delta = 1e-04,
  step = 1,
  alpha = 1,
  seed = NULL
)

Arguments

x

Training sequences, in the formats accepted by indid(). Only the first 2 * window steps of every sequence are used (a history window and the future window that follows it).

window

Length of the history and future windows.

nb_filters

Number of filters of the convolutions.

kernel_size

Kernel size of the convolutions.

nb_stacks, dilations

The TCN has nb_stacks stacks of residual blocks, one per dilation.

use_skip_connections

Whether the skip connection of the last block is added to the output of the TCN.

batch_norm

Whether the convolutions are followed by batch normalisation.

n_steps, code_size

Sizes of the dense layers: 2 * n_steps, n_steps and the embedding (code_size).

temperature

Temperature of the contrastive loss.

learning_rate

Learning rate of Adam, annealed by a cosine schedule of period decay_steps epochs.

decay_steps

Period of the cosine annealing (T_max, in epochs).

batch_size

Number of sequences per batch.

epochs

Largest number of epochs.

patience, min_delta

Early stopping on the training loss: training stops after patience epochs whose loss is not below the best one minus min_delta.

step, alpha

Prediction settings: the similarity is computed every step steps, and the scores are smoothed by an exponential moving average with factor alpha (1: none).

seed

Seed of the private random stream (initial weights and order of the batches). NULL draws one from the session.

Details

The model follows the reference code (https://github.com/stalex2902/wwagr-ensemble-cpd, src/baselines/tscp.py and prediction_utils.py):

The dropout of the reference (rate 0 in its configurations) and its layer and weight normalisation options (not functional there) are not implemented. The network, its gradients and Adam are written in R. The defaults are those of the Human Activity configuration of the reference (configs/human_activity_tscp.yaml).

Value

A tscp2 object with the parameters, the batch normalisation statistics, the settings and the training loss of every epoch.

References

Deldari, S., Smith, D. V., Xue, H. and Salim, F. D. (2021). Time series change point detection with self-supervised contrastive predictive coding. Proceedings of The Web Conference 2021, 3124-3135. https://doi.org/10.1145/3442381.3449903

Stepikin, A., Romanenkova, E. and Zaytsev, A. (2025). WWAggr: A window Wasserstein-based aggregation for ensemble change point detection. 2025 IEEE International Conference on Data Mining (ICDM), 1535-1544. https://doi.org/10.1109/ICDM65498.2025.00163

See Also

cpd_scores(), cpd_ensemble(), dfr_wwaggr().

Examples

set.seed(1)
x <- array(stats::rnorm(16 * 12 * 2), c(16, 12, 2))
model <- tscp2(x, window = 4, nb_filters = 4, dilations = c(1, 2), n_steps = 4, code_size = 3,
               epochs = 3, seed = 1)
model

Update concept

Description

Keeps the selector's per-concept state up to date with the current batch. REMIND calls it for the active concept at every batch, before (stage = "before") and after (stage = "after") the drift decision. Selectors receive phase = "observe" (record the batch in the learned limits, when record = TRUE) or phase = "adapt" (adapt the active concept to the batch, e.g. the autoencoder of slct_ae).

Usage

update_concept(obj, concept, X, y, ...)

Arguments

obj

A concept_pool or selector object.

concept

The active concept.

X

Current batch (features).

y

Current batch (target).

...

stage, record and trainer (concept_pool); phase, record and trainer (selector).

Value

The updated concept.


Update State

Description

Update Drifter State with a new observation.

Usage

update_state(obj, value, ...)

Arguments

obj

Drifter object

value

a value that represents a processed batch

...

optional arguments

Value

a list with two elements: obj, the updated Drifter object, and drift, a logical flag indicating whether a drift was detected in this call

Examples

model <- dfr_ddm()
output <- update_state(model, 0)
output$drift

WWAggr and naive aggregations of ensemble scores

Description

Aggregates the change point scores of the members of an ensemble (cpd_scores() of a cpd_ensemble()) into one score per time step. WWAggr (Stepikin et al., 2025) compares, at every step, the scores of all members in a "future" window of the last window_size steps with those in an anchor ("history") window, by the Wasserstein distance of the two samples (the window flattened over steps and members) or by the maximum mean discrepancy; the naive aggregations take the mean, minimum, maximum, median or a quantile of the members at every step.

Usage

wwaggr(
  scores,
  method = c("wasserstein", "mmd", "mean", "min", "max", "median", "quantile"),
  window_size = 3,
  anchor = c("prev", "start", "combined"),
  p = 1,
  kernel = c("rbf", "multiscale"),
  bandwidth = NULL,
  q = 0.5
)

Arguments

scores

Scores of the members: an array ⁠[member, sequence, time]⁠ or a matrix ⁠[member, time]⁠ (one sequence).

method

"wasserstein" (WWAggr, default), "mmd", "mean", "min", "max", "median" or "quantile".

window_size

Size of the windows (distance methods).

anchor

Anchor window: "prev" (default, the window_size steps before the future window, as Algorithm 1 of the paper), "start" (the first window_size steps of the sequence) or "combined" (the first window_size %/% 2 steps followed by the window_size %/% 2 steps before the last ones; the future window then has 2 * (window_size %/% 2) steps).

p

Order of the Wasserstein distance.

kernel

Kernel of the MMD: "rbf" or "multiscale".

bandwidth

Bandwidths of the MMD kernel. NULL uses those of the reference: 10, 15, 20 and 50 (rbf) or 0.2, 0.5, 0.9 and 1.3 (multiscale).

q

Quantile of the "quantile" method (the median is 0.5, the minimum 0 and the maximum 1; linear interpolation as torch.quantile).

Details

The steps where some member has no score (the first steps of the representation models) are left out, as in the reference code, and get NA. For the distance methods, the score of the i-th remaining step (i > window_size) compares the future window of steps i - window_size to i - 1 with the anchor window, and the first window_size scores are 0 (anchor_window_detector_batch of the reference, src/ensembles/ distances.py). For "prev", the anchor starts at max(1, i - 2 * window_size).

The 1-Wasserstein distance of two samples of the same size is the mean absolute difference of their order statistics, and the p-Wasserstein distance the p-th root of the mean of their p-th powers. The MMD treats the steps of a window as samples and the members as dimensions; it is the mean of ⁠k(x, x') + k(y, y') - 2 k(x, y')⁠ over all pairs, with the sum of the kernels of all bandwidths: ⁠exp(-d / (2 a))⁠ (rbf) or a^2 / (a^2 + d) (multiscale), d the squared distance. With calibrated members, the scores are in ⁠[0, 1]⁠ and so is the 1-Wasserstein distance, so that a threshold around 0.5 works without tuning (Section IV of the paper).

Value

A matrix ⁠[sequence, time]⁠ of aggregated scores, or a vector for one sequence.

References

Stepikin, A., Romanenkova, E. and Zaytsev, A. (2025). WWAggr: A window Wasserstein-based aggregation for ensemble change point detection. 2025 IEEE International Conference on Data Mining (ICDM), 1535-1544. https://doi.org/10.1109/ICDM65498.2025.00163

Examples

set.seed(1)
# 10 members, 2 sequences of 30 steps; the change is at step 16.
scores <- array(stats::runif(10 * 2 * 30, 0, 0.2), c(10, 2, 30))
scores[, , 16:30] <- scores[, , 16:30] + 0.7
round(wwaggr(scores, window_size = 3)[1, 12:22], 2)
round(wwaggr(scores, method = "mean")[1, 12:22], 2)