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 .
- Real concept drift: 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 changes. The rule is the same but the inputs move, often into regions the model has rarely seen.
- Prior shift: the class proportions change (fraud rises from 1 % to 3 %).
Drift also differs in how it unfolds over time:
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 (was the prediction of example wrong?), because a real concept drift shows up as more errors. That needs labels, possibly delayed; detectors on 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 . With the running mean and a tolerance :
While the mean is stable, each term is slightly negative on average (because of ), so drifts downwards and stays near its minimum. When the mean rises, the terms turn positive and climbs away from . The threshold trades detection delay against false alarms; 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 examples, with error rate and standard deviation , it remembers the point where was smallest, , and signals
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 the label is ; from then on it is : 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 (, ) and DDM watch its error stream. The run is done twice: once only detecting, once resetting the model when DDM signals drift.
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 to 2499 is 0.130 instead of 0.390, and by 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 , 30 streams of 3,000 steps, and count how fast each detector finds the change and how often it fires before it.
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 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. raises none in these runs and needs 202 steps; needs 523. DDM sits in between on delay (284) but with false alarms similar to . 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 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. 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
- In Page-Hinkley, what happens if is set larger than the change you want to detect (for example for a rise from 0.10 to 0.20)?
- Why does DDM use and not just ?
- A model for a ski shop's sales sees the same drift every November and every April. Which reaction strategy suits it?
Answers
- After the change, the terms are still negative on average (the mean rises by 0.10, less than ), so keeps falling and the detector never fires. must be smaller than the smallest change worth detecting.
- Early on, is estimated from few examples and is noisy. Adding , which shrinks like , 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 is one where the estimate was both low and reliable.
- 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?
- A change in the input distribution only
- A change in : the same input now has a different correct label
- A bug in the model
- More data arriving
In Page-Hinkley, what does raising the threshold do?
- Faster detection, more false alarms
- Slower detection, fewer false alarms
- Nothing
- It changes the model's learning rate
DDM signals drift when…
- the error rate falls
In the sudden-drift example, why did the model without a reaction recover so slowly?
- The detector never fired
- Its decaying learning rate was small by , so each update moved the weights only a little
- The data had no labels
- The drift was virtual