ratulsikder.me / all projects

forecast.ratulsikder.me

outbreak-forecast-mlops

End-to-end MLOps for probabilistic dengue outbreak forecasting: LightGBM + conformal intervals, walk-forward backtests, MLflow registry with promotion gate, FastAPI serving, drift monitoring

  • conformal-prediction
  • dengue
  • epidemiology
  • fastapi
  • lightgbm
  • mlflow
  • mlops
  • time-series-forecasting

Probabilistic weekly dengue forecasts with outbreak alerts, built like a production ML system.

CI Python 3.12 License: MIT

This project forecasts laboratory-confirmed dengue cases in San Juan, Puerto Rico, 1 to 4 weeks ahead, with calibrated 90% prediction intervals. It raises an outbreak alert when the upper bound crosses the historical endemic channel for that week of the year. It succeeds my earlier dengue-spread and trajectory-prediction notebooks, and the point here is the system around the model:

  • versioned, checksummed data
  • one feature pipeline shared by training and serving
  • walk-forward backtesting
  • an MLflow registry with a champion/challenger promotion gate
  • a FastAPI service that hot-swaps on promotion
  • Prometheus metrics
  • drift monitoring that triggers retraining

Every number and chart below comes from running the pipeline end to end on the public CDC / Puerto Rico Department of Health data (see DATA.md).

Not medical advice. This is an engineering showcase on a historical benchmark dataset that ends in 2013. It is not a validated public-health tool. See Limitations.

Architecture

flowchart LR
    subgraph Data
        A[CDC/PRDH weekly cases<br/>CC BY 4.0] --> I[ofm ingest<br/>SHA-256 pinned fetch]
        B[NOAA GHCN-Daily<br/>station climate] --> I
        I --> V{{Pandera<br/>contracts}}
        V --> W[(weekly table<br/>parquet)]
    end
    subgraph Training
        W --> F[features.py<br/>lags, rolling stats,<br/>lagged climate, seasonality]
        F --> T[ofm train<br/>LightGBM + CQR intervals]
        T --> R[(MLflow registry<br/>@staging)]
        R --> BT[ofm backtest<br/>walk-forward vs baseline]
        BT --> G{ofm promote<br/>gate}
        G -- pass --> P[(@production)]
        G -- fail --> X[rejected]
    end
    subgraph Serving
        P -- alias poll + hot swap --> API[FastAPI /predict<br/>same features.py]
        API --> L[(prediction log<br/>JSONL)]
        API --> PR[Prometheus<br/>metrics + alert rules]
    end
    subgraph Monitoring
        L --> M[ofm monitor<br/>PSI + KS drift, realised<br/>accuracy, alert precision]
        W --> M
        M -- drift trigger --> T
    end
ConcernImplementation
DataPinned upstream commit, SHA-256 verified, Pandera schemas on raw, weekly and every serving request
Featuressrc/ofm/features.py, one code path for training and serving; parity proven by test
ModelsSeasonal-naive baseline; LightGBM point model on log1p(cases); LightGBM quantile models with conformalized quantile regression (CQR) per horizon
EvaluationRolling-origin backtest, expanding window, refit every 26 weeks; MAE, MASE, 90% PI coverage, width, interval score
RegistryMLflow 3 (SQLite backend, proxied artifacts), aliases @staging, @production, @previous-production
GateMust beat baseline MASE, beat production MASE on identical rows, keep coverage at or above 0.80
ServingFastAPI, /predict /health /metrics, alias polling with zero-downtime hot swap, JSONL request/response log
MonitoringOwn PSI + two-sample KS (SciPy), prediction drift, realised accuracy as truth arrives, alert precision/recall, retrain trigger
Orchestrationofm Typer CLI + Makefile; cron example in deploy/crontab; compose monitor job service

Results (real run)

Walk-forward backtest

Training window: 1990-04-30 to 2009-04-23, the end of the 2008/09 season and the same split the 2015 CDC forecasting challenge used. Forecast origins run from 2003-04 to 2009-03 with 12 refits and 1,248 forecasts per model (312 origins x 4 horizons).

modelMAEMASE90% PI coveragemean PI widthinterval score
LightGBM-CQR, climate + cases (promoted, v1)8.050.2090.91339.343.8
LightGBM-CQR, cases only (challenger, v2)9.300.2410.904n/an/a
Seasonal-naive baseline22.920.6000.927152.4175.4

By horizon (v1):

horizon (weeks)MAEMASEcoveragemean PI width
16.480.1680.90733.6
27.580.1970.92336.6
38.440.2190.91341.6
49.690.2520.91045.2

MASE is scaled by the in-sample seasonal-naive (lag 52) MAE of each fold's training data. The lagged climate features account for the 0.241 to 0.209 gap: same model, same folds, climate removed. Raw outputs: reports/backtest.md, reports/backtest.json.

Walk-forward backtest, 4-week-ahead forecasts with 90% intervals

The 4-week-ahead forecast catches the 2005 and 2007 epidemics but trails the peaks by a week or two, which is the usual cost of lead time.

Promotion gate in action

versionprofilegate outcomewhy
v1lgbm-climatepromotedMASE 0.209 vs baseline 0.600; no production yet; coverage 0.913
v2lgbm-cases-onlyrejectedMASE 0.241 vs production 0.209 on the same 12 folds (exit code 3)
v3lgbm-climate, retrained through 2013-04promotedMASE 0.509 vs frozen v1 0.531 on 816 forecasts v1 never saw; vs baseline 0.422 vs 1.393

Each decision is logged as an MLflow run and in reports/promotion_v*.json.

Production replay, drift and automatic retraining

With v1 serving, the 208 held-out weeks (2009-05 to 2013-04) were replayed against the API one origin at a time, as a surveillance feed would post them. All 208 requests returned 200, at a mean /predict latency of about 15 ms in the container, and 73 origins raised an outbreak alert. The span includes the 2010 epidemic, the largest in Puerto Rico's recorded history.

Forecasts served by the API vs observed, with outbreak alerts

Alerts fire from January 2010, months ahead of the July/August 2010 peak, because winter incidence was far above the endemic channel.

The ofm monitor --retrain report for the last 52 served origins (2012-04-29 to 2013-04-23):

signalvaluetrigger
features drifted (PSI >= 0.2 and KS p < 0.01)61%>= 30%, fired
prediction PSI vs training reference3.45>= 0.25, fired
realised MAE / 90% coverage (188 scored forecasts)27.1 / 0.947coverage < 0.80 would fire
outbreak-alert precision / recall vs threshold exceedance0.753 / 1.000reported

Top PSI features

The drift is real, not a test artefact. 2012/13 was a high-incidence season, and the upstream metadata notes a more sensitive PCR assay from 2009. Diurnal temperature range at the station also moved. The trigger retrained the production profile on data through 2013-04-23 (v3) and ran the gate.

The first gate run exposed a design flaw. Re-fitting the champion's config on the candidate's folds produced the identical model, so a same-config refresh could never win. Production is now judged as the frozen artifact on the weeks after its train_end, against the candidate on exactly those rows. On that basis v3 won 0.509 vs 0.531 MASE and was promoted. The running API picked up @production = v3 within about 20 s, with no restart. The improvement is modest: v3's intervals are tighter (75.6 vs 89.4) but slightly under-cover on those weeks (0.898 vs 0.956), and its interval score is worse (103.0 vs 96.8).

Quickstart

Requirements: Docker, uv, Python 3.12.

bash
uv sync
make up                                   # MLflow :5050, API :8000, Prometheus :9090
export OFM_TRAIN_END=2009-04-28           # hold out 2009-2013 for the replay
uv run ofm ingest                         # fetch + verify + validate -> data/processed/
uv run ofm train --profile lgbm-climate   # -> registry @staging
uv run ofm backtest                       # -> reports/backtest.*, docs/img/backtest_forecast.png
uv run ofm promote                        # gate -> @production (API hot-swaps)
uv run ofm replay --start 2009-04-30      # simulated production traffic
uv run ofm monitor --retrain              # drift report, retrain + gate on trigger
make down                                 # remove containers and the MLflow volume

The MLflow UI is at http://localhost:5050. Port 5000 is avoided because macOS reserves it for AirPlay. Host ports can be changed with OFM_MLFLOW_HOST_PORT, OFM_API_HOST_PORT and OFM_PROMETHEUS_HOST_PORT; every runtime setting is an OFM_* environment variable (src/ofm/config.py).

bash
curl -s localhost:8000/predict -H 'content-type: application/json' -d @request.json

Response from the real run (v1, origin 2010-06-25, during the 2010 epidemic; truncated to two horizons):

json
{
  "request_id": "readme-demo",
  "model_name": "ofm-dengue-san-juan",
  "model_version": "1",
  "origin": "2010-06-25",
  "interval_level": 0.9,
  "outbreak_alert": true,
  "forecasts": [
    {"horizon": 1, "target_week": "2010-07-02", "point": 121.647, "lower": 42.964,
     "upper": 231.152, "threshold": 72.135, "alert": true},
    {"horizon": 4, "target_week": "2010-07-23", "point": 115.612, "lower": 32.273,
     "upper": 316.058, "threshold": 113.593, "alert": true}
  ]
}

The request body is {"observations": [...]}: at least 55 consecutive weeks of week_start, cases, tmax, tmin, tavg, tdtr, prcp, rain_days, oldest first. Too little history, out-of-order or missing weeks, negative counts or implausible climate values get a 422 and increment ofm_validation_errors_total.

Prometheus metrics: ofm_requests_total, ofm_request_latency_seconds, ofm_outbreak_alerts_total{horizon}, ofm_forecast_point and ofm_forecast_upper, ofm_validation_errors_total, ofm_model_info{version}. Alert rules are in deploy/alerts.yml.

Design decisions

  • Direct multi-horizon, one model. Rows are (origin t, horizon h) -> y[t+h], with h as a feature. There is no recursive error compounding, and one model serves every horizon.
  • Train/serve parity by construction. Every feature at origin t uses shift(k >= 0) and trailing windows only. The target week's calendar features are projected from the origin date, not read from the future row. tests/test_features.py rebuilds serving features from truncated histories at 25 random origins and asserts exact equality with the training matrix. It also poisons all future rows and asserts the features do not change.
  • Leak-free walk-forward. At cutoff c, training rows need t + h <= c, so training targets are observed by c, and all test targets lie after c. tests/test_splits.py asserts this on every fold.
  • Positional weeks, not calendar arithmetic. The upstream epi-weeks are not all 7 days long (23 of the 1,195 week-to-week gaps are 8 or 9 days). Lags count rows, climate is aggregated onto the real [start_i, start_{i+1}) edges, and precipitation is normalised to 7 days.
  • Log scale + CQR. Training on log1p stabilises variance between quiet years and epidemics. Quantiles commute with monotone transforms, so the intervals need no bias correction. Quantile-loss boosting alone has no coverage guarantee, so per-horizon CQR offsets are fit on a purged temporal holdout (the latest 25% of origins). The backtest coverage of 0.913 for nominal 0.90 is the check.
  • Endemic-channel alerting. The threshold per ISO week is geometric mean + 1.96 SD of historical counts in a +/-2-week window, the standard surveillance-programme definition. Alerts use the upper bound: missing an outbreak costs more than a false alarm.
  • Gate on identical rows. Champion and challenger are always compared on the same forecasts: either a config re-fit on the same folds (new model type, same data), or the frozen production artifact on weeks it never saw (refresh on new data). Coverage has a floor, so an overconfident model cannot win on MAE alone.
  • One deployable unit. The MLflow pyfunc bundles the model, the CQR offsets, the endemic channel, and the drift reference features and predictions. The API and the monitor can never disagree about which reference goes with which model.
  • Lean infra. MLflow uses SQLite with proxied local artifacts instead of Postgres + MinIO. The workload is small, and --backend-store-uri / --artifacts-destination are the only changes needed to move to managed stores.
  • Drift needs two signals. A feature only counts as drifted when PSI and KS agree, which damps false alarms on 52-row windows.

Testing and CI

uv run pytest runs 46 tests covering:

  • schema contracts
  • feature parity and no-future-leakage
  • splitter leakage
  • the conformal quantile
  • baseline correctness
  • the gate policy, including frozen-champion mode
  • PSI/KS
  • the API contract: health, predict, 422s, 503 without a model, metrics, prediction log
  • an end-to-end ingest -> train -> backtest -> promote -> reject -> retrain cycle against a throwaway MLflow store

ruff and mypy --strict are clean.

The GitHub Actions jobs:

  • lint-types
  • test
  • training-smoke: slow tests, plus the CLI pipeline on the fixture slice against a real MLflow server container
  • docker: builds the API image

Limitations

  • Not medical advice, and not a validated early-warning system. Real deployments need epidemiologist review, prospective evaluation and local thresholds.
  • Data latency is ignored. The replay assumes a week's lab-confirmed count is final when it is posted. In practice counts are backfilled for weeks, so nowcasting the reporting delay would come first.
  • Historical benchmark. The data ends in April 2013. Diagnostic sensitivity changed over the period (PCR in 2005 and 2009, better IgM in 2007), so part of the measured drift is measurement, not epidemiology.
  • One location, one station. Climate comes from a single airport station, not an area average. Serotype dynamics, population immunity and mobility are not modelled.
  • Peak timing lags. As the backtest chart shows, the 4-week-ahead point forecast trails epidemic peaks. The intervals and the alert rule carry the early-warning signal.
  • Coverage is marginal, not conditional. CQR targets average coverage. Intervals can be too narrow inside an epidemic and too wide outside one.

Data and licence

Code: MIT. Data: CC BY 4.0 (Puerto Rico Department of Health and CDC) and NOAA GHCN-Daily (U.S. public domain). Attribution and citations are in DATA.md.