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.
An air-quality model that scores R² ≈ 0.99 has usually been handed the answer. The Air Quality Index is calculated from pollutant concentrations, so feeding those same pollutants back in as inputs lets a model reconstruct the index instead of predicting it. Random train–test splits on daily data add a second leak, because neighbouring days are near-copies of each other. An honest AQI model predicts ahead, keeps time order and is tested in every season.
Search for “AQI prediction machine learning” and you will find a long list of studies reporting R² above 0.98 for XGBoost, Random Forest or gradient boosting. Some of these models may be excellent. But the number alone cannot tell you, because the same score comes out of a set-up that leaks the target. This article explains the three most common leaks and the evaluation design we used in Air Quality Crisis Prediction in Dhaka: Benchmarking Machine Learning with Seasonal Brick Kiln Features (MECON 2026), where we benchmarked Random Forest, XGBoost and Support Vector Regression for daily AQI prediction under seasonally stratified evaluation.
Key points
- AQI is a deterministic function of pollutant concentrations. Same-day pollutants as inputs turn prediction into recalculation.
- Daily air quality is strongly autocorrelated, so a random split puts near-duplicate days on both sides of the line.
- A model can look accurate on average while failing in the one season that matters most. Evaluate each season separately.
- Report errors in AQI units (RMSE, MAE) per season, not only a pooled R².
How is the AQI calculated, and why does it matter?
In the US EPA method, which many national schemes follow closely, each pollutant p gets a sub-index by linear interpolation inside the breakpoint band that contains its concentration C_p. The AQI is the highest sub-index:
C_lo and C_hi are the breakpoints around the measured concentration, and I_lo and I_hi are the index values assigned to them. The whole calculation is piecewise linear in the pollutant concentrations. A tree ensemble given PM2.5, PM10, NO₂, O₃, SO₂ and CO for the same day can learn this function almost perfectly. That is a test of curve fitting, not of forecasting.
Leak 1: the target hides in the inputs
If the goal is to warn people about tomorrow, the model may only use what is known today. That rules out tomorrow’s pollutant readings, and it also rules out today’s AQI components if you claim to predict today’s AQI. Useful inputs are lagged pollutant values, weather forecasts, calendar effects and known emission patterns.
Here h is the forecast horizon, x are observed pollutant and weather values up to today, w is the weather forecast for the target day, and s are seasonal or calendar features. Nothing on the right-hand side is measured on day t + h.
Leak 2: random splits on daily data
Air quality on Tuesday looks a lot like air quality on Monday and Wednesday. With a random 80/20 split, most test days have their neighbours in the training set, so the model can interpolate between them. The score measures memory, not foresight. Splits must respect time: train on the past, test on the future, and leave a gap if inputs include rolling windows.
Leak 3: one season dominates the average
Dhaka’s air has a strong seasonal cycle. In the dry season, roughly November to March, brick kilns around the city operate and pollution peaks; the monsoon washes the air. A pooled error can look small because most days are easy, while the dry-season peaks, the days that matter for health warnings, are predicted badly. Two changes address this:
First, give the model the season explicitly. In our study we added a binary brick-kiln-season feature:
Second, evaluate per season. Seasonally stratified evaluation makes sure every season is represented in the test data and reports errors season by season, so a model cannot hide a dry-season failure behind a good monsoon.
Seasonally stratified evaluation, step by step
The script below is a simplified sketch of this kind of set-up, not the code used in the paper (that is in the project repository). It predicts tomorrow’s AQI from lagged values only, holds out the last part of every season in every year, and reports RMSE and MAE per season.
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.svm import SVR
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from xgboost import XGBRegressor
df = pd.read_csv("daily_aqi.csv", parse_dates=["date"]).sort_values("date")
# Target: tomorrow's AQI. Inputs: only what is known today.
df["target"] = df["aqi"].shift(-1)
for lag in (0, 1, 2, 7):
df[f"aqi_lag{lag}"] = df["aqi"].shift(lag)
df[f"pm25_lag{lag}"] = df["pm25"].shift(lag)
df["kiln_season"] = df["date"].dt.month.isin([11, 12, 1, 2, 3]).astype(int)
df["doy_sin"] = np.sin(2 * np.pi * df["date"].dt.dayofyear / 365.25)
df["doy_cos"] = np.cos(2 * np.pi * df["date"].dt.dayofyear / 365.25)
df = df.dropna()
season = {12: "dry", 1: "dry", 2: "dry", 3: "pre-monsoon", 4: "pre-monsoon", 5: "pre-monsoon",
6: "monsoon", 7: "monsoon", 8: "monsoon", 9: "monsoon", 10: "post-monsoon", 11: "post-monsoon"}
df["season"] = df["date"].dt.month.map(season)
df["block"] = df["date"].dt.year.astype(str) + "-" + df["season"]
# Stratified, time-ordered split: the last 20% of every season block is test data.
is_test = df.groupby("block")["date"].transform(lambda d: d.rank(pct=True) > 0.8)
features = [c for c in df.columns if c.endswith(("lag0", "lag1", "lag2", "lag7"))] + \
["kiln_season", "doy_sin", "doy_cos"]
train, test = df[~is_test], df[is_test]
models = {
"Random Forest": RandomForestRegressor(random_state=0),
"XGBoost": XGBRegressor(random_state=0),
"SVR": make_pipeline(StandardScaler(), SVR(kernel="rbf")),
}
for name, model in models.items():
model.fit(train[features], train["target"])
test = test.assign(pred=model.predict(test[features]))
per_season = test.groupby("season").apply(lambda g: pd.Series({
"RMSE": np.sqrt(((g.target - g.pred) ** 2).mean()),
"MAE": (g.target - g.pred).abs().mean()}))
print(name, per_season.round(1), sep="\n")
Note what is missing: no same-day pollutant columns for the target day, no shuffling, and no single pooled score.
RMSE and MAE: which one to report?
Report both, in AQI units:
MAE is the typical miss. RMSE squares errors before averaging, so it grows when a model misses pollution spikes, which are exactly the days a warning system exists for. A large gap between RMSE and MAE is a sign that the model handles ordinary days but not peaks.
Random Forest, XGBoost and SVR: what each brings
| Random Forest | XGBoost | Support Vector Regression | |
|---|---|---|---|
| How it learns | Averages many deep trees grown on bootstrap samples | Adds shallow trees one at a time, each correcting the last | Fits a function within an ε-tube using kernel similarity |
| Strengths | Robust defaults, little tuning, hard to overfit badly | Strong on tabular data, handles missing values, fine control | Smooth predictions, works well on small, scaled datasets |
| Watch out for | Cannot extrapolate beyond training range, so it under-predicts record peaks | Many hyperparameters; easy to overfit a leaky validation set | Needs feature scaling; slow on long daily series |
| Explainability | TreeSHAP | TreeSHAP | KernelSHAP (slower) |
Comparing three different model families under one protocol is more informative than tuning one model to a high score. If all three agree on which season is hardest, that is a property of the data, not of the model.
A checklist for reading AQI papers
- Are pollutant concentrations from the target day among the inputs?
- Is the split random, or does the test set come strictly after the training set?
- Is there a forecast horizon, and is it stated?
- Are errors reported per season, or only pooled?
- Are errors given in AQI units (RMSE, MAE), or only as R²?
- Is there a simple baseline, such as “tomorrow equals today”, to compare against?
A model that beats persistence in the dry season, on data it has never seen, is worth more than any R² of 0.999.
Frequently asked questions
Why do so many AQI prediction studies report R² above 0.98?
Usually because the inputs include the pollutant concentrations that the AQI is calculated from, and because daily data is split at random so test days have near-identical neighbours in training. Both make the task easier than real forecasting.
Is XGBoost better than Random Forest for air-quality prediction?
Neither wins everywhere. XGBoost often edges ahead on tabular data when tuned carefully, while Random Forest is more forgiving with default settings. Compare them under the same time-ordered, season-aware protocol before choosing.
What is seasonally stratified evaluation?
A test design in which every season is represented in the held-out data and errors are reported season by season, so that a model cannot hide poor performance in a critical season behind good performance in the others.
Why add a brick-kiln season feature for Dhaka?
Brick kilns around Dhaka operate mainly in the dry season, roughly November to March, when air quality is at its worst. A binary feature tells the model directly which regime it is in.
The study, its co-authors and the full benchmark are on the Dhaka air-quality 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.
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.
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.