Lesson 38 (Capstone 2): Urban Airshed PM2.5 Forecasting & Leak-Free Temporal Machine Learning

Courses Integrated: Atmospheric Dispersion Modeling · ME 300 Gas Turbine Emissions · COURSE_HUB Capstone 1 (UCI Beijing PM2.5 + Italy Air Quality)
Companion Datasets: UCI_Beijing_PM25_Meteorology.csv, UCI_Air_Quality_Italy_Hourly.csv, UCI_Gas_Turbine_2015_Emissions.csv

Why Chronological Splits Matter (No Temporal ML Leakage!)

A random 80/20 split on hourly air quality leaks 14:00 and 16:00 into training so your model effortlessly guesses 15:00 (fake R^2 = 0.99)—then fails completely in live forecasting!

In real environmental forecasting, you ALWAYS split strictly by time (e.g., train on 2010–2013, test on completely unseen 2014) AND build engineered physical features:

from pathlib import Path
def data_file(name):
    """Locate a dataset file whether running from SRC_DIR, module folder, HOMEWORK, or EXAMS."""
    for p in [
        Path("datasets") / name,
        Path("../datasets") / name,
        Path("../../datasets") / name,
    ]:
        if p.exists():
            return p
    raise FileNotFoundError(f"Missing dataset {name} in datasets/")
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# --- Load All 43,824 Real Hours from UCI_Beijing_PM25_Meteorology.csv ---
bj = pd.read_csv(data_file("UCI_Beijing_PM25_Meteorology.csv"))
bj["Datetime"] = pd.to_datetime(bj[["year", "month", "day", "hour"]])
bj = bj.set_index("Datetime").sort_index()

# Physical Feature Engineering (Zero future leakage!)
bj["pm_lag1"] = bj["pm2.5"].shift(1)
bj["pm_lag3"] = bj["pm2.5"].shift(3)
bj["dP_3h"] = bj["PRES"] - bj["PRES"].shift(3)
bj["dew_dep"] = bj["TEMP"] - bj["DEWP"]
bj["is_NW"] = (bj["cbwd"] == "NW").astype(float)
bj["is_SE"] = (bj["cbwd"] == "SE").astype(float)
bj["sin_hr"] = np.sin(2.0 * np.pi * bj["hour"] / 24.0)
bj["cos_hr"] = np.cos(2.0 * np.pi * bj["hour"] / 24.0)

feat_cols = ["pm_lag1", "pm_lag3", "TEMP", "dew_dep", "PRES", "dP_3h", "Iws", "is_NW", "is_SE", "sin_hr", "cos_hr"]
df_ml = bj[feat_cols + ["pm2.5"]].dropna()

# Strict Chronological Train (2010-2013) vs Unseen Holdout Year (2014)
train = df_ml.loc[: "2013-12-31"]
test = df_ml.loc["2014-01-01":]

X_tr, y_tr = train[feat_cols].values, train["pm2.5"].values
X_te, y_te = test[feat_cols].values, test["pm2.5"].values

# Standardize STRICTLY using Training mean & std (Zero Data Leakage!)
mu_x, sig_x = X_tr.mean(axis=0), X_tr.std(axis=0)
X_tr_s = np.column_stack([np.ones(len(X_tr)), (X_tr - mu_x) / sig_x])
X_te_s = np.column_stack([np.ones(len(X_te)), (X_te - mu_x) / sig_x])

# Closed-Form Ridge Regression: (X^T X + lambda I) w = X^T y (with bias unpenalized!)
lam = 15.0
reg_I = np.eye(X_tr_s.shape[1]); reg_I[0, 0] = 0.0
w_ridge = np.linalg.solve(X_tr_s.T @ X_tr_s + lam * reg_I, X_tr_s.T @ y_tr)

y_pred = np.clip(X_te_s @ w_ridge, 0.0, None)
rmse = np.sqrt(np.mean((y_te - y_pred) ** 2))
mae = np.mean(np.abs(y_te - y_pred))
r2_te = 1.0 - np.sum((y_te - y_pred)**2) / np.sum((y_te - y_te.mean())**2)

# Compare against Persistence Baseline (guessing pm(t) = pm(t-1))
rmse_persist = np.sqrt(np.mean((y_te - test["pm_lag1"].values) ** 2))

print("=== Strictly Out-of-Sample 2014 Hourly PM2.5 Forecast Results (UCI Beijing) ===")
print(f"Train Rows (2010-2013) : {len(X_tr):,} | Unseen Test Rows (2014) : {len(X_te):,}")
print(f"Persistence Baseline   : RMSE = {rmse_persist:.2f} ug/m^3")
print(f"Ridge Meteorology Model: RMSE = {rmse:.2f} ug/m^3 | MAE = {mae:.2f} | R^2 = {r2_te:.4f}")

# Visualize 10-day Unseen February 2014 Haze Forecast Event
win14 = test.loc["2014-02-15":"2014-02-26"]
p_win = y_pred[(test.index >= "2014-02-15") & (test.index <= "2014-02-26 23:59")]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.5, 3.8))
ax1.plot(win14.index, win14["pm2.5"], color="#0f172a", lw=1.6, label="Observed 2014 PM2.5")
ax1.plot(win14.index, p_win, color="#dc2626", ls="--", lw=1.5, label="ML 1-hr Forecast")
ax1.set_title("Unseen Feb 2014 Beijing Haze Episode Forecast"); ax1.set_ylabel("PM2.5 [ug/m^3]"); ax1.legend(); ax1.grid(True, alpha=0.3); ax1.tick_params(axis="x", rotation=25)

# Standardized feature weights (exclude bias)
coefs = pd.Series(w_ridge[1:], index=feat_cols).sort_values()
coefs.plot(kind="barh", ax=ax2, color=["#059669" if v < 0 else "#d97706" for v in coefs])
ax2.set_title("Standardized Meteorology & Lag Feature Impacts"); ax2.set_xlabel("Standardized Weight"); ax2.grid(True, axis="x", alpha=0.3)
fig.tight_layout()
Urban Airshed PM2.5 Forecasting & Leak-Free Temporal Machine Learning Output Plot 1
=== Strictly Out-of-Sample 2014 Hourly PM2.5 Forecast Results (UCI Beijing) ===
Train Rows (2010-2013) : 32,684 | Unseen Test Rows (2014) : 8,581
Persistence Baseline   : RMSE = 22.07 ug/m^3
Ridge Meteorology Model: RMSE = 21.28 ug/m^3 | MAE = 11.87 | R^2 = 0.9482

Look at Panel 2: North-West wind (is_NW), strong accumulated wind (Iws), and widening dewpoint spread (dew_dep, dry clean air) hold negative standardized weights—they physically flush \(\text{PM}_{2.5}\) out of the Beijing basin!


Concept Check Questions

  1. Explain why fitting mu_x, sig_x on X_tr ONLY (and NEVER across combined 2010–2014) enforces zero data leakage.
  2. Why did we set reg_I[0, 0] = 0.0 so Ridge regularization (lam = 15.0) never shrinks the intercept bias term?
  3. Explain what sin_hr and cos_hr solve compared to feeding raw hour = 0..23 (why is 23:00 right next to 00:00 in real time, yet 23 numbers apart numerically)?

Guided Practice Problem 1: Multi-Step (t + 6h) Air Quality Forecast Horizon Degradation

Modify the target/lag setup so features predict pm2.5 6 hours ahead (shift(6) and shift(8)) on the exact same 2014 holdout test year. Quantify how 6-hour RMSE and \(R^2\) change compared to 1-hour ahead forecasting!

# Guided Practice 1 Starter
bj6 = bj[["pm2.5", "TEMP", "dew_dep", "PRES", "Iws", "is_NW", "sin_hr", "cos_hr"]].copy()
bj6["pm_lag6"] = bj6["pm2.5"].shift(6)
bj6["pm_lag12"] = bj6["pm2.5"].shift(12)
bj6 = bj6.dropna()
f6 = ["pm_lag6", "pm_lag12", "TEMP", "dew_dep", "PRES", "Iws", "is_NW", "sin_hr", "cos_hr"]
tr6, te6 = bj6.loc[:"2013-12-31"], bj6.loc["2014-01-01":]
mx, sx = tr6[f6].values.mean(0), tr6[f6].values.std(0)
Xtr6 = np.column_stack([np.ones(len(tr6)), (tr6[f6].values - mx) / sx])
Xte6 = np.column_stack([np.ones(len(te6)), (te6[f6].values - mx) / sx])
w6 = np.linalg.solve(Xtr6.T @ Xtr6 + 20 * np.eye(Xtr6.shape[1]), Xtr6.T @ tr6["pm2.5"].values)
pred6 = np.clip(Xte6 @ w6, 0.0, None)
r2_6 = 1.0 - np.sum((te6["pm2.5"].values - pred6)**2) / np.sum((te6["pm2.5"].values - te6["pm2.5"].mean())**2)
print(f"6-Hour Ahead Unseen 2014 PM2.5 Forecast: RMSE={np.sqrt(np.mean((te6['pm2.5']-pred6)**2)):.1f} ug/m^3 | R^2={r2_6:.3f}")
6-Hour Ahead Unseen 2014 PM2.5 Forecast: RMSE=52.9 ug/m^3 | R^2=0.678