TExcelTAD

Detecting Concept Drift: Page-Hinkley and DDM

An online model learns from a stream on the assumption that tomorrow looks like today. It often does not. Fraudsters change tactics, a sensor is recalibrated, a pandemic changes what people buy, a competitor changes prices. When the relation between inputs and labels changes, that is concept drift, and a model trained on the old concept quietly becomes wrong. With a decaying learning rate, as in the previous lesson, it also adapts too slowly to recover on its own. A drift detector watches a statistic of the stream, usually the model's error, and raises an alarm when it changes, so the system can react: retrain, reset, or roll back.

Distribution shift covered how shift damages a trained model's evaluation. This lesson is about detecting it in a stream, as it happens.

Kinds of drift

Write the data distribution as P(x,y)=P(x) P(y∣x)P(\mathbf{x}, y) = P(\mathbf{x}) \, P(y \mid \mathbf{x}).

  • Real concept drift: P(y∣x)P(y \mid \mathbf{x}) changes. The same input now has a different answer (a transaction pattern that was safe is now fraud). The decision boundary must move.
  • Virtual drift (covariate shift): only P(x)P(\mathbf{x}) changes. The rule is the same but the inputs move, often into regions the model has rarely seen.
  • Prior shift: the class proportions P(y)P(y) change (fraud rises from 1 % to 3 %).

Drift also differs in how it unfolds over time:

sudden gradual incremental recurring BA timetimetimetime

Sudden drift is the easiest to detect and the most damaging; gradual and incremental drift are harder to tell from noise; recurring drift (seasons, weekdays) suggests keeping old models around instead of discarding them.

Detectors on the error stream

Most detectors watch the model's prequential error et∈{0,1}e_t \in \{0, 1\} (was the prediction of example tt wrong?), because a real concept drift shows up as more errors. That needs labels, possibly delayed; detectors on P(x)P(\mathbf{x}) alone (comparing feature distributions with a statistical test) catch virtual drift without labels but also raise alarms for shifts that do not hurt the model.

Page-Hinkley is a cumulative-sum test for a rise in the mean of a signal xtx_t. With xˉt\bar{x}_t the running mean and a tolerance δ\delta:

mT=∑t=1T(xt−xˉt−δ),MT=min⁡t≤Tmt,alarm if mT−MT>λm_T = \sum_{t=1}^{T} \big(x_t - \bar{x}_t - \delta\big), \qquad M_T = \min_{t \le T} m_t, \qquad \text{alarm if } m_T - M_T > \lambda

While the mean is stable, each term is slightly negative on average (because of δ\delta), so mTm_T drifts downwards and stays near its minimum. When the mean rises, the terms turn positive and mTm_T climbs away from MTM_T. The threshold λ\lambda trades detection delay against false alarms; δ\delta is the size of change you are willing to ignore.

DDM (Drift Detection Method, Gama et al., 2004) treats the error count as binomial. After ii examples, with error rate pip_i and standard deviation si=pi(1−pi)/is_i = \sqrt{p_i (1 - p_i) / i}, it remembers the point where pi+sip_i + s_i was smallest, (pmin⁡,smin⁡)(p_{\min}, s_{\min}), and signals

warning if pi+si≥pmin⁡+2smin⁡,drift if pi+si≥pmin⁡+3smin⁡\text{warning if } p_i + s_i \ge p_{\min} + 2 s_{\min}, \qquad \text{drift if } p_i + s_i \ge p_{\min} + 3 s_{\min}

after a minimum of 30 examples. The warning level is meant for starting to collect recent examples, so that a new model can be trained on them as soon as the drift level confirms the change. Both detectors are reset after an alarm. Variants such as EDDM (distances between errors) and ADWIN (an adaptive window that drops old data when two sub-windows differ significantly) are implemented, with many others, in streaming libraries such as river.

From scratch: a sudden drift

A stream of 4,000 points in 2-D with 5 % label noise. Until t=2000t = 2000 the label is 1[x1+x2>0]\mathbb{1}[x_1 + x_2 > 0]; from then on it is 1[x1−x2>0]\mathbb{1}[x_1 - x_2 > 0]: the boundary turns by 90 degrees, so half of the plane changes its answer. The model is the online logistic regression of the previous lesson, evaluated test-then-train. Page-Hinkley (δ=0.005\delta = 0.005, λ=25\lambda = 25) and DDM watch its error stream. The run is done twice: once only detecting, once resetting the model when DDM signals drift.

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

class PageHinkley:
    """Alarm when the mean of the input rises: m_T - min_t m_t > lam."""
    def __init__(self, delta=0.005, lam=25.0):
        self.delta, self.lam = delta, lam
        self.reset()
    def reset(self):
        self.n, self.mean, self.m, self.m_min = 0, 0.0, 0.0, 0.0
    def update(self, x):
        self.n += 1
        self.mean += (x - self.mean) / self.n                  # running mean of the input
        self.m += x - self.mean - self.delta                   # cumulative deviation
        self.m_min = min(self.m_min, self.m)
        return self.m - self.m_min > self.lam                  # True = drift

class DDM:
    """Drift Detection Method (Gama et al., 2004) on a stream of 0/1 errors."""
    def __init__(self, min_n=30):
        self.min_n = min_n
        self.reset()
    def reset(self):
        self.n, self.p, self.p_min, self.s_min = 0, 1.0, np.inf, np.inf
    def update(self, error):
        self.n += 1
        self.p += (error - self.p) / self.n                    # error rate so far
        s = np.sqrt(self.p * (1 - self.p) / self.n)
        if self.n < self.min_n:
            return "ok"
        if self.p + s < self.p_min + self.s_min:
            self.p_min, self.s_min = self.p, s                 # best point seen so far
        if self.p + s >= self.p_min + 3 * self.s_min:
            return "drift"
        if self.p + s >= self.p_min + 2 * self.s_min:
            return "warning"
        return "ok"

# A stream of 4000 points; at t = 2000 the concept changes: the boundary turns by 90 degrees
rng = np.random.default_rng(0)
T, t_drift = 4000, 2000
X = rng.normal(size=(T, 2))
w_old, w_new = np.array([1.0, 1.0]), np.array([1.0, -1.0])
y = np.where(np.arange(T) < t_drift, X @ w_old > 0, X @ w_new > 0).astype(int)
y ^= (rng.random(T) < 0.05)                                    # 5 % label noise

def run(react):
    w, b, t0 = np.zeros(2), 0.0, 0
    ph, ddm = PageHinkley(), DDM()
    errors, alarms = [], []
    for t in range(T):
        p = 1 / (1 + np.exp(-(X[t] @ w + b)))
        err = int((p > 0.5) != y[t])                           # test ...
        errors.append(err)
        eta = 0.5 / np.sqrt(t - t0 + 1)
        w -= eta * (p - y[t]) * X[t]; b -= eta * (p - y[t])   # ... then train
        ph_alarm, state = ph.update(err), ddm.update(err)
        if ph_alarm: alarms.append(("Page-Hinkley", t))
        if state == "drift": alarms.append(("DDM", t))
        if react and state == "drift":
            w, b, t0 = np.zeros(2), 0.0, t                     # start a fresh model
            ph.reset(); ddm.reset()
        elif ph_alarm:
            ph.reset()
    return np.array(errors), alarms

curves = {}
for react in (False, True):
    errors, alarms = run(react)
    curves[react] = errors
    first = {}
    for name, t in alarms:
        first.setdefault(name, t)
    print(f"react to DDM: {react}")
    print(f"  first alarms: " + ", ".join(f"{k} at t={v}" for k, v in first.items()))
    print(f"  alarms before the drift: {sum(t < t_drift for _, t in alarms)}")
    for a, b in ((1500, 2000), (2000, 2500), (2500, 3000), (3500, 4000)):
        print(f"  error rate t={a}..{b - 1}: {errors[a:b].mean():.3f}")

fig, ax = plt.subplots(figsize=(6.4, 3.2))
k = 100                                                        # moving average over 100 steps
for react, label in ((False, "no reaction"), (True, "reset on DDM drift")):
    ax.plot(np.arange(k - 1, T), np.convolve(curves[react], np.ones(k) / k, "valid"), label=label)
ax.axvline(t_drift, color="grey", ls="--", lw=1)
ax.set_xlabel("t"); ax.set_ylabel("error rate (last 100)"); ax.legend()
ax.set_title("Sudden drift at t = 2000")
fig.tight_layout()
react to DDM: False
  first alarms: DDM at t=2040, Page-Hinkley at t=2052
  alarms before the drift: 0
  error rate t=1500..1999: 0.056
  error rate t=2000..2499: 0.390
  error rate t=2500..2999: 0.220
  error rate t=3500..3999: 0.090
react to DDM: True
  first alarms: DDM at t=2040
  alarms before the drift: 0
  error rate t=1500..1999: 0.056
  error rate t=2000..2499: 0.130
  error rate t=2500..2999: 0.074
  error rate t=3500..3999: 0.056

Both detectors are silent for the 2,000 examples before the change, and both fire soon after it: DDM 40 examples after the drift, Page-Hinkley 52. Without a reaction, the model's error jumps from 0.056 to 0.390 and takes well over a thousand examples to come back down (0.090 in the last 500), because its decaying learning rate makes every step small by then. Resetting the model at the DDM alarm restarts it with a fresh, large learning rate: the error over t=2000t = 2000 to 2499 is 0.130 instead of 0.390, and by t=2500t = 2500 the model is back at its old level (0.074, then 0.056). The plot shows the moving error rate of both runs.

A reset is the bluntest reaction. It throws away everything, including the parts of the old concept that still hold. Better reactions retrain on the examples collected since the DDM warning, keep the learning rate from decaying below a floor, or switch to a model trained on a recent window, keeping the old one in case the concept recurs.

Delay against false alarms

A detector with a low threshold fires quickly but also fires on noise; a high threshold is quiet but late. To measure the trade-off, simulate error streams directly: an error rate of 0.10 that rises to 0.20 at t=1500t = 1500, 30 streams of 3,000 steps, and count how fast each detector finds the change and how often it fires before it.

python · try it yourself
import numpy as np

def page_hinkley(xs, delta=0.005, lam=25.0):
    """Return the time steps at which Page-Hinkley raises an alarm (restarting after each)."""
    alarms, n, mean, m, m_min = [], 0, 0.0, 0.0, 0.0
    for t, x in enumerate(xs):
        n += 1; mean += (x - mean) / n
        m += x - mean - delta; m_min = min(m_min, m)
        if m - m_min > lam:
            alarms.append(t); n, mean, m, m_min = 0, 0.0, 0.0, 0.0
    return alarms

def ddm(errors, min_n=30):
    alarms, n, p, p_min, s_min = [], 0, 0.0, np.inf, np.inf
    for t, e in enumerate(errors):
        n += 1; p += (e - p) / n
        s = np.sqrt(p * (1 - p) / n)
        if n < min_n: continue
        if p + s < p_min + s_min: p_min, s_min = p, s
        if p + s >= p_min + 3 * s_min:
            alarms.append(t); n, p, p_min, s_min = 0, 0.0, np.inf, np.inf
    return alarms

# Error streams of length 3000: error rate 0.10, rising to 0.20 at t = 1500 (or never)
T, t_change, runs = 3000, 1500, 30
detectors = {"PH lambda=10": lambda e: page_hinkley(e, lam=10), "PH lambda=25": lambda e: page_hinkley(e, lam=25),
             "PH lambda=50": lambda e: page_hinkley(e, lam=50), "DDM": ddm}
print(f"{'detector':13s} {'detected':>9s} {'mean delay':>11s} {'false alarms per 1000':>22s}")
for name, detect in detectors.items():
    delays, false = [], 0
    for seed in range(runs):
        rng = np.random.default_rng(seed)
        rate = np.where(np.arange(T) < t_change, 0.10, 0.20)
        alarms = detect((rng.random(T) < rate).astype(float))
        false += sum(t < t_change for t in alarms)
        after = [t for t in alarms if t >= t_change]
        if after:
            delays.append(after[0] - t_change)
    print(f"{name:13s} {len(delays):5d}/{runs} {np.mean(delays):11.0f} {1000 * false / (runs * t_change):22.2f}")
detector       detected  mean delay  false alarms per 1000
PH lambda=10     30/30         133                   0.58
PH lambda=25     30/30         202                   0.00
PH lambda=50     30/30         523                   0.00
DDM              30/30         284                   0.64

All detectors find the change in all 30 streams, but at very different costs. Page-Hinkley with λ=10\lambda = 10 is fastest (133 steps on average) and raises 0.58 false alarms per 1,000 steps of the stable period, about one every 1,700 steps. λ=25\lambda = 25 raises none in these runs and needs 202 steps; λ=50\lambda = 50 needs 523. DDM sits in between on delay (284) but with false alarms similar to λ=10\lambda = 10. Which point is right depends on costs: a false alarm that triggers an expensive retraining and a human review is different from one that only resets a cheap online model. Run this simulation with your own error rate and the size of change you need to catch, and choose λ\lambda from it.

Pitfalls

  • Labels arrive late. Fraud labels come after chargebacks, weeks later. Error-based detectors then see the drift weeks late; monitor input distributions and prediction distributions as early warnings.
  • Detecting what does not matter. A feature distribution can shift without hurting accuracy (virtual drift in an irrelevant feature). Alarms that lead nowhere erode trust; prefer error-based detection when labels exist, and check the effect before retraining.
  • One threshold for every stream. λ\lambda depends on the base error rate and the noise. Calibrate on historical data or a simulation, as above.
  • Not resetting the detector. After an alarm, the statistics still contain the old concept; without a reset, DDM keeps signalling drift for every example.
  • Reacting by forgetting everything. A reset discards knowledge that still applies; with recurring drift, keep old models and switch back.
  • Multiple testing. Monitoring hundreds of features with a test each guarantees alarms by chance; correct the thresholds or aggregate.

Practice

  1. In Page-Hinkley, what happens if δ\delta is set larger than the change you want to detect (for example δ=0.2\delta = 0.2 for a rise from 0.10 to 0.20)?
  2. Why does DDM use pi+sip_i + s_i and not just pip_i?
  3. A model for a ski shop's sales sees the same drift every November and every April. Which reaction strategy suits it?
Answers
  1. After the change, the terms xt−xˉt−δx_t - \bar{x}_t - \delta are still negative on average (the mean rises by 0.10, less than δ\delta), so mTm_T keeps falling and the detector never fires. δ\delta must be smaller than the smallest change worth detecting.
  2. Early on, pip_i is estimated from few examples and is noisy. Adding sis_i, which shrinks like 1/i1/\sqrt{i}, makes the test compare upper confidence bounds: a high error rate counts as drift only when it is high beyond its own uncertainty, and the reference point (pmin⁡,smin⁡)(p_{\min}, s_{\min}) is one where the estimate was both low and reliable.
  3. Recurring drift: keep a summer model and a winter model (or a model with season features) and switch when the detector fires or by calendar, instead of retraining from scratch each time.

Test yourself

What is real concept drift?

  1. A change in the input distribution only
  2. A change in P(y∣x)P(y \mid x): the same input now has a different correct label
  3. A bug in the model
  4. More data arriving

In Page-Hinkley, what does raising the threshold λ\lambda do?

  1. Faster detection, more false alarms
  2. Slower detection, fewer false alarms
  3. Nothing
  4. It changes the model's learning rate

DDM signals drift when…

  1. pi+si≥pmin⁡+3smin⁡p_i + s_i \ge p_{\min} + 3 s_{\min}
  2. pi>0.5p_i > 0.5
  3. the error rate falls
  4. si=0s_i = 0

In the sudden-drift example, why did the model without a reaction recover so slowly?

  1. The detector never fired
  2. Its decaying learning rate ηt=0.5/t\eta_t = 0.5/\sqrt{t} was small by t=2000t = 2000, so each update moved the weights only a little
  3. The data had no labels
  4. The drift was virtual