Forecasting dengue from open weather data: lags, leakage and lead time
Weather shapes dengue with a delay of weeks, and that delay is what makes early warning possible. How to build lagged weather features, validate a forecaster in time order and judge it by lead time, with Malaysia as the example.
Rain, temperature and humidity affect dengue with a delay: mosquitoes need time to breed, and the virus needs time to develop inside the mosquito and then inside a person. A useful forecaster turns that delay into lagged weather features, is tested only on weeks after its training data, and is judged by how many weeks of warning it gives, not by its error alone.
That idea underpins our paper Forecasting Dengue Outbreaks in Malaysia: A Machine Learning Approach Using Open Weather Data (MECON 2026), which built a predictive framework on open-source meteorological data to forecast dengue outbreak trends across Malaysia for early warning and public-health preparedness. This article walks through the modelling choices that make such a forecaster trustworthy, with code you can adapt.
Key points
- Weather acts on dengue through the mosquito life cycle, so its effect shows up weeks later. Lagged features encode that.
- Any input measured after the forecast date leaks the future. Build features so that this cannot happen by accident.
- Validate with walk-forward splits: train on the past, test on the next block, move forward, repeat.
- Report accuracy by forecast horizon. A forecast that is accurate one week ahead may be useless at four.
Why does weather predict dengue weeks later?
Dengue in Malaysia is spread mainly by Aedes mosquitoes. Each link in the chain between weather and reported cases takes time:
- Breeding. Rain fills containers where Aedes lay eggs. In warm conditions, the step from egg to adult mosquito takes around a week or more.
- Development in the mosquito. After biting an infected person, the virus must replicate before the mosquito can transmit it. This extrinsic incubation period shortens as temperature rises and is commonly put at one to two weeks.
- Incubation in people. Symptoms usually appear 4 to 10 days after an infective bite (WHO).
- Reporting. Diagnosis, notification and weekly aggregation add further delay.
Added together, weather this week is most informative about cases several weeks from now. That is a gift for forecasting: the predictors arrive before the outcome.
Turning delays into features
A lagged feature is the value of a weather variable k weeks before the week being predicted. Rolling sums or means capture accumulated conditions, such as total rainfall over the past month:
Open archives such as NASA POWER or Open-Meteo provide daily rainfall, temperature and humidity by location, which can be aggregated to the epidemiological week used in case reports. Past case counts are usually the strongest single predictor and belong in the model too, lagged like everything else.
import pandas as pd
weekly = (weather.set_index("date")
.resample("W-SAT") # epidemiological weeks
.agg({"rain_mm": "sum", "t_mean": "mean", "rh_mean": "mean"}))
df = weekly.join(cases.set_index("week_end")["cases"]).sort_index()
H = 4 # forecast horizon: predict cases 4 weeks after the last observed week
for col in ["rain_mm", "t_mean", "rh_mean"]:
for k in range(0, 9): # 0 to 8 weeks back
df[f"{col}_lag{k}"] = df[col].shift(k)
df[f"{col}_roll4"] = df[col].rolling(4).mean()
for k in range(0, 5):
df[f"cases_lag{k}"] = df["cases"].shift(k)
df["target"] = df["cases"].shift(-H) # the future value we want
df = df.dropna()
features = [c for c in df.columns if "_lag" in c or "_roll" in c]
Every feature on row t uses data from week t or earlier, and the target is H weeks later. Keeping this rule in one place, the shift calls, is the simplest defence against leakage.
Look-ahead bias: the leak that makes forecasts look clairvoyant
Look-ahead bias happens when a model is trained or evaluated with information that would not have been available when the forecast was made. Common forms in disease forecasting:
- Same-week weather for a same-week target. If you predict this week’s cases, this week’s weather is only partly known until the week ends.
- Rolling windows centred on the date. A centred moving average uses future values; use trailing windows only.
- Scaling or imputing on the full series. Fit scalers and imputers on training data only, inside the cross-validation loop.
- Revised case counts. Surveillance data are often corrected later. A model trained on final counts will look better than one that must work with first reports.
Walk-forward validation
A random K-fold split mixes past and future. Walk-forward validation (scikit-learn’s TimeSeriesSplit) trains on an expanding window of history and tests on the block that follows, then moves on:
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import TimeSeriesSplit
tscv = TimeSeriesSplit(n_splits=5, gap=H) # gap keeps the horizon out of training
scores = []
for train_idx, test_idx in tscv.split(df):
train, test = df.iloc[train_idx], df.iloc[test_idx]
model = RandomForestRegressor(random_state=0).fit(train[features], train["target"])
pred = model.predict(test[features])
mae = np.mean(np.abs(test["target"] - pred))
naive = np.mean(np.abs(test["target"] - test["cases_lag0"])) # "same as now" baseline
scores.append((mae, naive))
for i, (mae, naive) in enumerate(scores, 1):
print(f"fold {i}: model MAE {mae:.1f} vs persistence MAE {naive:.1f}")
The gap argument leaves H weeks between the end of training and the start of testing, so rows whose target falls inside the test period cannot leak into training. The persistence baseline, “cases in H weeks will equal cases now”, is the bar any model has to clear.
Lead time: the number that matters to a health officer
A forecast is a function of its horizon h:
Accuracy almost always falls as h grows, while usefulness rises: a vector-control team needs time to inspect breeding sites, run clean-up campaigns and brief clinics. So report results as a curve of error against horizon, and mark the horizon at which the model stops beating the persistence baseline. That point, not a single RMSE, tells a public-health team how much warning they can rely on.
For outbreak decisions, a threshold view is often clearer than raw counts: does the model correctly flag the weeks in which cases will exceed the local epidemic threshold, and how many weeks in advance?
What open weather data cannot tell you
Weather explains a share of dengue variation, not all of it. Forecasts should say so:
- Population immunity and serotype shifts can drive large outbreaks in otherwise ordinary weather.
- Interventions, such as fogging or clean-up campaigns, change the relationship the model learned.
- Peaks are the hardest part. Published forecasting studies regularly note that short, sharp peaks remain difficult to predict even when overall trends are captured well.
- Local conditions such as water storage habits, construction sites and drainage are invisible in gridded weather data.
Frequently asked questions
Which weather variables predict dengue best?
Rainfall, temperature and humidity are the most commonly used, usually with lags of several weeks and as rolling totals or means. Past case counts are typically the strongest single predictor and should be included as lagged features too.
How far ahead can dengue be forecast from weather data?
It depends on the location and data quality. Biological delays make a few weeks of warning plausible; the reliable horizon should be measured with walk-forward validation against a persistence baseline rather than assumed.
Why not use a random train-test split for disease forecasting?
A random split puts future weeks into training and neighbouring weeks into testing, so the model appears to forecast when it is really interpolating. Time-ordered, walk-forward validation reflects how the model will be used.
Does this replace epidemiological surveillance?
No. A weather-driven forecaster is an early-warning aid that works alongside surveillance and local knowledge, not a substitute for them.
The study and its co-authors are listed on the dengue forecasting project page.
Related articles
Measuring vehicle speed from a roadside camera: from pixels to km/h
Detect, track, calibrate, measure: the full pipeline for estimating vehicle speed and spotting lane changes in traffic video, with the homography maths, OpenCV code and lessons for placing cameras on mixed-traffic roads.
Why AQI models report R² = 0.99, and how to evaluate them honestly
Near-perfect scores in air-quality papers usually say more about the evaluation than the model. Target leakage, random splits and seasonal blind spots explained, with the seasonally stratified set-up from our Dhaka study.
SHAP vs LIME vs feature importance: which explanation should you trust?
SHAP, LIME and built-in feature importance answer different questions. A side-by-side comparison on one decision-tree classifier, with the maths, runnable Python and a table for choosing between them.