{ "cells": [ { "cell_type": "markdown", "id": "md_title", "metadata": {}, "source": [ "# 🌫️ PM2.5 Spike Prediction — XGBoost Multi-Horizon Classifier\n", "\n", "This notebook trains **three XGBoost binary classifiers** (one per forecast horizon: **t+1h, t+2h, t+3h**) to predict PM2.5 pollution spikes across Bangladesh monitoring stations.\n", "\n", "**Pipeline overview:**\n", "1. Load pre-engineered train/test feature CSVs\n", "2. Use chronological validation to tune XGBoost hyperparameters with randomized search\n", "3. Select a horizon-specific alert threshold with a recall floor\n", "4. Evaluate with F1, Recall, Precision, ROC-AUC, and PR-AUC\n", "5. Visualise confusion matrices, metric comparisons, and SHAP feature importance inline" ] }, { "cell_type": "markdown", "id": "md_imports", "metadata": {}, "source": [ "## 1. Imports & Configuration" ] }, { "cell_type": "code", "execution_count": 68, "id": "cell_imports", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "✅ Imports done\n" ] } ], "source": [ "import pandas as pd\n", "import numpy as np\n", "import lightgbm as lgb\n", "import shap\n", "import matplotlib\n", "import matplotlib.pyplot as plt\n", "import matplotlib.gridspec as gridspec\n", "import seaborn as sns\n", "import os\n", "import joblib\n", "import warnings\n", "warnings.filterwarnings('ignore')\n", "\n", "from sklearn.metrics import (\n", " f1_score, recall_score, precision_score, roc_auc_score,\n", " average_precision_score, confusion_matrix,\n", " roc_curve, precision_recall_curve\n", ")\n", "from imblearn.over_sampling import SMOTE\n", "\n", "%matplotlib inline\n", "plt.rcParams.update({\n", " 'figure.dpi': 120,\n", " 'axes.spines.top': False,\n", " 'axes.spines.right': False,\n", " 'font.family': 'DejaVu Sans',\n", "})\n", "PALETTE = ['#4C72B0', '#DD8452', '#55A868'] # one colour per horizon\n", "print('✅ Imports done')" ] }, { "cell_type": "markdown", "id": "md_config", "metadata": {}, "source": [ "## 2. Path & Hyperparameter Configuration" ] }, { "cell_type": "code", "execution_count": 69, "id": "cell_config", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "✅ Configuration set\n" ] } ], "source": [ "TRAIN_PATH = 'train_features_v3.csv'\n", "TEST_PATH = 'test_features_v3.csv'\n", "HORIZONS = [1, 2, 3]\n", "USE_SMOTE = False # set True only if you explicitly want SMOTE instead of class weighting\n", "MODELS_DIR = 'models'\n", "SHAP_DIR = 'shap_plots'\n", "TRAIN_SPLIT = 0.8 # chronological train/val split inside training data\n", "THRESHOLD_GRID = np.linspace(0.10, 0.90, 161)\n", "RECALL_FLOOR = 0.75\n", "\n", "os.makedirs(MODELS_DIR, exist_ok=True)\n", "os.makedirs(SHAP_DIR, exist_ok=True)\n", "\n", "# Columns excluded from features (identifiers / raw targets / already encoded)\n", "NON_FEATURE_COLS = [\n", " 'No', 'year', 'month', 'day', 'hour', 'wd', 'datetime',\n", " 'spike_t+1', 'spike_t+2', 'spike_t+3',\n", "]\n", "\n", "\n", "def add_advanced_horizon_features(df):\n", " \"\"\"Add long-horizon, station-local, and neighbor-aware signals for better spike detection.\"\"\"\n", " df = df.sort_values(['station', 'datetime']).copy()\n", "\n", " df['pm25_delta_1'] = df['PM2.5'] - df.groupby('station')['PM2.5'].shift(1)\n", " df['pm25_delta_3'] = df['PM2.5'] - df.groupby('station')['PM2.5'].shift(3)\n", " df['pm25_change_6'] = df['PM2.5'] - df.groupby('station')['PM2.5'].shift(6)\n", " df['pm25_roc_3'] = df['pm25_delta_3'] / 3.0\n", "\n", " if 'pm25_roll_mean_6' in df.columns:\n", " df['pm25_trend_6'] = df['PM2.5'] - df['pm25_roll_mean_6']\n", "\n", " if 'idw_pm25_neighbors' in df.columns:\n", " df['pm25_vs_neighbor'] = df['PM2.5'] - df['idw_pm25_neighbors']\n", " df['neighbor_pressure'] = df['idw_pm25_neighbors'] / (df['PM2.5'] + 1e-6)\n", "\n", " if 'dayofweek' in df.columns:\n", " df['weekend_flag'] = df['dayofweek'].isin([5, 6]).astype(int)\n", "\n", " station_mean = df.groupby('station')['PM2.5'].transform(\n", " lambda s: s.rolling(24, min_periods=12).mean()\n", " )\n", " station_std = df.groupby('station')['PM2.5'].transform(\n", " lambda s: s.rolling(24, min_periods=12).std().fillna(0.0)\n", " )\n", " df['station_pm25_zscore_24'] = (df['PM2.5'] - station_mean) / station_std.replace(0, np.nan)\n", " df['station_pm25_zscore_24'] = df['station_pm25_zscore_24'].fillna(0.0)\n", "\n", " if 'regional_elevated_frac' in df.columns:\n", " df['regional_gap'] = df['PM2.5'] - df['regional_elevated_frac']\n", " else:\n", " df['regional_gap'] = 0.0\n", "\n", " return df\n", "\n", "\n", "if not os.path.exists(TRAIN_PATH) or not os.path.exists(TEST_PATH):\n", " train_v2 = pd.read_csv('train_features_v2.csv')\n", " test_v2 = pd.read_csv('test_features_v2.csv')\n", " train_v3 = add_advanced_horizon_features(train_v2)\n", " test_v3 = add_advanced_horizon_features(test_v2)\n", " train_v3.to_csv(TRAIN_PATH, index=False)\n", " test_v3.to_csv(TEST_PATH, index=False)\n", " print(f'✅ Created enhanced feature files: {TRAIN_PATH}, {TEST_PATH}')\n", "\n", "print('✅ Configuration set')" ] }, { "cell_type": "markdown", "id": "md_data", "metadata": {}, "source": [ "## 3. Data Loading\n", "\n", "We use the **v3 feature CSVs** produced from the engineered lag, rolling, spatial-neighborhood, and station-local features. \n", "An 80/20 chronological split is applied so validation always comes *after* training, preventing temporal leakage." ] }, { "cell_type": "code", "execution_count": 70, "id": "cell_load", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Train rows : 143,424\n", "Valid rows : 35,856\n", "Test rows : 28,800\n", "Date range (train): 2022-08-05 to 2025-12-31\n", "Date range (valid): 2022-08-05 to 2025-12-31\n" ] }, { "data": { "application/vnd.microsoft.datawrangler.viewer.v0+json": { "columns": [ { "name": "index", "rawType": "int64", "type": "integer" }, { "name": "No", "rawType": "int64", "type": "integer" }, { "name": "year", "rawType": "int64", "type": "integer" }, { "name": "month", "rawType": "int64", "type": "integer" }, { "name": "day", "rawType": "int64", "type": "integer" }, { "name": "hour", "rawType": "int64", "type": "integer" }, { "name": "PM2.5", "rawType": "float64", "type": "float" }, { "name": "PM10", "rawType": "float64", "type": "float" }, { "name": "SO2", "rawType": "float64", "type": "float" }, { "name": "NO2", "rawType": "float64", "type": "float" }, { "name": "CO", "rawType": "float64", "type": "float" }, { "name": "O3", "rawType": "float64", "type": "float" }, { "name": "TEMP", "rawType": "float64", "type": "float" }, { "name": "PRES", "rawType": "float64", "type": "float" }, { "name": "DEWP", "rawType": "float64", "type": "float" }, { "name": "RAIN", "rawType": "float64", "type": "float" }, { "name": "wd", "rawType": "str", "type": "string" }, { "name": "WSPM", "rawType": "float64", "type": "float" }, { "name": "station", "rawType": "str", "type": "string" }, { "name": "datetime", "rawType": "datetime64[us]", "type": "datetime" }, { "name": "hour_sin", "rawType": "float64", "type": "float" }, { "name": "hour_cos", "rawType": "float64", "type": "float" }, { "name": "month_sin", "rawType": "float64", "type": "float" }, { "name": "month_cos", "rawType": "float64", "type": "float" }, { "name": "dayofweek", "rawType": "int64", "type": "integer" }, { "name": "wind_u", "rawType": "float64", "type": "float" }, { "name": "wind_v", "rawType": "float64", "type": "float" }, { "name": "pm25_lag_1", "rawType": "float64", "type": "float" }, { "name": "pm25_lag_2", "rawType": "float64", "type": "float" }, { "name": "pm25_lag_3", "rawType": "float64", "type": "float" }, { "name": "pm25_lag_6", "rawType": "float64", "type": "float" }, { "name": "pm25_lag_24", "rawType": "float64", "type": "float" }, { "name": "pm25_roll_mean_3", "rawType": "float64", "type": "float" }, { "name": "pm25_roll_std_3", "rawType": "float64", "type": "float" }, { "name": "pm25_roll_mean_6", "rawType": "float64", "type": "float" }, { "name": "pm25_roll_std_6", "rawType": "float64", "type": "float" }, { "name": "pm25_roll_mean_24", "rawType": "float64", "type": "float" }, { "name": "pm25_roll_std_24", "rawType": "float64", "type": "float" }, { "name": "idw_pm25_neighbors", "rawType": "float64", "type": "float" }, { "name": "idw_wind_u_neighbors", "rawType": "float64", "type": "float" }, { "name": "idw_wind_v_neighbors", "rawType": "float64", "type": "float" }, { "name": "regional_elevated_frac", "rawType": "float64", "type": "float" }, { "name": "spike_t+1", "rawType": "int64", "type": "integer" }, { "name": "spike_t+2", "rawType": "int64", "type": "integer" }, { "name": "spike_t+3", "rawType": "int64", "type": "integer" }, { "name": "in_plume", "rawType": "int64", "type": "integer" }, { "name": "plume_size", "rawType": "float64", "type": "float" }, { "name": "apriori_propagation_signal", "rawType": "float64", "type": "float" }, { "name": "pm25_delta_1", "rawType": "float64", "type": "float" }, { "name": "pm25_delta_3", "rawType": "float64", "type": "float" }, { "name": "pm25_change_6", "rawType": "float64", "type": "float" }, { "name": "pm25_roc_3", "rawType": "float64", "type": "float" }, { "name": "pm25_trend_6", "rawType": "float64", "type": "float" }, { "name": "pm25_vs_neighbor", "rawType": "float64", "type": "float" }, { "name": "neighbor_pressure", "rawType": "float64", "type": "float" }, { "name": "weekend_flag", "rawType": "int64", "type": "integer" }, { "name": "station_pm25_zscore_24", "rawType": "float64", "type": "float" }, { "name": "regional_gap", "rawType": "float64", "type": "float" } ], "ref": "2db45317-4104-4db3-8a0f-d6529fd70b73", "rows": [ [ "0", "173665", "2022", "8", "5", "0", "8.5", "13.5", "1.0", "3.1", "118.0", "28.0", "27.1", "1002.3", "25.7", "0.0", "ESE", "1.99", "Barisal", "2022-08-05 00:00:00", "0.0", "1.0", "-0.8660254037844385", "-0.5000000000000004", "4", "-1.8385202696974603", "0.7615400304065285", "7.0", "6.8", "7.0", "7.9", "7.4", "6.933333333333334", "0.1154700538379552", "7.316666666666666", "0.4445971959725601", "6.275", "1.1398893920407176", "12.469896372079289", "-1.7273408898615403", "-0.1252390339281927", "0.0", "0", "0", "0", "0", "0.0", "0.0", null, null, null, null, "1.1833333333333336", "-3.9698963720792886", "1.4670464594156272", "0", "0.0", "8.5" ], [ "1", "173666", "2022", "8", "5", "1", "7.1", "11.5", "1.1", "2.9", "119.0", "33.0", "28.4", "1002.5", "25.6", "0.0", "ESE", "3.0", "Barisal", "2022-08-05 01:00:00", "0.2588190451025207", "0.9659258262890684", "-0.8660254037844385", "-0.5000000000000004", "4", "-2.77163859753386", "1.1480502970952693", "8.5", "7.0", "6.8", "7.7", "5.0", "7.433333333333334", "0.9291573243177584", "7.416666666666667", "0.6306081720582625", "6.320833333333333", "1.207217125626454", "10.508043008301906", "-1.6443069247173017", "0.1182062125535724", "0.0", "0", "0", "0", "0", "0.0", "0.0", "-1.4000000000000004", null, null, null, "-0.3166666666666673", "-3.408043008301906", "1.4800058490557826", "0", "0.0", "7.1" ], [ "2", "173667", "2022", "8", "5", "2", "6.4", "10.3", "1.1", "2.7", "120.0", "41.0", "27.7", "1003.4", "25.1", "7.9", "SE", "3.68", "Barisal", "2022-08-05 02:00:00", "0.4999999999999999", "0.8660254037844387", "-0.8660254037844385", "-0.5000000000000004", "4", "-2.602152954766495", "2.6021529547664946", "7.1", "8.5", "7.0", "7.5", "4.7", "7.533333333333334", "0.8386497083606094", "7.316666666666666", "0.6242328625334164", "6.408333333333332", "1.1831853346927033", "8.198477825028814", "-1.9217388728871605", "0.9540340637403426", "0.0", "0", "0", "0", "0", "0.0", "0.0", "-0.6999999999999993", null, null, null, "-0.9166666666666661", "-1.7984778250288134", "1.2810119600026333", "0", "0.0", "6.4" ] ], "shape": { "columns": 57, "rows": 3 } }, "text/html": [ "
| \n", " | No | \n", "year | \n", "month | \n", "day | \n", "hour | \n", "PM2.5 | \n", "PM10 | \n", "SO2 | \n", "NO2 | \n", "CO | \n", "... | \n", "pm25_delta_1 | \n", "pm25_delta_3 | \n", "pm25_change_6 | \n", "pm25_roc_3 | \n", "pm25_trend_6 | \n", "pm25_vs_neighbor | \n", "neighbor_pressure | \n", "weekend_flag | \n", "station_pm25_zscore_24 | \n", "regional_gap | \n", "
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | \n", "173665 | \n", "2022 | \n", "8 | \n", "5 | \n", "0 | \n", "8.5 | \n", "13.5 | \n", "1.0 | \n", "3.1 | \n", "118.0 | \n", "... | \n", "NaN | \n", "NaN | \n", "NaN | \n", "NaN | \n", "1.183333 | \n", "-3.969896 | \n", "1.467046 | \n", "0 | \n", "0.0 | \n", "8.5 | \n", "
| 1 | \n", "173666 | \n", "2022 | \n", "8 | \n", "5 | \n", "1 | \n", "7.1 | \n", "11.5 | \n", "1.1 | \n", "2.9 | \n", "119.0 | \n", "... | \n", "-1.4 | \n", "NaN | \n", "NaN | \n", "NaN | \n", "-0.316667 | \n", "-3.408043 | \n", "1.480006 | \n", "0 | \n", "0.0 | \n", "7.1 | \n", "
| 2 | \n", "173667 | \n", "2022 | \n", "8 | \n", "5 | \n", "2 | \n", "6.4 | \n", "10.3 | \n", "1.1 | \n", "2.7 | \n", "120.0 | \n", "... | \n", "-0.7 | \n", "NaN | \n", "NaN | \n", "NaN | \n", "-0.916667 | \n", "-1.798478 | \n", "1.281012 | \n", "0 | \n", "0.0 | \n", "6.4 | \n", "
3 rows × 57 columns
\n", "| horizon | \n", "model | \n", "best_threshold | \n", "valid_f1 | \n", "valid_recall | \n", "valid_precision | \n", "f1 | \n", "recall | \n", "precision | \n", "roc_auc | \n", "pr_auc | \n", "tp | \n", "fp | \n", "fn | \n", "tn | \n", "best_cv_ap | \n", "
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| t+1h | \n", "XGBoost | \n", "0.405000 | \n", "0.867052 | \n", "0.903614 | \n", "0.833333 | \n", "0.8671 | \n", "0.9036 | \n", "0.8333 | \n", "0.9997 | \n", "0.9301 | \n", "75 | \n", "15 | \n", "8 | \n", "35758 | \n", "0.955731 | \n", "
| t+2h | \n", "XGBoost | \n", "0.385000 | \n", "0.741176 | \n", "0.759036 | \n", "0.724138 | \n", "0.7412 | \n", "0.7590 | \n", "0.7241 | \n", "0.9992 | \n", "0.8057 | \n", "63 | \n", "24 | \n", "20 | \n", "35749 | \n", "0.909269 | \n", "
| t+3h | \n", "XGBoost | \n", "0.105000 | \n", "0.553719 | \n", "0.807229 | \n", "0.421384 | \n", "0.5537 | \n", "0.8072 | \n", "0.4214 | \n", "0.9981 | \n", "0.6240 | \n", "67 | \n", "92 | \n", "16 | \n", "35681 | \n", "0.863778 | \n", "