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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Re-implement the DECODE paper training pipeline for local I-BLEND data.
|
| 3 |
+
|
| 4 |
+
The paper pipeline is:
|
| 5 |
+
1. Fuse energy, occupancy, calendar, and weather-like environmental features.
|
| 6 |
+
2. Align everything to a 10-minute sampling rate.
|
| 7 |
+
3. Normalize features with Min-Max scaling.
|
| 8 |
+
4. Split chronologically into train/validation/test with a 70:15:15 ratio.
|
| 9 |
+
5. Compare LSTM with Linear Regression, Decision Tree, and Random Forest.
|
| 10 |
+
|
| 11 |
+
This local implementation supports two targets:
|
| 12 |
+
- paper_buildings: 7 building-level series matching the paper.
|
| 13 |
+
- meters: 9 meter-level series from all_buildings_power.csv.
|
| 14 |
+
|
| 15 |
+
Weather is optional because the local weather file in this workspace starts in
|
| 16 |
+
2018, while the energy data ends in 2017. The script detects this and continues.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import argparse
|
| 22 |
+
import os
|
| 23 |
+
import json
|
| 24 |
+
import math
|
| 25 |
+
import sys
|
| 26 |
+
import warnings
|
| 27 |
+
from dataclasses import dataclass
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 32 |
+
DEFAULT_DATA_MINING_ROOT = ROOT if (ROOT / "IIITD_occupancy_dataset").exists() else ROOT.parent
|
| 33 |
+
DATA_MINING_ROOT = Path(os.environ.get("IBLEND_DATA_ROOT", DEFAULT_DATA_MINING_ROOT))
|
| 34 |
+
ENERGY_FILE = Path(os.environ.get("IBLEND_ENERGY_FILE", DATA_MINING_ROOT / "energy_dataset" / "all_buildings_power.csv"))
|
| 35 |
+
OCCUPANCY_DIR = DATA_MINING_ROOT / "IIITD_occupancy_dataset" / "IIITD_occupancy_dataset"
|
| 36 |
+
CALENDAR_DIR = DATA_MINING_ROOT / "iiitd_calender_schedule" / "iiitd_calender_schedule"
|
| 37 |
+
WEATHER_FILE = DATA_MINING_ROOT / "weather_comparison" / "weather_comparison" / "IIITD_and_airport_data.csv"
|
| 38 |
+
OUT_DIR = ROOT / "decode_reimplementation_outputs"
|
| 39 |
+
TZ = "Asia/Kolkata"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
PAPER_BUILDINGS = {
|
| 43 |
+
"Academic": {"meters": ["Academic"], "occupancy": "ACB"},
|
| 44 |
+
"Boys_hostel": {"meters": ["Boys_main", "Boys_backup"], "occupancy": "BH"},
|
| 45 |
+
"Girls_hostel": {"meters": ["Girls_main", "Girls_backup"], "occupancy": "GH"},
|
| 46 |
+
"Library": {"meters": ["Library"], "occupancy": "LB"},
|
| 47 |
+
"Lecture": {"meters": ["Lecture"], "occupancy": "LCB"},
|
| 48 |
+
"Dining": {"meters": ["Mess"], "occupancy": "DB"},
|
| 49 |
+
"Facilities": {"meters": ["Facilities"], "occupancy": "SRB"},
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
METER_TARGETS = {
|
| 53 |
+
"Academic": {"meters": ["Academic"], "occupancy": "ACB"},
|
| 54 |
+
"Boys_main": {"meters": ["Boys_main"], "occupancy": "BH"},
|
| 55 |
+
"Boys_backup": {"meters": ["Boys_backup"], "occupancy": "BH"},
|
| 56 |
+
"Facilities": {"meters": ["Facilities"], "occupancy": "SRB"},
|
| 57 |
+
"Girls_main": {"meters": ["Girls_main"], "occupancy": "GH"},
|
| 58 |
+
"Girls_backup": {"meters": ["Girls_backup"], "occupancy": "GH"},
|
| 59 |
+
"Lecture": {"meters": ["Lecture"], "occupancy": "LCB"},
|
| 60 |
+
"Library": {"meters": ["Library"], "occupancy": "LB"},
|
| 61 |
+
"Mess": {"meters": ["Mess"], "occupancy": "DB"},
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@dataclass
|
| 66 |
+
class SplitData:
|
| 67 |
+
x_train: object
|
| 68 |
+
x_val: object
|
| 69 |
+
x_test: object
|
| 70 |
+
y_train: object
|
| 71 |
+
y_val: object
|
| 72 |
+
y_test: object
|
| 73 |
+
feature_names: list[str]
|
| 74 |
+
test_span_steps: int | None = None
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def import_stack():
|
| 78 |
+
try:
|
| 79 |
+
import numpy as np
|
| 80 |
+
import pandas as pd
|
| 81 |
+
from sklearn.ensemble import RandomForestRegressor
|
| 82 |
+
from sklearn.linear_model import Ridge
|
| 83 |
+
from sklearn.metrics import mean_absolute_error, r2_score
|
| 84 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 85 |
+
from sklearn.tree import DecisionTreeRegressor
|
| 86 |
+
except ImportError as exc:
|
| 87 |
+
missing = str(exc).split("No module named ")[-1].strip("'")
|
| 88 |
+
raise SystemExit(
|
| 89 |
+
f"Missing dependency: {missing}\n"
|
| 90 |
+
"Install the base training stack with:\n"
|
| 91 |
+
f" {sys.executable} -m pip install pandas numpy scikit-learn\n"
|
| 92 |
+
"Install LSTM support with either PyTorch or TensorFlow:\n"
|
| 93 |
+
f" {sys.executable} -m pip install torch\n"
|
| 94 |
+
f" {sys.executable} -m pip install tensorflow\n"
|
| 95 |
+
) from exc
|
| 96 |
+
|
| 97 |
+
torch_import_error = None
|
| 98 |
+
try:
|
| 99 |
+
import torch
|
| 100 |
+
from torch import nn
|
| 101 |
+
from torch.utils.data import DataLoader, TensorDataset
|
| 102 |
+
except Exception as exc:
|
| 103 |
+
torch = None
|
| 104 |
+
nn = None
|
| 105 |
+
DataLoader = None
|
| 106 |
+
TensorDataset = None
|
| 107 |
+
torch_import_error = f"{type(exc).__name__}: {exc}"
|
| 108 |
+
|
| 109 |
+
lgbm_import_error = None
|
| 110 |
+
try:
|
| 111 |
+
import lightgbm as lgb
|
| 112 |
+
except Exception as exc:
|
| 113 |
+
lgb = None
|
| 114 |
+
lgbm_import_error = f"{type(exc).__name__}: {exc}"
|
| 115 |
+
|
| 116 |
+
statsmodels_import_error = None
|
| 117 |
+
try:
|
| 118 |
+
from statsmodels.tsa.arima.model import ARIMA
|
| 119 |
+
except Exception as exc:
|
| 120 |
+
ARIMA = None
|
| 121 |
+
statsmodels_import_error = f"{type(exc).__name__}: {exc}"
|
| 122 |
+
|
| 123 |
+
tf_import_error = None
|
| 124 |
+
try:
|
| 125 |
+
import tensorflow as tf
|
| 126 |
+
from tensorflow import keras
|
| 127 |
+
except Exception as exc:
|
| 128 |
+
tf = None
|
| 129 |
+
keras = None
|
| 130 |
+
tf_import_error = f"{type(exc).__name__}: {exc}"
|
| 131 |
+
|
| 132 |
+
return {
|
| 133 |
+
"np": np,
|
| 134 |
+
"pd": pd,
|
| 135 |
+
"RandomForestRegressor": RandomForestRegressor,
|
| 136 |
+
"Ridge": Ridge,
|
| 137 |
+
"DecisionTreeRegressor": DecisionTreeRegressor,
|
| 138 |
+
"MinMaxScaler": MinMaxScaler,
|
| 139 |
+
"mean_absolute_error": mean_absolute_error,
|
| 140 |
+
"r2_score": r2_score,
|
| 141 |
+
"torch": torch,
|
| 142 |
+
"nn": nn,
|
| 143 |
+
"DataLoader": DataLoader,
|
| 144 |
+
"TensorDataset": TensorDataset,
|
| 145 |
+
"torch_import_error": torch_import_error,
|
| 146 |
+
"lgb": lgb,
|
| 147 |
+
"lgbm_import_error": lgbm_import_error,
|
| 148 |
+
"ARIMA": ARIMA,
|
| 149 |
+
"statsmodels_import_error": statsmodels_import_error,
|
| 150 |
+
"tf": tf,
|
| 151 |
+
"keras": keras,
|
| 152 |
+
"tf_import_error": tf_import_error,
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def parse_args() -> argparse.Namespace:
|
| 157 |
+
parser = argparse.ArgumentParser(description="DECODE paper re-implementation for I-BLEND data.")
|
| 158 |
+
parser.add_argument(
|
| 159 |
+
"--mode",
|
| 160 |
+
choices=["paper_buildings", "meters"],
|
| 161 |
+
default="paper_buildings",
|
| 162 |
+
help="paper_buildings trains 7 building-level targets; meters trains 9 meter-level targets.",
|
| 163 |
+
)
|
| 164 |
+
parser.add_argument(
|
| 165 |
+
"--target",
|
| 166 |
+
default="all",
|
| 167 |
+
help="Target name to train, or 'all'. Names depend on --mode.",
|
| 168 |
+
)
|
| 169 |
+
parser.add_argument("--freq", default="10min", help="Common sampling frequency. Paper uses 10min.")
|
| 170 |
+
parser.add_argument("--lookback", type=int, default=18, help="LSTM lookback steps. 18 at 10min = 3 hours.")
|
| 171 |
+
parser.add_argument("--horizon", type=int, default=1, help="Prediction horizon in rows. 1 at 10min = next 10min.")
|
| 172 |
+
parser.add_argument("--horizon-days", type=float, default=0, help="Prediction horizon in days. Overrides --horizon when > 0.")
|
| 173 |
+
parser.add_argument("--test-span-days", type=float, default=0, help="Evaluate only this many days from the chronological test split.")
|
| 174 |
+
parser.add_argument("--epochs", type=int, default=20, help="LSTM epochs. Paper uses 20.")
|
| 175 |
+
parser.add_argument("--batch-size", type=int, default=64, help="LSTM batch size. Paper uses 64.")
|
| 176 |
+
parser.add_argument("--rf-trees", type=int, default=500, help="Random Forest trees. Paper tuned to 500.")
|
| 177 |
+
parser.add_argument("--dl-models", default="lstm,cnn,tcn", help="Comma-separated deep models: lstm,cnn,tcn,none.")
|
| 178 |
+
parser.add_argument("--include-arima", action="store_true", help="Fit ARIMA(2,1,2). This can be slow on full series.")
|
| 179 |
+
parser.add_argument("--arima-max-train", type=int, default=20000, help="Maximum recent train points for ARIMA fitting.")
|
| 180 |
+
parser.add_argument("--max-rows", type=int, default=0, help="Optional cap after preprocessing for quick smoke tests.")
|
| 181 |
+
parser.add_argument("--include-weather", action="store_true", help="Try to merge local weather data if time ranges overlap.")
|
| 182 |
+
parser.add_argument("--skip-lstm", action="store_true", help="Only train baseline ML models.")
|
| 183 |
+
parser.add_argument("--output-dir", default=str(OUT_DIR), help="Output directory.")
|
| 184 |
+
return parser.parse_args()
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def read_energy_10min(pd, freq: str):
|
| 188 |
+
if not ENERGY_FILE.exists():
|
| 189 |
+
raise FileNotFoundError(f"Missing energy file: {ENERGY_FILE}")
|
| 190 |
+
df = pd.read_csv(ENERGY_FILE, na_values=["NA", ""])
|
| 191 |
+
df["datetime"] = pd.to_datetime(df["timestamp"], unit="s", utc=True).dt.tz_convert(TZ)
|
| 192 |
+
df = df.drop(columns=["timestamp"]).set_index("datetime").sort_index()
|
| 193 |
+
|
| 194 |
+
# Paper predicts energy in Wh. Original columns are power in W at 1-minute resolution.
|
| 195 |
+
# For a 10-minute interval: Wh = mean(W) * 10 / 60.
|
| 196 |
+
mean_power_w = df.resample(freq).mean()
|
| 197 |
+
interval_minutes = pd.Timedelta(freq).total_seconds() / 60
|
| 198 |
+
energy_wh = mean_power_w * interval_minutes / 60
|
| 199 |
+
return energy_wh
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def read_occupancy_10min(pd, code: str, freq: str):
|
| 203 |
+
path = OCCUPANCY_DIR / f"{code}.csv"
|
| 204 |
+
if not path.exists():
|
| 205 |
+
warnings.warn(f"Missing occupancy file for {code}: {path}")
|
| 206 |
+
return None
|
| 207 |
+
df = pd.read_csv(path, na_values=["NA", ""])
|
| 208 |
+
df["datetime"] = pd.to_datetime(df["timestamp"], unit="s", utc=True).dt.tz_convert(TZ)
|
| 209 |
+
df = df.drop(columns=["timestamp"]).set_index("datetime").sort_index()
|
| 210 |
+
occ = df.resample(freq).mean()
|
| 211 |
+
occ["occupancy_count"] = occ["occupancy_count"].interpolate(method="time").ffill().bfill()
|
| 212 |
+
return occ
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def read_calendar(pd):
|
| 216 |
+
frames = []
|
| 217 |
+
for path in sorted(CALENDAR_DIR.glob("calender_year_*.csv")):
|
| 218 |
+
frames.append(pd.read_csv(path))
|
| 219 |
+
if not frames:
|
| 220 |
+
warnings.warn(f"No calendar files found in {CALENDAR_DIR}")
|
| 221 |
+
return None
|
| 222 |
+
cal = pd.concat(frames, ignore_index=True)
|
| 223 |
+
cal["date"] = pd.to_datetime(cal["Date"]).dt.date
|
| 224 |
+
cal = cal[["date", "working_day", "activity"]].drop_duplicates("date")
|
| 225 |
+
cal["working_day"] = pd.to_numeric(cal["working_day"], errors="coerce").fillna(0).astype(int)
|
| 226 |
+
cal["activity"] = cal["activity"].fillna("unknown").astype(str)
|
| 227 |
+
cal["activity_code"] = cal["activity"].astype("category").cat.codes
|
| 228 |
+
return cal
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def read_weather_10min(pd, freq: str):
|
| 232 |
+
if not WEATHER_FILE.exists():
|
| 233 |
+
warnings.warn(f"Missing weather file: {WEATHER_FILE}")
|
| 234 |
+
return None
|
| 235 |
+
df = pd.read_csv(WEATHER_FILE, na_values=["NA", ""])
|
| 236 |
+
first_col = df.columns[0]
|
| 237 |
+
df = df.rename(columns={first_col: "datetime"})
|
| 238 |
+
df["datetime"] = pd.to_datetime(df["datetime"], errors="coerce")
|
| 239 |
+
df = df.dropna(subset=["datetime"]).set_index("datetime").sort_index()
|
| 240 |
+
if df.index.tz is None:
|
| 241 |
+
df.index = df.index.tz_localize(TZ)
|
| 242 |
+
weather = df.resample(freq).mean().interpolate(method="time").ffill().bfill()
|
| 243 |
+
return weather
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def horizon_steps_from_args(pd, args) -> int:
|
| 247 |
+
if args.horizon_days and args.horizon_days > 0:
|
| 248 |
+
freq_delta = pd.Timedelta(args.freq)
|
| 249 |
+
steps = int(round(pd.Timedelta(days=args.horizon_days) / freq_delta))
|
| 250 |
+
return max(1, steps)
|
| 251 |
+
return max(1, args.horizon)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def test_span_steps_from_args(pd, args) -> int | None:
|
| 255 |
+
if args.test_span_days and args.test_span_days > 0:
|
| 256 |
+
freq_delta = pd.Timedelta(args.freq)
|
| 257 |
+
steps = int(round(pd.Timedelta(days=args.test_span_days) / freq_delta))
|
| 258 |
+
return max(1, steps)
|
| 259 |
+
return None
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def describe_steps(pd, steps: int, freq: str) -> str:
|
| 263 |
+
delta = pd.Timedelta(freq) * steps
|
| 264 |
+
total_minutes = delta.total_seconds() / 60
|
| 265 |
+
if total_minutes % 1440 == 0:
|
| 266 |
+
return f"{int(total_minutes // 1440)} day(s)"
|
| 267 |
+
if total_minutes % 60 == 0:
|
| 268 |
+
return f"{int(total_minutes // 60)} hour(s)"
|
| 269 |
+
return f"{total_minutes:g} minute(s)"
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def add_time_features(pd, df):
|
| 273 |
+
out = df.copy()
|
| 274 |
+
idx = out.index
|
| 275 |
+
out["hour"] = idx.hour
|
| 276 |
+
out["day_of_week"] = idx.dayofweek
|
| 277 |
+
out["month"] = idx.month
|
| 278 |
+
out["time_slot"] = idx.hour * 60 + idx.minute
|
| 279 |
+
out["hour_sin"] = (2 * math.pi * out["hour"] / 24).map(math.sin)
|
| 280 |
+
out["hour_cos"] = (2 * math.pi * out["hour"] / 24).map(math.cos)
|
| 281 |
+
out["dow_sin"] = (2 * math.pi * out["day_of_week"] / 7).map(math.sin)
|
| 282 |
+
out["dow_cos"] = (2 * math.pi * out["day_of_week"] / 7).map(math.cos)
|
| 283 |
+
out["month_sin"] = (2 * math.pi * out["month"] / 12).map(math.sin)
|
| 284 |
+
out["month_cos"] = (2 * math.pi * out["month"] / 12).map(math.cos)
|
| 285 |
+
return out
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def add_historical_features(df):
|
| 289 |
+
out = df.copy()
|
| 290 |
+
out["energy_lag_1"] = out["energy_wh"].shift(1)
|
| 291 |
+
out["energy_lag_6"] = out["energy_wh"].shift(6)
|
| 292 |
+
out["energy_lag_144"] = out["energy_wh"].shift(144)
|
| 293 |
+
out["energy_lag_1008"] = out["energy_wh"].shift(1008)
|
| 294 |
+
out["rolling_mean_6"] = out["energy_wh"].shift(1).rolling(6).mean()
|
| 295 |
+
out["rolling_mean_144"] = out["energy_wh"].shift(1).rolling(144).mean()
|
| 296 |
+
out["rolling_std_144"] = out["energy_wh"].shift(1).rolling(144).std()
|
| 297 |
+
|
| 298 |
+
# DECODE-style baseline features: previous three days with same working-day class
|
| 299 |
+
# and same time instant.
|
| 300 |
+
same_type_groups = out.groupby(["working_day", "time_slot"], sort=False)["energy_wh"]
|
| 301 |
+
out["same_day_type_lag_1"] = same_type_groups.shift(1)
|
| 302 |
+
out["same_day_type_lag_2"] = same_type_groups.shift(2)
|
| 303 |
+
out["same_day_type_lag_3"] = same_type_groups.shift(3)
|
| 304 |
+
return out
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def build_target_frame(pd, energy_10min, calendar, target_name: str, target_spec: dict, freq: str, include_weather: bool):
|
| 308 |
+
missing_meters = [m for m in target_spec["meters"] if m not in energy_10min.columns]
|
| 309 |
+
if missing_meters:
|
| 310 |
+
raise KeyError(f"{target_name} references missing meter columns: {missing_meters}")
|
| 311 |
+
|
| 312 |
+
df = pd.DataFrame(index=energy_10min.index)
|
| 313 |
+
df["energy_wh"] = energy_10min[target_spec["meters"]].sum(axis=1, min_count=1)
|
| 314 |
+
|
| 315 |
+
occ = read_occupancy_10min(pd, target_spec["occupancy"], freq)
|
| 316 |
+
if occ is not None:
|
| 317 |
+
df = df.join(occ[["occupancy_count"]], how="left")
|
| 318 |
+
else:
|
| 319 |
+
df["occupancy_count"] = math.nan
|
| 320 |
+
|
| 321 |
+
df["date"] = df.index.date
|
| 322 |
+
if calendar is not None:
|
| 323 |
+
df = df.reset_index().merge(calendar, on="date", how="left").set_index("datetime").sort_index()
|
| 324 |
+
else:
|
| 325 |
+
df["working_day"] = (df.index.dayofweek < 5).astype(int)
|
| 326 |
+
df["activity"] = "unknown"
|
| 327 |
+
df["activity_code"] = 0
|
| 328 |
+
|
| 329 |
+
if include_weather:
|
| 330 |
+
weather = read_weather_10min(pd, freq)
|
| 331 |
+
if weather is not None:
|
| 332 |
+
before = len(df)
|
| 333 |
+
df = df.join(weather, how="inner")
|
| 334 |
+
if df.empty:
|
| 335 |
+
warnings.warn(
|
| 336 |
+
"Weather data has no overlap with this target after joining. "
|
| 337 |
+
"Continuing without weather features."
|
| 338 |
+
)
|
| 339 |
+
df = pd.DataFrame(index=energy_10min.index)
|
| 340 |
+
df["energy_wh"] = energy_10min[target_spec["meters"]].sum(axis=1, min_count=1)
|
| 341 |
+
occ = read_occupancy_10min(pd, target_spec["occupancy"], freq)
|
| 342 |
+
if occ is not None:
|
| 343 |
+
df = df.join(occ[["occupancy_count"]], how="left")
|
| 344 |
+
df["date"] = df.index.date
|
| 345 |
+
df = df.reset_index().merge(calendar, on="date", how="left").set_index("datetime").sort_index()
|
| 346 |
+
elif len(df) < before:
|
| 347 |
+
warnings.warn(f"Weather join reduced rows from {before} to {len(df)}.")
|
| 348 |
+
|
| 349 |
+
df["occupancy_count"] = df["occupancy_count"].interpolate(method="time").ffill().bfill()
|
| 350 |
+
fallback_working_day = pd.Series((df.index.dayofweek < 5).astype(int), index=df.index)
|
| 351 |
+
df["working_day"] = df["working_day"].fillna(fallback_working_day).astype(int)
|
| 352 |
+
df["activity"] = df["activity"].fillna("unknown").astype(str)
|
| 353 |
+
df["activity_code"] = df["activity_code"].fillna(0).astype(int)
|
| 354 |
+
df = add_time_features(pd, df)
|
| 355 |
+
df = add_historical_features(df)
|
| 356 |
+
return df
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def make_ml_split(
|
| 360 |
+
np,
|
| 361 |
+
pd,
|
| 362 |
+
MinMaxScaler,
|
| 363 |
+
df,
|
| 364 |
+
horizon: int,
|
| 365 |
+
max_rows: int,
|
| 366 |
+
test_span_steps: int | None = None,
|
| 367 |
+
) -> tuple[SplitData, object, object]:
|
| 368 |
+
data = df.copy()
|
| 369 |
+
data["target"] = data["energy_wh"].shift(-horizon)
|
| 370 |
+
|
| 371 |
+
non_features = {"target", "date", "activity"}
|
| 372 |
+
feature_names = [
|
| 373 |
+
c for c in data.columns
|
| 374 |
+
if c not in non_features and pd.api.types.is_numeric_dtype(data[c])
|
| 375 |
+
]
|
| 376 |
+
clean = data[feature_names + ["target"]].replace([np.inf, -np.inf], np.nan).dropna()
|
| 377 |
+
if max_rows and len(clean) > max_rows:
|
| 378 |
+
clean = clean.tail(max_rows)
|
| 379 |
+
|
| 380 |
+
n = len(clean)
|
| 381 |
+
if n < 100:
|
| 382 |
+
raise ValueError(f"Not enough clean rows after preprocessing: {n}")
|
| 383 |
+
train_end = int(n * 0.70)
|
| 384 |
+
val_end = int(n * 0.85)
|
| 385 |
+
|
| 386 |
+
x_raw = clean[feature_names]
|
| 387 |
+
y_raw = clean[["target"]]
|
| 388 |
+
|
| 389 |
+
x_scaler = MinMaxScaler()
|
| 390 |
+
y_scaler = MinMaxScaler()
|
| 391 |
+
|
| 392 |
+
x_train = x_scaler.fit_transform(x_raw.iloc[:train_end])
|
| 393 |
+
x_val = x_scaler.transform(x_raw.iloc[train_end:val_end])
|
| 394 |
+
x_test = x_scaler.transform(x_raw.iloc[val_end:])
|
| 395 |
+
|
| 396 |
+
y_train = y_scaler.fit_transform(y_raw.iloc[:train_end]).ravel()
|
| 397 |
+
y_val = y_scaler.transform(y_raw.iloc[train_end:val_end]).ravel()
|
| 398 |
+
y_test = y_scaler.transform(y_raw.iloc[val_end:]).ravel()
|
| 399 |
+
|
| 400 |
+
if test_span_steps is not None:
|
| 401 |
+
x_test = x_test[:test_span_steps]
|
| 402 |
+
y_test = y_test[:test_span_steps]
|
| 403 |
+
|
| 404 |
+
split = SplitData(
|
| 405 |
+
x_train=x_train,
|
| 406 |
+
x_val=x_val,
|
| 407 |
+
x_test=x_test,
|
| 408 |
+
y_train=y_train,
|
| 409 |
+
y_val=y_val,
|
| 410 |
+
y_test=y_test,
|
| 411 |
+
feature_names=feature_names,
|
| 412 |
+
test_span_steps=test_span_steps,
|
| 413 |
+
)
|
| 414 |
+
return split, y_scaler, clean
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def make_lstm_sequences(np, split: SplitData, lookback: int):
|
| 418 |
+
x_all = np.vstack([split.x_train, split.x_val, split.x_test])
|
| 419 |
+
y_all = np.concatenate([split.y_train, split.y_val, split.y_test])
|
| 420 |
+
n_train = len(split.y_train)
|
| 421 |
+
n_val = len(split.y_val)
|
| 422 |
+
|
| 423 |
+
xs, ys, end_indices = [], [], []
|
| 424 |
+
for end in range(lookback, len(y_all)):
|
| 425 |
+
xs.append(x_all[end - lookback:end])
|
| 426 |
+
ys.append(y_all[end])
|
| 427 |
+
end_indices.append(end)
|
| 428 |
+
xs = np.asarray(xs)
|
| 429 |
+
ys = np.asarray(ys)
|
| 430 |
+
end_indices = np.asarray(end_indices)
|
| 431 |
+
|
| 432 |
+
train_mask = end_indices < n_train
|
| 433 |
+
val_mask = (end_indices >= n_train) & (end_indices < n_train + n_val)
|
| 434 |
+
test_mask = end_indices >= n_train + n_val
|
| 435 |
+
|
| 436 |
+
return (
|
| 437 |
+
xs[train_mask],
|
| 438 |
+
xs[val_mask],
|
| 439 |
+
xs[test_mask],
|
| 440 |
+
ys[train_mask],
|
| 441 |
+
ys[val_mask],
|
| 442 |
+
ys[test_mask],
|
| 443 |
+
)
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def inverse_metric(np, y_scaler, y_true_scaled, y_pred_scaled, mean_absolute_error, r2_score):
|
| 447 |
+
y_true = y_scaler.inverse_transform(np.asarray(y_true_scaled).reshape(-1, 1)).ravel()
|
| 448 |
+
y_pred = y_scaler.inverse_transform(np.asarray(y_pred_scaled).reshape(-1, 1)).ravel()
|
| 449 |
+
return {
|
| 450 |
+
"mae_wh": float(mean_absolute_error(y_true, y_pred)),
|
| 451 |
+
"r2": float(r2_score(y_true, y_pred)),
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
def save_feature_importance(pd, out_dir: Path, target_name: str, model_name: str, feature_names: list[str], importances):
|
| 456 |
+
importance_dir = out_dir / "feature_importance"
|
| 457 |
+
importance_dir.mkdir(parents=True, exist_ok=True)
|
| 458 |
+
table = pd.DataFrame({"feature": feature_names, "importance": importances})
|
| 459 |
+
table = table.sort_values("importance", ascending=False)
|
| 460 |
+
table.to_csv(importance_dir / f"{target_name}_{model_name}_feature_importance.csv", index=False)
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def train_baselines(stack, split: SplitData, y_scaler, args, out_dir: Path, target_name: str):
|
| 464 |
+
np = stack["np"]
|
| 465 |
+
pd = stack["pd"]
|
| 466 |
+
models = {
|
| 467 |
+
"ridge_regression": stack["Ridge"](alpha=1.0),
|
| 468 |
+
"decision_tree": stack["DecisionTreeRegressor"](max_depth=14, min_samples_split=20, random_state=42),
|
| 469 |
+
"random_forest": stack["RandomForestRegressor"](
|
| 470 |
+
n_estimators=args.rf_trees,
|
| 471 |
+
random_state=42,
|
| 472 |
+
n_jobs=-1,
|
| 473 |
+
min_samples_split=2,
|
| 474 |
+
),
|
| 475 |
+
}
|
| 476 |
+
if stack["lgb"] is not None:
|
| 477 |
+
models["lightgbm"] = stack["lgb"].LGBMRegressor(
|
| 478 |
+
n_estimators=500,
|
| 479 |
+
learning_rate=0.03,
|
| 480 |
+
num_leaves=31,
|
| 481 |
+
subsample=0.9,
|
| 482 |
+
colsample_bytree=0.9,
|
| 483 |
+
random_state=42,
|
| 484 |
+
n_jobs=-1,
|
| 485 |
+
verbose=-1,
|
| 486 |
+
)
|
| 487 |
+
rows = []
|
| 488 |
+
for name, model in models.items():
|
| 489 |
+
model.fit(split.x_train, split.y_train)
|
| 490 |
+
pred = model.predict(split.x_test)
|
| 491 |
+
metrics = inverse_metric(
|
| 492 |
+
np,
|
| 493 |
+
y_scaler,
|
| 494 |
+
split.y_test,
|
| 495 |
+
pred,
|
| 496 |
+
stack["mean_absolute_error"],
|
| 497 |
+
stack["r2_score"],
|
| 498 |
+
)
|
| 499 |
+
if name == "lightgbm" and hasattr(model, "feature_importances_"):
|
| 500 |
+
save_feature_importance(pd, out_dir, target_name, name, split.feature_names, model.feature_importances_)
|
| 501 |
+
metrics["feature_importance_path"] = str(
|
| 502 |
+
out_dir / "feature_importance" / f"{target_name}_{name}_feature_importance.csv"
|
| 503 |
+
)
|
| 504 |
+
rows.append({"model": name, **metrics})
|
| 505 |
+
if stack["lgb"] is None:
|
| 506 |
+
rows.append({
|
| 507 |
+
"model": "lightgbm",
|
| 508 |
+
"mae_wh": math.nan,
|
| 509 |
+
"r2": math.nan,
|
| 510 |
+
"note": f"lightgbm_missing: {stack.get('lgbm_import_error')}",
|
| 511 |
+
})
|
| 512 |
+
return rows
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
def train_sequence_torch(stack, split: SplitData, y_scaler, args, model_kind: str):
|
| 516 |
+
np = stack["np"]
|
| 517 |
+
torch = stack["torch"]
|
| 518 |
+
nn = stack["nn"]
|
| 519 |
+
DataLoader = stack["DataLoader"]
|
| 520 |
+
TensorDataset = stack["TensorDataset"]
|
| 521 |
+
|
| 522 |
+
torch.manual_seed(42)
|
| 523 |
+
np.random.seed(42)
|
| 524 |
+
|
| 525 |
+
x_train, x_val, x_test, y_train, y_val, y_test = make_lstm_sequences(np, split, args.lookback)
|
| 526 |
+
if len(x_train) < 100 or len(x_val) < 10 or len(x_test) < 10:
|
| 527 |
+
return [{"model": model_kind, "mae_wh": math.nan, "r2": math.nan, "note": "not_enough_sequences", "backend": "torch"}]
|
| 528 |
+
|
| 529 |
+
class DecodeLSTM(nn.Module):
|
| 530 |
+
def __init__(self, input_size: int):
|
| 531 |
+
super().__init__()
|
| 532 |
+
self.lstm = nn.LSTM(input_size=input_size, hidden_size=32, batch_first=True)
|
| 533 |
+
self.head = nn.Sequential(
|
| 534 |
+
nn.Linear(32, 5),
|
| 535 |
+
nn.ReLU(),
|
| 536 |
+
nn.Linear(5, 5),
|
| 537 |
+
nn.ReLU(),
|
| 538 |
+
nn.Linear(5, 1),
|
| 539 |
+
)
|
| 540 |
+
|
| 541 |
+
def forward(self, x):
|
| 542 |
+
output, _ = self.lstm(x)
|
| 543 |
+
return self.head(output[:, -1, :]).squeeze(-1)
|
| 544 |
+
|
| 545 |
+
class DecodeCNN1D(nn.Module):
|
| 546 |
+
def __init__(self, input_size: int):
|
| 547 |
+
super().__init__()
|
| 548 |
+
self.net = nn.Sequential(
|
| 549 |
+
nn.Conv1d(input_size, 32, kernel_size=3, padding=1),
|
| 550 |
+
nn.ReLU(),
|
| 551 |
+
nn.Conv1d(32, 32, kernel_size=3, padding=1),
|
| 552 |
+
nn.ReLU(),
|
| 553 |
+
nn.AdaptiveAvgPool1d(1),
|
| 554 |
+
)
|
| 555 |
+
self.head = nn.Sequential(
|
| 556 |
+
nn.Flatten(),
|
| 557 |
+
nn.Linear(32, 16),
|
| 558 |
+
nn.ReLU(),
|
| 559 |
+
nn.Linear(16, 1),
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
def forward(self, x):
|
| 563 |
+
x = x.transpose(1, 2)
|
| 564 |
+
return self.head(self.net(x)).squeeze(-1)
|
| 565 |
+
|
| 566 |
+
class Chomp1d(nn.Module):
|
| 567 |
+
def __init__(self, chomp_size: int):
|
| 568 |
+
super().__init__()
|
| 569 |
+
self.chomp_size = chomp_size
|
| 570 |
+
|
| 571 |
+
def forward(self, x):
|
| 572 |
+
return x[:, :, :-self.chomp_size].contiguous() if self.chomp_size else x
|
| 573 |
+
|
| 574 |
+
class DecodeTCN(nn.Module):
|
| 575 |
+
def __init__(self, input_size: int):
|
| 576 |
+
super().__init__()
|
| 577 |
+
self.net = nn.Sequential(
|
| 578 |
+
nn.Conv1d(input_size, 32, kernel_size=3, padding=2, dilation=1),
|
| 579 |
+
Chomp1d(2),
|
| 580 |
+
nn.ReLU(),
|
| 581 |
+
nn.Conv1d(32, 32, kernel_size=3, padding=4, dilation=2),
|
| 582 |
+
Chomp1d(4),
|
| 583 |
+
nn.ReLU(),
|
| 584 |
+
)
|
| 585 |
+
self.head = nn.Sequential(
|
| 586 |
+
nn.Linear(32, 16),
|
| 587 |
+
nn.ReLU(),
|
| 588 |
+
nn.Linear(16, 1),
|
| 589 |
+
)
|
| 590 |
+
|
| 591 |
+
def forward(self, x):
|
| 592 |
+
x = x.transpose(1, 2)
|
| 593 |
+
output = self.net(x).transpose(1, 2)
|
| 594 |
+
return self.head(output[:, -1, :]).squeeze(-1)
|
| 595 |
+
|
| 596 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 597 |
+
model_classes = {
|
| 598 |
+
"lstm": DecodeLSTM,
|
| 599 |
+
"cnn1d": DecodeCNN1D,
|
| 600 |
+
"tcn": DecodeTCN,
|
| 601 |
+
}
|
| 602 |
+
model = model_classes[model_kind](input_size=x_train.shape[2]).to(device)
|
| 603 |
+
criterion = nn.L1Loss()
|
| 604 |
+
optimizer = torch.optim.RMSprop(model.parameters())
|
| 605 |
+
|
| 606 |
+
train_ds = TensorDataset(
|
| 607 |
+
torch.tensor(x_train, dtype=torch.float32),
|
| 608 |
+
torch.tensor(y_train, dtype=torch.float32),
|
| 609 |
+
)
|
| 610 |
+
val_x = torch.tensor(x_val, dtype=torch.float32).to(device)
|
| 611 |
+
val_y = torch.tensor(y_val, dtype=torch.float32).to(device)
|
| 612 |
+
train_loader = DataLoader(train_ds, batch_size=args.batch_size, shuffle=False)
|
| 613 |
+
|
| 614 |
+
best_state = None
|
| 615 |
+
best_val_loss = math.inf
|
| 616 |
+
patience = 4
|
| 617 |
+
patience_left = patience
|
| 618 |
+
epochs_run = 0
|
| 619 |
+
|
| 620 |
+
for epoch in range(args.epochs):
|
| 621 |
+
model.train()
|
| 622 |
+
train_loss = 0.0
|
| 623 |
+
seen = 0
|
| 624 |
+
for batch_x, batch_y in train_loader:
|
| 625 |
+
batch_x = batch_x.to(device)
|
| 626 |
+
batch_y = batch_y.to(device)
|
| 627 |
+
optimizer.zero_grad()
|
| 628 |
+
pred = model(batch_x)
|
| 629 |
+
loss = criterion(pred, batch_y)
|
| 630 |
+
loss.backward()
|
| 631 |
+
optimizer.step()
|
| 632 |
+
train_loss += loss.item() * len(batch_y)
|
| 633 |
+
seen += len(batch_y)
|
| 634 |
+
|
| 635 |
+
model.eval()
|
| 636 |
+
with torch.no_grad():
|
| 637 |
+
val_pred = model(val_x)
|
| 638 |
+
val_loss = criterion(val_pred, val_y).item()
|
| 639 |
+
|
| 640 |
+
epochs_run = epoch + 1
|
| 641 |
+
print(f"Epoch {epochs_run}/{args.epochs} - loss: {train_loss / max(seen, 1):.6f} - val_loss: {val_loss:.6f}")
|
| 642 |
+
if val_loss < best_val_loss:
|
| 643 |
+
best_val_loss = val_loss
|
| 644 |
+
best_state = {key: value.detach().cpu().clone() for key, value in model.state_dict().items()}
|
| 645 |
+
patience_left = patience
|
| 646 |
+
else:
|
| 647 |
+
patience_left -= 1
|
| 648 |
+
if patience_left <= 0:
|
| 649 |
+
break
|
| 650 |
+
|
| 651 |
+
if best_state is not None:
|
| 652 |
+
model.load_state_dict(best_state)
|
| 653 |
+
|
| 654 |
+
model.eval()
|
| 655 |
+
test_loader = DataLoader(
|
| 656 |
+
TensorDataset(torch.tensor(x_test, dtype=torch.float32), torch.tensor(y_test, dtype=torch.float32)),
|
| 657 |
+
batch_size=args.batch_size,
|
| 658 |
+
shuffle=False,
|
| 659 |
+
)
|
| 660 |
+
preds = []
|
| 661 |
+
with torch.no_grad():
|
| 662 |
+
for batch_x, _ in test_loader:
|
| 663 |
+
preds.append(model(batch_x.to(device)).detach().cpu().numpy())
|
| 664 |
+
pred = np.concatenate(preds)
|
| 665 |
+
metrics = inverse_metric(
|
| 666 |
+
np,
|
| 667 |
+
y_scaler,
|
| 668 |
+
y_test,
|
| 669 |
+
pred,
|
| 670 |
+
stack["mean_absolute_error"],
|
| 671 |
+
stack["r2_score"],
|
| 672 |
+
)
|
| 673 |
+
metrics["epochs_run"] = epochs_run
|
| 674 |
+
metrics["backend"] = "torch"
|
| 675 |
+
metrics["device"] = str(device)
|
| 676 |
+
return [{"model": model_kind, **metrics}]
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
def train_lstm_torch(stack, split: SplitData, y_scaler, args):
|
| 680 |
+
return train_sequence_torch(stack, split, y_scaler, args, "lstm")
|
| 681 |
+
|
| 682 |
+
|
| 683 |
+
def train_cnn1d_torch(stack, split: SplitData, y_scaler, args):
|
| 684 |
+
return train_sequence_torch(stack, split, y_scaler, args, "cnn1d")
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
def train_tcn_torch(stack, split: SplitData, y_scaler, args):
|
| 688 |
+
return train_sequence_torch(stack, split, y_scaler, args, "tcn")
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
def train_lstm_keras(stack, split: SplitData, y_scaler, args):
|
| 692 |
+
np = stack["np"]
|
| 693 |
+
keras = stack["keras"]
|
| 694 |
+
tf = stack["tf"]
|
| 695 |
+
tf.random.set_seed(42)
|
| 696 |
+
np.random.seed(42)
|
| 697 |
+
|
| 698 |
+
x_train, x_val, x_test, y_train, y_val, y_test = make_lstm_sequences(np, split, args.lookback)
|
| 699 |
+
if len(x_train) < 100 or len(x_val) < 10 or len(x_test) < 10:
|
| 700 |
+
return [{"model": "lstm", "mae_wh": math.nan, "r2": math.nan, "note": "not_enough_sequences", "backend": "tensorflow"}]
|
| 701 |
+
|
| 702 |
+
model = keras.Sequential(
|
| 703 |
+
[
|
| 704 |
+
keras.layers.Input(shape=(x_train.shape[1], x_train.shape[2])),
|
| 705 |
+
keras.layers.LSTM(32),
|
| 706 |
+
keras.layers.Dense(5, activation="relu"),
|
| 707 |
+
keras.layers.Dense(5, activation="relu"),
|
| 708 |
+
keras.layers.Dense(1),
|
| 709 |
+
]
|
| 710 |
+
)
|
| 711 |
+
model.compile(optimizer=keras.optimizers.RMSprop(), loss="mae")
|
| 712 |
+
early_stop = keras.callbacks.EarlyStopping(monitor="val_loss", patience=4, restore_best_weights=True)
|
| 713 |
+
history = model.fit(
|
| 714 |
+
x_train,
|
| 715 |
+
y_train,
|
| 716 |
+
validation_data=(x_val, y_val),
|
| 717 |
+
epochs=args.epochs,
|
| 718 |
+
batch_size=args.batch_size,
|
| 719 |
+
verbose=1,
|
| 720 |
+
callbacks=[early_stop],
|
| 721 |
+
)
|
| 722 |
+
pred = model.predict(x_test, verbose=0).ravel()
|
| 723 |
+
metrics = inverse_metric(
|
| 724 |
+
np,
|
| 725 |
+
y_scaler,
|
| 726 |
+
y_test,
|
| 727 |
+
pred,
|
| 728 |
+
stack["mean_absolute_error"],
|
| 729 |
+
stack["r2_score"],
|
| 730 |
+
)
|
| 731 |
+
metrics["epochs_run"] = len(history.history["loss"])
|
| 732 |
+
metrics["backend"] = "tensorflow"
|
| 733 |
+
return [{"model": "lstm", **metrics}]
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
def train_lstm(stack, split: SplitData, y_scaler, args):
|
| 737 |
+
if args.skip_lstm:
|
| 738 |
+
return [{"model": "lstm", "mae_wh": math.nan, "r2": math.nan, "note": "skipped_by_flag"}]
|
| 739 |
+
if stack["torch"] is not None:
|
| 740 |
+
return train_lstm_torch(stack, split, y_scaler, args)
|
| 741 |
+
if stack["keras"] is not None:
|
| 742 |
+
return train_lstm_keras(stack, split, y_scaler, args)
|
| 743 |
+
note = (
|
| 744 |
+
"lstm_backend_missing: "
|
| 745 |
+
f"torch={stack.get('torch_import_error')}; "
|
| 746 |
+
f"tensorflow={stack.get('tf_import_error')}"
|
| 747 |
+
)
|
| 748 |
+
return [{"model": "lstm", "mae_wh": math.nan, "r2": math.nan, "note": note}]
|
| 749 |
+
|
| 750 |
+
|
| 751 |
+
def train_deep_models(stack, split: SplitData, y_scaler, args):
|
| 752 |
+
requested = {item.strip().lower() for item in args.dl_models.split(",") if item.strip()}
|
| 753 |
+
if "none" in requested or args.skip_lstm:
|
| 754 |
+
return [{"model": "deep_models", "mae_wh": math.nan, "r2": math.nan, "note": "skipped_by_flag"}]
|
| 755 |
+
|
| 756 |
+
rows = []
|
| 757 |
+
if "lstm" in requested:
|
| 758 |
+
rows.extend(train_lstm(stack, split, y_scaler, args))
|
| 759 |
+
|
| 760 |
+
torch_missing_note = f"torch_missing: {stack.get('torch_import_error')}"
|
| 761 |
+
if "cnn" in requested:
|
| 762 |
+
requested.add("cnn1d")
|
| 763 |
+
if "cnn1d" in requested:
|
| 764 |
+
if stack["torch"] is not None:
|
| 765 |
+
rows.extend(train_cnn1d_torch(stack, split, y_scaler, args))
|
| 766 |
+
else:
|
| 767 |
+
rows.append({"model": "cnn1d", "mae_wh": math.nan, "r2": math.nan, "note": torch_missing_note})
|
| 768 |
+
if "tcn" in requested:
|
| 769 |
+
if stack["torch"] is not None:
|
| 770 |
+
rows.extend(train_tcn_torch(stack, split, y_scaler, args))
|
| 771 |
+
else:
|
| 772 |
+
rows.append({"model": "tcn", "mae_wh": math.nan, "r2": math.nan, "note": torch_missing_note})
|
| 773 |
+
return rows
|
| 774 |
+
|
| 775 |
+
|
| 776 |
+
def train_arima(stack, clean, args):
|
| 777 |
+
if not args.include_arima:
|
| 778 |
+
return [{"model": "arima", "mae_wh": math.nan, "r2": math.nan, "note": "skipped_enable_with_include_arima"}]
|
| 779 |
+
if stack["ARIMA"] is None:
|
| 780 |
+
return [{
|
| 781 |
+
"model": "arima",
|
| 782 |
+
"mae_wh": math.nan,
|
| 783 |
+
"r2": math.nan,
|
| 784 |
+
"note": f"statsmodels_missing: {stack.get('statsmodels_import_error')}",
|
| 785 |
+
}]
|
| 786 |
+
|
| 787 |
+
n = len(clean)
|
| 788 |
+
train_end = int(n * 0.70)
|
| 789 |
+
val_end = int(n * 0.85)
|
| 790 |
+
history = clean["energy_wh"].iloc[:val_end].dropna()
|
| 791 |
+
if args.arima_max_train and len(history) > args.arima_max_train:
|
| 792 |
+
history = history.iloc[-args.arima_max_train:]
|
| 793 |
+
y_true = clean["target"].iloc[val_end:].dropna()
|
| 794 |
+
test_span_steps = test_span_steps_from_args(stack["pd"], args)
|
| 795 |
+
if test_span_steps is not None:
|
| 796 |
+
y_true = y_true.iloc[:test_span_steps]
|
| 797 |
+
if len(history) < 50 or len(y_true) < 10:
|
| 798 |
+
return [{"model": "arima", "mae_wh": math.nan, "r2": math.nan, "note": "not_enough_points"}]
|
| 799 |
+
|
| 800 |
+
try:
|
| 801 |
+
model = stack["ARIMA"](history, order=(2, 1, 2))
|
| 802 |
+
fitted = model.fit()
|
| 803 |
+
forecast = fitted.forecast(steps=len(y_true))
|
| 804 |
+
metrics = {
|
| 805 |
+
"mae_wh": float(stack["mean_absolute_error"](y_true, forecast)),
|
| 806 |
+
"r2": float(stack["r2_score"](y_true, forecast)),
|
| 807 |
+
"note": f"order=(2,1,2); train_points={len(history)}",
|
| 808 |
+
}
|
| 809 |
+
return [{"model": "arima", **metrics}]
|
| 810 |
+
except Exception as exc:
|
| 811 |
+
return [{"model": "arima", "mae_wh": math.nan, "r2": math.nan, "note": f"arima_failed: {type(exc).__name__}: {exc}"}]
|
| 812 |
+
|
| 813 |
+
|
| 814 |
+
def save_dataset(pd, clean, out_dir: Path, target_name: str):
|
| 815 |
+
out_path = out_dir / "processed" / f"{target_name}_train_ready.csv"
|
| 816 |
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
| 817 |
+
clean.to_csv(out_path)
|
| 818 |
+
return out_path
|
| 819 |
+
|
| 820 |
+
|
| 821 |
+
def run_target(stack, args, energy_10min, calendar, target_name: str, target_spec: dict, out_dir: Path):
|
| 822 |
+
pd = stack["pd"]
|
| 823 |
+
np = stack["np"]
|
| 824 |
+
horizon_steps = horizon_steps_from_args(pd, args)
|
| 825 |
+
test_span_steps = test_span_steps_from_args(pd, args)
|
| 826 |
+
print(f"\n=== Target: {target_name} ===")
|
| 827 |
+
print(f"Horizon: {horizon_steps} step(s) = {describe_steps(pd, horizon_steps, args.freq)}")
|
| 828 |
+
print(f"Lookback: {args.lookback} step(s) = {describe_steps(pd, args.lookback, args.freq)}")
|
| 829 |
+
if test_span_steps is not None:
|
| 830 |
+
print(f"Test span: {test_span_steps} step(s) = {describe_steps(pd, test_span_steps, args.freq)}")
|
| 831 |
+
df = build_target_frame(
|
| 832 |
+
pd,
|
| 833 |
+
energy_10min,
|
| 834 |
+
calendar,
|
| 835 |
+
target_name,
|
| 836 |
+
target_spec,
|
| 837 |
+
args.freq,
|
| 838 |
+
args.include_weather,
|
| 839 |
+
)
|
| 840 |
+
split, y_scaler, clean = make_ml_split(
|
| 841 |
+
np,
|
| 842 |
+
pd,
|
| 843 |
+
stack["MinMaxScaler"],
|
| 844 |
+
df,
|
| 845 |
+
horizon=horizon_steps,
|
| 846 |
+
max_rows=args.max_rows,
|
| 847 |
+
test_span_steps=test_span_steps,
|
| 848 |
+
)
|
| 849 |
+
dataset_path = save_dataset(pd, clean, out_dir, target_name)
|
| 850 |
+
print(f"Rows after feature engineering: {len(clean):,}")
|
| 851 |
+
print(f"Train/val/test: {len(split.y_train):,}/{len(split.y_val):,}/{len(split.y_test):,}")
|
| 852 |
+
print(f"Saved train-ready table: {dataset_path}")
|
| 853 |
+
|
| 854 |
+
rows = []
|
| 855 |
+
rows.extend(train_baselines(stack, split, y_scaler, args, out_dir, target_name))
|
| 856 |
+
rows.extend(train_deep_models(stack, split, y_scaler, args))
|
| 857 |
+
rows.extend(train_arima(stack, clean, args))
|
| 858 |
+
for row in rows:
|
| 859 |
+
row["target"] = target_name
|
| 860 |
+
row["rows"] = len(clean)
|
| 861 |
+
row["features"] = len(split.feature_names)
|
| 862 |
+
row["horizon_steps"] = horizon_steps
|
| 863 |
+
row["horizon"] = describe_steps(pd, horizon_steps, args.freq)
|
| 864 |
+
row["lookback_steps"] = args.lookback
|
| 865 |
+
row["lookback"] = describe_steps(pd, args.lookback, args.freq)
|
| 866 |
+
row["test_span_steps"] = test_span_steps if test_span_steps is not None else len(split.y_test)
|
| 867 |
+
row["test_span"] = describe_steps(pd, row["test_span_steps"], args.freq)
|
| 868 |
+
return rows
|
| 869 |
+
|
| 870 |
+
|
| 871 |
+
def main() -> int:
|
| 872 |
+
args = parse_args()
|
| 873 |
+
stack = import_stack()
|
| 874 |
+
pd = stack["pd"]
|
| 875 |
+
|
| 876 |
+
out_dir = Path(args.output_dir)
|
| 877 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 878 |
+
(out_dir / "processed").mkdir(exist_ok=True)
|
| 879 |
+
|
| 880 |
+
config = PAPER_BUILDINGS if args.mode == "paper_buildings" else METER_TARGETS
|
| 881 |
+
if args.target != "all":
|
| 882 |
+
if args.target not in config:
|
| 883 |
+
raise SystemExit(f"Unknown target {args.target!r}. Available: {', '.join(config)}")
|
| 884 |
+
config = {args.target: config[args.target]}
|
| 885 |
+
|
| 886 |
+
print("DECODE re-implementation")
|
| 887 |
+
print(f"Mode: {args.mode}")
|
| 888 |
+
print(f"Frequency: {args.freq}")
|
| 889 |
+
print(f"Python executable: {sys.executable}")
|
| 890 |
+
print(f"PyTorch available: {stack['torch'] is not None}")
|
| 891 |
+
if stack["torch"] is None:
|
| 892 |
+
print(f"PyTorch import error: {stack.get('torch_import_error')}")
|
| 893 |
+
print(f"TensorFlow available: {stack['keras'] is not None}")
|
| 894 |
+
if stack["keras"] is None:
|
| 895 |
+
print(f"TensorFlow import error: {stack.get('tf_import_error')}")
|
| 896 |
+
print(f"LightGBM available: {stack['lgb'] is not None}")
|
| 897 |
+
if stack["lgb"] is None:
|
| 898 |
+
print(f"LightGBM import error: {stack.get('lgbm_import_error')}")
|
| 899 |
+
print(f"Statsmodels ARIMA available: {stack['ARIMA'] is not None}")
|
| 900 |
+
if stack["ARIMA"] is None:
|
| 901 |
+
print(f"Statsmodels import error: {stack.get('statsmodels_import_error')}")
|
| 902 |
+
if not args.skip_lstm:
|
| 903 |
+
if stack["torch"] is not None:
|
| 904 |
+
print("LSTM backend: PyTorch")
|
| 905 |
+
elif stack["keras"] is not None:
|
| 906 |
+
print("LSTM backend: TensorFlow/Keras")
|
| 907 |
+
else:
|
| 908 |
+
print("LSTM backend: unavailable")
|
| 909 |
+
|
| 910 |
+
energy_10min = read_energy_10min(pd, args.freq)
|
| 911 |
+
calendar = read_calendar(pd)
|
| 912 |
+
|
| 913 |
+
all_rows = []
|
| 914 |
+
for target_name, target_spec in config.items():
|
| 915 |
+
rows = run_target(stack, args, energy_10min, calendar, target_name, target_spec, out_dir)
|
| 916 |
+
all_rows.extend(rows)
|
| 917 |
+
|
| 918 |
+
results = pd.DataFrame(all_rows)
|
| 919 |
+
effective_horizon = horizon_steps_from_args(pd, args)
|
| 920 |
+
effective_test_span = test_span_steps_from_args(pd, args)
|
| 921 |
+
result_suffix = f"h{effective_horizon}"
|
| 922 |
+
if effective_test_span is not None:
|
| 923 |
+
result_suffix += f"_ts{effective_test_span}"
|
| 924 |
+
result_path = out_dir / f"results_{args.mode}_{result_suffix}.csv"
|
| 925 |
+
results.to_csv(result_path, index=False)
|
| 926 |
+
|
| 927 |
+
metadata = {
|
| 928 |
+
"mode": args.mode,
|
| 929 |
+
"target": args.target,
|
| 930 |
+
"freq": args.freq,
|
| 931 |
+
"lookback": args.lookback,
|
| 932 |
+
"horizon": args.horizon,
|
| 933 |
+
"horizon_days": args.horizon_days,
|
| 934 |
+
"horizon_steps_effective": horizon_steps_from_args(pd, args),
|
| 935 |
+
"test_span_days": args.test_span_days,
|
| 936 |
+
"test_span_steps_effective": test_span_steps_from_args(pd, args),
|
| 937 |
+
"epochs": args.epochs,
|
| 938 |
+
"batch_size": args.batch_size,
|
| 939 |
+
"rf_trees": args.rf_trees,
|
| 940 |
+
"dl_models": args.dl_models,
|
| 941 |
+
"include_arima": args.include_arima,
|
| 942 |
+
"include_weather": args.include_weather,
|
| 943 |
+
"pytorch_available": stack["torch"] is not None,
|
| 944 |
+
"torch_import_error": stack.get("torch_import_error"),
|
| 945 |
+
"lightgbm_available": stack["lgb"] is not None,
|
| 946 |
+
"lightgbm_import_error": stack.get("lgbm_import_error"),
|
| 947 |
+
"statsmodels_available": stack["ARIMA"] is not None,
|
| 948 |
+
"statsmodels_import_error": stack.get("statsmodels_import_error"),
|
| 949 |
+
"tensorflow_available": stack["keras"] is not None,
|
| 950 |
+
"tensorflow_import_error": stack.get("tf_import_error"),
|
| 951 |
+
"energy_file": str(ENERGY_FILE),
|
| 952 |
+
"occupancy_dir": str(OCCUPANCY_DIR),
|
| 953 |
+
"calendar_dir": str(CALENDAR_DIR),
|
| 954 |
+
"weather_file": str(WEATHER_FILE),
|
| 955 |
+
}
|
| 956 |
+
(out_dir / f"run_config_{args.mode}.json").write_text(json.dumps(metadata, indent=2), encoding="utf-8")
|
| 957 |
+
|
| 958 |
+
print("\n=== Results ===")
|
| 959 |
+
print(results.sort_values(["target", "mae_wh"]).to_string(index=False))
|
| 960 |
+
print(f"\nSaved results: {result_path}")
|
| 961 |
+
return 0
|
| 962 |
+
|
| 963 |
+
|
| 964 |
+
if __name__ == "__main__":
|
| 965 |
+
raise SystemExit(main())
|