File size: 14,635 Bytes
9dd9495 df71594 9dd9495 df71594 9dd9495 df71594 5db54f2 df71594 5db54f2 df71594 6d4379d 9dd9495 df71594 9dd9495 df71594 9dd9495 df71594 6d4379d df71594 9dd9495 df71594 6d4379d 9dd9495 df71594 9dd9495 df71594 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 6d4379d 9dd9495 df71594 9dd9495 6d4379d 9dd9495 5cbcc6d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 | {
"cells": [
{
"cell_type": "markdown",
"id": "bdb90c6a",
"metadata": {},
"source": [
"# DECODE Paper Re-implementation\n",
"\n",
"Notebook wrapper này chạy lại pipeline theo paper DECODE trên dữ liệu local I-BLEND. Logic chính nằm trong `scripts/decode_reimplementation.py`.\n",
"\n",
"Pipeline:\n",
"- Resample về 10 phút.\n",
"- Convert power W thành interval energy Wh.\n",
"- Merge occupancy + calendar/schedule.\n",
"- Tạo historical features, gồm 3 ngày trước cùng loại working/non-working day tại cùng thời điểm.\n",
"- Min-Max normalization.\n",
"- Split theo thời gian 70/15/15.\n",
"- Train Ridge, Decision Tree, Random Forest, LightGBM nếu có, LSTM, 1D-CNN, TCN, và ARIMA nếu bật `--include-arima`.\n",
"- LSTM/1D-CNN/TCN ưu tiên PyTorch nếu có; LSTM fallback TensorFlow/Keras."
]
},
{
"cell_type": "markdown",
"id": "f6c2854f",
"metadata": {},
"source": [
"## 0. Download Data And Code From Hugging Face\n",
"\n",
"Khi chạy notebook ở môi trường khác, tải **data repo** và **code repo** riêng. Nếu đang chạy local trong workspace này thì có thể bỏ qua cell này; `SCRIPT_PATH` sẽ được set về script local ở cell kế tiếp."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7f558695",
"metadata": {},
"outputs": [],
"source": [
"# Run this in a fresh environment after uploading data and code to separate Hugging Face repos.\n",
"# This notebook intentionally uses subprocess instead of notebook magics, so it also works in Marimo/Colab-like runners.\n",
"\n",
"from pathlib import Path\n",
"import importlib.util\n",
"import os\n",
"import shlex\n",
"import subprocess\n",
"import sys\n",
"\n",
"def run_cmd(cmd, *, env=None):\n",
" cmd = [str(x) for x in cmd]\n",
" print(\"Running:\", \" \".join(shlex.quote(x) for x in cmd))\n",
" return subprocess.run(cmd, check=True, env=env)\n",
"\n",
"def pip_install(*packages, extra_args=None):\n",
" cmd = [sys.executable, \"-m\", \"pip\", \"install\", \"-q\"]\n",
" if extra_args:\n",
" cmd.extend(extra_args)\n",
" cmd.extend(packages)\n",
" run_cmd(cmd)\n",
"\n",
"def ensure_package(import_name, pip_name=None, *, extra_args=None):\n",
" if importlib.util.find_spec(import_name) is None:\n",
" pip_install(pip_name or import_name, extra_args=extra_args)\n",
"\n",
"ensure_package(\"huggingface_hub\")\n",
"ensure_package(\"numpy\")\n",
"ensure_package(\"pandas\")\n",
"ensure_package(\"sklearn\", \"scikit-learn\")\n",
"ensure_package(\"statsmodels\")\n",
"ensure_package(\"lightgbm\")\n",
"\n",
"# GPU PyTorch wheel. The marimo GPU runner currently exposes CUDA 13.0.\n",
"# If your platform needs a different CUDA build, change cu130 to cu121/cu124.\n",
"ensure_package(\"torch\", \"torch\", extra_args=[\"--index-url\", \"https://download.pytorch.org/whl/cu130\"])\n",
"\n",
"import torch\n",
"print(\"PyTorch:\", torch.__version__)\n",
"print(\"CUDA available:\", torch.cuda.is_available())\n",
"if torch.cuda.is_available():\n",
" print(\"GPU:\", torch.cuda.get_device_name(0))\n",
"\n",
"HF_DATA_REPO_ID = \"HoangTrungNguyen/decode-iblend-data\"\n",
"HF_CODE_REPO_ID = \"HoangTrungNguyen/decode-iblend-code\"\n",
"CODE_REPO_TYPE = \"model\" # use \"dataset\" if you uploaded code as a dataset repo\n",
"\n",
"DATA_DIR = Path(\"hf_data\")\n",
"CODE_DIR = Path(\"hf_code\")\n",
"LOCAL_SCRIPT = Path(\"scripts/decode_reimplementation.py\")\n",
"\n",
"if HF_DATA_REPO_ID and HF_CODE_REPO_ID:\n",
" from huggingface_hub import snapshot_download\n",
" snapshot_download(\n",
" repo_id=HF_DATA_REPO_ID,\n",
" repo_type=\"dataset\",\n",
" local_dir=str(DATA_DIR),\n",
" local_dir_use_symlinks=False,\n",
" )\n",
" snapshot_download(\n",
" repo_id=HF_CODE_REPO_ID,\n",
" repo_type=CODE_REPO_TYPE,\n",
" local_dir=str(CODE_DIR),\n",
" local_dir_use_symlinks=False,\n",
" )\n",
" os.environ[\"IBLEND_DATA_ROOT\"] = str(DATA_DIR.resolve())\n",
" SCRIPT_PATH = str((CODE_DIR / \"scripts\" / \"decode_reimplementation.py\").resolve())\n",
"else:\n",
" SCRIPT_PATH = str(LOCAL_SCRIPT.resolve())\n",
" print(\"Set HF_DATA_REPO_ID and HF_CODE_REPO_ID first if you need to download from Hugging Face.\")\n",
"\n",
"OUTPUT_DIR = Path(SCRIPT_PATH).resolve().parents[1] / \"decode_reimplementation_outputs\"\n",
"\n",
"TRAIN_ENV = os.environ.copy()\n",
"TRAIN_ENV[\"DECODE_DISABLE_TENSORFLOW\"] = \"1\"\n",
"TRAIN_ENV.pop(\"CUDA_VISIBLE_DEVICES\", None)\n",
"if \"IBLEND_DATA_ROOT\" in os.environ:\n",
" TRAIN_ENV[\"IBLEND_DATA_ROOT\"] = os.environ[\"IBLEND_DATA_ROOT\"]\n",
"\n",
"print(\"Data root:\", os.environ.get(\"IBLEND_DATA_ROOT\", \"local/default\"))\n",
"print(\"Script path:\", SCRIPT_PATH)\n",
"print(\"Output dir:\", OUTPUT_DIR)\n",
"print(\"Subprocess CUDA_VISIBLE_DEVICES:\", TRAIN_ENV.get(\"CUDA_VISIBLE_DEVICES\", \"all devices\"))\n"
]
},
{
"cell_type": "markdown",
"id": "450521e7",
"metadata": {},
"source": [
"## 1. Check Dependencies"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "83b7b2b8",
"metadata": {},
"outputs": [],
"source": [
"import importlib.util\n",
"\n",
"packages = ['numpy', 'pandas', 'sklearn', 'torch', 'lightgbm', 'statsmodels']\n",
"for package in packages:\n",
" status = 'OK' if importlib.util.find_spec(package) else 'MISSING'\n",
" print(f'{package}: {status}')"
]
},
{
"cell_type": "markdown",
"id": "038ac26a",
"metadata": {},
"source": [
"Cell đầu đã tự cài các package cần thiết bằng `subprocess` trong đúng kernel hiện tại. Deep learning chạy bằng PyTorch; nếu CUDA khả dụng, script sẽ tự dùng GPU."
]
},
{
"cell_type": "markdown",
"id": "quick_smoke_md",
"metadata": {},
"source": [
"## 2. Quick Smoke Test\n",
"\n",
"Chạy nhanh một building với 20,000 dòng để kiểm tra pipeline, LightGBM feature importance và PyTorch GPU."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "quick_smoke_code",
"metadata": {},
"outputs": [],
"source": [
"subprocess.run([\n",
" sys.executable, SCRIPT_PATH,\n",
" \"--mode\", \"paper_buildings\",\n",
" \"--target\", \"Academic\",\n",
" \"--max-rows\", \"20000\",\n",
" \"--epochs\", \"5\",\n",
" \"--batch-size\", \"64\",\n",
" \"--dl-models\", \"lstm\",\n",
"], check=True, env=TRAIN_ENV)"
]
},
{
"cell_type": "markdown",
"id": "baseline_md",
"metadata": {},
"source": [
"## 3. Baselines + LightGBM Feature Importance\n",
"\n",
"Chạy toàn bộ 7 building-level targets với Ridge, Decision Tree, Random Forest và LightGBM. Deep learning được skip ở cell này để lấy baseline và file feature importance trước."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "baseline_code",
"metadata": {},
"outputs": [],
"source": [
"subprocess.run([\n",
" sys.executable, SCRIPT_PATH,\n",
" \"--mode\", \"paper_buildings\",\n",
" \"--skip-lstm\",\n",
"], check=True, env=TRAIN_ENV)"
]
},
{
"cell_type": "markdown",
"id": "lstm_all_md",
"metadata": {},
"source": [
"## 4. Deep Learning: LSTM For All Buildings\n",
"\n",
"Chạy riêng LSTM cho toàn bộ 7 building-level targets. Default `horizon=1` nghĩa là dự đoán 10 phút tới."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "lstm_all_code",
"metadata": {},
"outputs": [],
"source": [
"subprocess.run([\n",
" sys.executable, SCRIPT_PATH,\n",
" \"--mode\", \"paper_buildings\",\n",
" \"--epochs\", \"20\",\n",
" \"--batch-size\", \"64\",\n",
" \"--dl-models\", \"lstm\",\n",
"], check=True, env=TRAIN_ENV)"
]
},
{
"cell_type": "markdown",
"id": "cnn_all_md",
"metadata": {},
"source": [
"## 5. Deep Learning: 1D-CNN For All Buildings\n",
"\n",
"Chạy riêng 1D-CNN cho toàn bộ 7 building-level targets."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cnn_all_code",
"metadata": {},
"outputs": [],
"source": [
"subprocess.run([\n",
" sys.executable, SCRIPT_PATH,\n",
" \"--mode\", \"paper_buildings\",\n",
" \"--epochs\", \"20\",\n",
" \"--batch-size\", \"64\",\n",
" \"--dl-models\", \"cnn\",\n",
"], check=True, env=TRAIN_ENV)"
]
},
{
"cell_type": "markdown",
"id": "tcn_all_md",
"metadata": {},
"source": [
"## 6. Deep Learning: TCN For All Buildings\n",
"\n",
"Chạy riêng TCN cho toàn bộ 7 building-level targets."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "tcn_all_code",
"metadata": {},
"outputs": [],
"source": [
"subprocess.run([\n",
" sys.executable, SCRIPT_PATH,\n",
" \"--mode\", \"paper_buildings\",\n",
" \"--epochs\", \"20\",\n",
" \"--batch-size\", \"64\",\n",
" \"--dl-models\", \"tcn\",\n",
"], check=True, env=TRAIN_ENV)"
]
},
{
"cell_type": "markdown",
"id": "meters_md",
"metadata": {},
"source": [
"## 7. Optional: Train 9 Local Meter Models\n",
"\n",
"Chế độ này train riêng 9 meter trong `all_buildings_power.csv`. Chạy từng model riêng để dễ so sánh và tránh một cell quá dài."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "meters_code",
"metadata": {},
"outputs": [],
"source": [
"for model_name in [\"lstm\", \"cnn\", \"tcn\"]:\n",
" subprocess.run([\n",
" sys.executable, SCRIPT_PATH,\n",
" \"--mode\", \"meters\",\n",
" \"--epochs\", \"20\",\n",
" \"--batch-size\", \"64\",\n",
" \"--dl-models\", model_name,\n",
" ], check=True, env=TRAIN_ENV)"
]
},
{
"cell_type": "markdown",
"id": "horizon_md",
"metadata": {},
"source": [
"## 8. Forecast Horizon Examples\n",
"\n",
"Mặc định `--horizon 1` nghĩa là dự báo 1 bước tới. Với `freq=10min`, đó là 10 phút tới. Muốn dự báo 1 ngày tới, dùng `--horizon-days 1`. ARIMA có thể chậm nên chỉ bật khi cần bằng `--include-arima`."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "horizon_code",
"metadata": {},
"outputs": [],
"source": [
"subprocess.run([\n",
" sys.executable, SCRIPT_PATH,\n",
" \"--mode\", \"paper_buildings\",\n",
" \"--target\", \"Academic\",\n",
" \"--horizon-days\", \"1\",\n",
" \"--lookback\", \"144\",\n",
" \"--epochs\", \"20\",\n",
" \"--batch-size\", \"64\",\n",
" \"--dl-models\", \"lstm\",\n",
"], check=True, env=TRAIN_ENV)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "arima_code",
"metadata": {},
"outputs": [],
"source": [
"subprocess.run([\n",
" sys.executable, SCRIPT_PATH,\n",
" \"--mode\", \"paper_buildings\",\n",
" \"--target\", \"Academic\",\n",
" \"--horizon\", \"6\",\n",
" \"--lookback\", \"144\",\n",
" \"--skip-lstm\",\n",
" \"--include-arima\",\n",
" \"--arima-max-train\", \"20000\",\n",
"], check=True, env=TRAIN_ENV)"
]
},
{
"cell_type": "markdown",
"id": "testspan_md",
"metadata": {},
"source": [
"## 9. Paper-style Test Span: 1 Week\n",
"\n",
"Giống cách paper báo cáo performance trên các test spans, cell này vẫn split chronological 70/15/15 nhưng chỉ evaluate 1 tuần đầu của test split. Mặc định horizon vẫn là 10 phút tới."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "testspan_dl_code",
"metadata": {},
"outputs": [],
"source": [
"for model_name in [\"lstm\", \"cnn\", \"tcn\"]:\n",
" subprocess.run([\n",
" sys.executable, SCRIPT_PATH,\n",
" \"--mode\", \"paper_buildings\",\n",
" \"--target\", \"Academic\",\n",
" \"--test-span-days\", \"7\",\n",
" \"--dl-models\", model_name,\n",
" \"--epochs\", \"20\",\n",
" \"--batch-size\", \"64\",\n",
" ], check=True, env=TRAIN_ENV)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "testspan_arima_code",
"metadata": {},
"outputs": [],
"source": [
"subprocess.run([\n",
" sys.executable, SCRIPT_PATH,\n",
" \"--mode\", \"paper_buildings\",\n",
" \"--target\", \"Academic\",\n",
" \"--test-span-days\", \"7\",\n",
" \"--skip-lstm\",\n",
" \"--include-arima\",\n",
" \"--arima-max-train\", \"20000\",\n",
"], check=True, env=TRAIN_ENV)"
]
},
{
"cell_type": "markdown",
"id": "5687ab98",
"metadata": {},
"source": [
"## 10. Load Results"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e2f16525",
"metadata": {},
"outputs": [],
"source": [
"from pathlib import Path\n",
"import pandas as pd\n",
"\n",
"out = OUTPUT_DIR\n",
"for path in sorted(out.glob('results_*.csv')):\n",
" print('\n",
"', path)\n",
" results_df = pd.read_csv(path).sort_values(['target', 'model'])\n",
" display(results_df)\n",
"\n",
"importance_dir = out / 'feature_importance'\n",
"if importance_dir.exists():\n",
" print('\n",
"Feature importance files:')\n",
" for path in sorted(importance_dir.glob('*_lightgbm_feature_importance.csv')):\n",
" print(path)\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "tf_linux",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.20"
}
},
"nbformat": 4,
"nbformat_minor": 5
} |