Part IV: Deep Learning for Sensor Time Series
Chapter 18: Uncertainty, Calibration, and Conformal Prediction

Adaptive conformal inference (ACI) and conformal PID under drift

"You promised me ninety percent coverage. The sensor promised me a stationary world. One of you lied, and I have to pick which knob to turn."

A Feedback-Minded AI Agent

The Big Picture

Split conformal prediction gives an exact finite-sample coverage guarantee, but only under exchangeability: the calibration data and the test point must be interchangeable. Real sensor streams violate this constantly. A battery ages, a machine warms up, a user changes gait, weather shifts a chemical sensor's baseline. The moment the score distribution drifts, a frozen conformal threshold silently under-covers or over-covers, and you find out only when something downstream breaks. This section treats coverage as a control problem. Instead of computing one quantile and trusting it forever, we watch the running miscoverage rate and steer the interval width online. Adaptive conformal inference (ACI) is the integral controller; conformal PID adds proportional and derivative terms so the interval anticipates drift instead of merely reacting to it.

This section assumes you have the split-conformal machinery and the exchangeability failure from Section 18.4, the notion of a nonconformity score, and the coverage-versus-width tradeoff. It also leans on the drift and change-detection vocabulary from Chapter 12 and the online-learning setting of Chapter 60. If the probabilistic framing of coverage feels thin, the primer in Chapter 4 is the place to shore it up.

Why a frozen threshold fails on a moving stream

Recall the split-conformal recipe. You hold out a calibration set, compute nonconformity scores \(s_i = s(x_i, y_i)\), and take the threshold \(\hat q\) as the \(\lceil (n+1)(1-\alpha)\rceil / n\) empirical quantile. The prediction set is \(C(x) = \{y : s(x,y) \le \hat q\}\). Marginal coverage \(\mathbb{P}(y \in C(x)) \ge 1-\alpha\) holds because the test score is exchangeable with the calibration scores, so its rank is uniform.

Drift breaks the rank argument. Suppose a vibration model was calibrated on a bearing at 40 degrees Celsius and the machine now runs at 70 degrees. Residuals grow, scores shift right, and the fraction of test points exceeding the old \(\hat q\) climbs past \(\alpha\). Coverage decays exactly when the operating condition is most unusual, which is the worst possible time to be over-confident. Re-calibrating on a sliding window helps but chases a target it never catches, and it needs fresh ground-truth labels that a deployed sensor rarely has in real time. We want a guarantee that survives arbitrary, even adversarial, distribution change.

Key Insight

ACI abandons the goal of exact per-step coverage and instead guarantees long-run average coverage under any sequence, including adversarial drift. The price is honest: the interval width can swing, and any single step may be badly covered. What you buy is a distribution-free promise that, averaged over time, the empirical miscoverage converges to \(\alpha\) no matter how the world moves. That trade is exactly right for a sensor deployed for years across seasons and hardware aging.

Adaptive conformal inference as an integral controller

The idea from Gibbs and Candes (2021) is to make the target level itself adaptive. Keep a state variable \(\alpha_t\), form the set \(C_t\) at the \(1-\alpha_t\) quantile of recent scores, observe whether the truth landed inside, and nudge \(\alpha_t\) by the coverage error. Define the miscoverage indicator \(\mathrm{err}_t = \mathbf{1}[y_t \notin C_t]\). The update is a single line:

$$\alpha_{t+1} = \alpha_t + \gamma\,(\alpha - \mathrm{err}_t).$$

When you miss (\(\mathrm{err}_t = 1\)), \(\alpha_{t+1}\) drops, so next step demands a higher quantile and a wider interval. When you cover (\(\mathrm{err}_t = 0\)), \(\alpha_{t+1}\) rises and the interval tightens. The step size \(\gamma\) is the learning rate. This is precisely integral control: \(\alpha_t\) accumulates the running coverage error and drives it to zero. Summing the recursion telescopes into a clean bound. For scores in a bounded range, the realized miscoverage satisfies

$$\left| \frac{1}{T}\sum_{t=1}^{T} \mathrm{err}_t - \alpha \right| \le \frac{\alpha_1 + \gamma}{\gamma\,T},$$

so the time-averaged coverage converges to \(1-\alpha\) at rate \(O(1/T)\), for every input sequence, with no distributional assumption whatsoever. Larger \(\gamma\) tracks abrupt shifts faster but makes the width jittery; smaller \(\gamma\) is smooth but sluggish after a regime change. A common default is \(\gamma \approx 0.005\) to \(0.05\), tuned so the width settles within your acceptable reaction time.

Practical Example: a wind-turbine gearbox monitor

An offshore turbine fleet runs a temporal-convolutional model (see Chapter 14) that forecasts gearbox oil temperature one hour ahead; the maintenance system trips an alert when the true value escapes the prediction interval. Static split conformal, calibrated in spring, delivered 90 percent coverage on the bench. By August the ambient rose, load patterns changed, and live coverage sagged to 78 percent: false alerts every windy afternoon. Swapping the frozen threshold for ACI with \(\gamma = 0.02\) let \(\alpha_t\) drift wider through the hot months and retighten in autumn. Rolling 30-day coverage held at 89 to 91 percent across the whole year, and nuisance alerts fell by more than half, all without a single new label being shipped from the platform.

Conformal PID: proportional and derivative terms

ACI is the integral term alone, and integral-only control has a known weakness: it lags. Under a steady trend (scores creeping up week over week), an integrator is always a step behind, so it chronically under-covers by a small margin. Angelopoulos, Candes, and Tibshirani (2024) reframe the whole thing as PID control of the conformal threshold and add the missing terms. Rather than steering \(\alpha_t\), they directly track the score quantile \(q_t\) with three contributions:

$$q_{t+1} = \underbrace{r_t\!\Big(\sum_{i\le t}(\mathrm{err}_i - \alpha)\Big)}_{\text{integral (ACI)}} \;+\; \underbrace{\eta\,(\mathrm{err}_t - \alpha)}_{\text{proportional}} \;+\; \underbrace{g_{t+1}}_{\text{derivative / scorecaster}}.$$

The integral term is ACI in a saturating wrapper \(r_t\) that keeps the state from winding up during long violations. The proportional term reacts to the instantaneous error for faster settling. The derivative term is the interesting one: instead of a naive difference, it is a scorecaster, a small forecaster (even the same class of model you use for the signal, per Chapter 16) that predicts next step's conformal score \(g_{t+1}\). When the scorecaster sees a rising residual trend it widens the interval before the misses accumulate, giving lead compensation. Crucially, the same long-run coverage guarantee holds regardless of how good or bad the scorecaster is: a useless scorecaster degrades gracefully to plain ACI, while an accurate one sharply reduces the transient under-coverage after a change point.

import numpy as np

def aci_stream(scores, y_in_set_fn, alpha=0.1, gamma=0.02, window=200):
    """Online ACI over a drifting score stream. Returns per-step coverage flags."""
    alpha_t, covered = alpha, []
    buf = []  # recent scores used as the running calibration set
    for t, s_t in enumerate(scores):
        if len(buf) >= 20:                      # need some history to form a quantile
            level = np.clip(1.0 - alpha_t, 0.0, 1.0)
            q_t = np.quantile(buf, level)        # adaptive threshold
            hit = y_in_set_fn(t, q_t)            # did truth fall inside C_t?
        else:
            hit = True
        covered.append(hit)
        err_t = 0.0 if hit else 1.0
        alpha_t = alpha_t + gamma * (alpha - err_t)   # integral update
        buf.append(s_t)
        if len(buf) > window:
            buf.pop(0)
    return np.array(covered)
A minimal ACI loop: a sliding score buffer supplies the quantile, and the single-line integral update on alpha_t steers coverage toward 1 - alpha even as the stream drifts. The window keeps the calibration set fresh; gamma sets tracking speed.

The loop above shows the mechanism, and it is worth running once to feel how \(\gamma\) trades jitter against lag. In production you would not hand-roll the buffer, the winsorized quantile, and the PID saturation.

Library Shortcut

The reference conformal-time-series package from the PID paper exposes ACI, quantile tracking, and the full P/I/D controller with a pluggable scorecaster in about 5 lines: instantiate the controller, then q = ctrl.predict(); ctrl.update(err) per step. MAPIE's MapieTimeSeriesRegressor similarly wraps adaptive conformal prediction with rolling recalibration. That is roughly a 10-to-1 line reduction versus the hand-rolled loop, and the library handles the state saturation (anti-windup), the bounded-score edge cases, and the scorecaster interface that are easy to get subtly wrong. Reach for it once you have understood the update above; leakage-safe evaluation of the stream (never letting future scores calibrate past predictions) is still your responsibility.

Choosing knobs and reading the width signal

Three practical rules carry most of the value. First, tune \(\gamma\) (and the proportional \(\eta\)) to the fastest drift you must survive, not the average one: pick the shortest change-point-to-recovery time you can tolerate and set the gain so the width settles inside it. Second, treat the interval width itself as a first-class monitoring signal. A width that is quietly ballooning is the controller telling you the model has drifted out of its competence; that is a maintenance trigger and a natural handoff to the abstention logic of Section 18.6. Third, remember the guarantee is average, not conditional: ACI can hold 90 percent overall while systematically missing one rare regime. If per-condition coverage matters (a safety case for a specific fault mode), combine adaptive updates with the conditional or Mondrian conformal ideas from the previous section, and validate under the distribution-shift protocols of Chapter 66.

Research Frontier

Current work pushes beyond scalar coverage control. Gibbs and Candes' 2024 fully adaptive conformal inference maintains a family of experts over multiple gains and aggregates them, removing the single-\(\gamma\) tuning burden. Bhatnagar and colleagues' strongly adaptive online conformal prediction (SAOCP) guarantees coverage on every sub-interval, not just the full horizon, which matters when drift is bursty. Zaffran and coworkers analyze ACI stability for time series with autocorrelated errors. And decision-theoretic conformal risk control generalizes the miscoverage indicator to arbitrary monotone losses, so the same PID machinery can steer false-negative rate on an anomaly detector rather than raw interval coverage. Expect these to converge into the streaming uncertainty layer of sensor foundation models.

Exercise

Take any 1-D forecaster and a sensor stream with an injected mid-series level shift (for example, add a constant to the target after the halfway point). (a) Run static split conformal calibrated on the first quarter and plot rolling coverage; observe the collapse after the shift. (b) Run the aci_stream loop for \(\gamma \in \{0.005, 0.02, 0.1\}\) and overlay rolling coverage and interval width. (c) Add a two-line scorecaster (predict next score as the mean of the last five) and report how much the post-shift recovery window shrinks. Summarize the width-versus-lag tradeoff you observe.

Self-Check

1. Split conformal guarantees exact marginal coverage; ACI guarantees only long-run average coverage. Why is the weaker guarantee the more useful one on a deployed sensor?

2. In the update \(\alpha_{t+1} = \alpha_t + \gamma(\alpha - \mathrm{err}_t)\), which direction does \(\alpha_t\) move after a miss, and what does that do to the next interval's width?

3. What failure of integral-only control does the derivative (scorecaster) term fix, and why does a poor scorecaster not break the coverage guarantee?

What's Next

In Section 18.6, we turn a ballooning conformal interval into a decision: when the width or the drift signal says the model is out of its depth, the system should abstain, fall back to a conservative estimate, or hand off to a human. We build the abstention thresholds and safety margins that sit on top of the adaptive coverage machinery from this section.