-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain.py
More file actions
2541 lines (2323 loc) · 114 KB
/
Copy pathtrain.py
File metadata and controls
2541 lines (2323 loc) · 114 KB
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import argparse
import json
import math
import os
import pickle
import random
import shutil
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from scipy.stats import pearsonr, spearmanr
from sklearn.linear_model import LogisticRegression, Ridge
from sklearn.metrics import (
average_precision_score,
balanced_accuracy_score,
brier_score_loss,
f1_score,
log_loss,
mean_absolute_error,
mean_squared_error,
median_absolute_error,
precision_score,
r2_score,
recall_score,
roc_auc_score,
)
PROJECT_ROOT = Path(__file__).resolve().parent
MODEL_READY_ROOT = Path("data/cache/model_ready")
EXPERIMENT_ROOT = Path("experiments")
MODEL_REGISTRY = {
"logistic_regression": {"families": ["tabular"], "implemented": True},
"xgboost": {"families": ["tabular"], "implemented": True},
"mlp": {"families": ["tabular"], "implemented": True},
"gru": {"families": ["temporal", "sequence"], "implemented": True},
"tcn": {"families": ["temporal", "sequence"], "implemented": True},
"transformer": {"families": ["temporal", "sequence"], "implemented": True},
"resnet18_unet": {"families": ["spatial"], "implemented": True},
"resnet50_unet": {"families": ["spatial"], "implemented": True},
"swin_unet": {"families": ["spatial"], "implemented": True},
"segformer": {"families": ["spatial"], "implemented": True},
"convlstm": {"families": ["spatiotemporal"], "implemented": True},
"convgru": {"families": ["spatiotemporal"], "implemented": True},
"predrnn_v2": {"families": ["spatiotemporal"], "implemented": True},
"utae": {"families": ["spatiotemporal"], "implemented": True},
"swinlstm": {"families": ["spatiotemporal"], "implemented": True},
"resnet3d": {"families": ["spatiotemporal"], "implemented": True},
}
def created_at() -> str:
return datetime.now(timezone.utc).isoformat()
def ensure_project_path(path: Path) -> Path:
resolved = path.resolve()
if not str(resolved).startswith(str(PROJECT_ROOT)):
raise ValueError(f"Path must stay inside {PROJECT_ROOT}: {resolved}")
return resolved
def json_ready(value):
if isinstance(value, Path):
return str(value)
if isinstance(value, np.generic):
return value.item()
if isinstance(value, np.ndarray):
return value.tolist()
if isinstance(value, dict):
return {str(k): json_ready(v) for k, v in value.items()}
if isinstance(value, (list, tuple)):
return [json_ready(v) for v in value]
return value
def write_json(path: Path, payload: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8") as file:
json.dump(json_ready(payload), file, indent=2, sort_keys=True)
file.write("\n")
def set_seed(seed: int) -> None:
random.seed(seed)
np.random.seed(seed)
try:
import torch
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = False
torch.backends.cudnn.benchmark = True
except Exception:
pass
def sigmoid(x: np.ndarray) -> np.ndarray:
x = np.asarray(x, dtype=np.float64)
return 1.0 / (1.0 + np.exp(-np.clip(x, -80, 80)))
def safe_logit(p: np.ndarray) -> np.ndarray:
p = np.asarray(p, dtype=np.float64)
p = np.clip(p, 1e-7, 1.0 - 1e-7)
return np.log(p / (1.0 - p))
def output_model_name(task: str, model_name: str) -> str:
if task == "containment_time" and model_name == "logistic_regression":
return "ridge_regression"
return model_name
def cache_representation_name(representation: str) -> str:
return "temporal" if representation == "sequence" else representation
def canonical_representation_name(representation: str) -> str:
return "temporal" if representation == "sequence" else representation
def cache_dir(base_dir: Path, task: str, representation: str, weather_days: int, input_protocol: str) -> Path:
rep = cache_representation_name(representation)
primary = base_dir / MODEL_READY_ROOT / task / rep / f"weather{weather_days}_{input_protocol}"
if primary.exists():
return primary
if representation == "sequence":
fallback = base_dir / MODEL_READY_ROOT / task / "sequence" / f"weather{weather_days}_{input_protocol}"
if fallback.exists():
return fallback
return primary
def run_dir(
base_dir: Path,
task: str,
experiment_type: str,
ablation_name: str | None,
run_tag: str | None,
representation: str,
weather_days: int,
input_protocol: str,
model_name: str,
seed: int,
) -> Path:
if experiment_type == "ablation" and ablation_name == "protocol_sweep" and run_tag:
return (
base_dir
/ EXPERIMENT_ROOT
/ task
/ "ablation"
/ "protocol_sweep"
/ run_tag
/ representation
/ f"weather{weather_days}_{input_protocol}"
/ f"{model_name}_seed{seed}"
)
if experiment_type == "ablation" and ablation_name:
return (
base_dir
/ EXPERIMENT_ROOT
/ task
/ "ablation"
/ ablation_name
/ representation
/ f"weather{weather_days}_{input_protocol}"
/ f"{model_name}_seed{seed}"
)
return (
base_dir
/ EXPERIMENT_ROOT
/ task
/ experiment_type
/ representation
/ f"weather{weather_days}_{input_protocol}"
/ f"{model_name}_seed{seed}"
)
def prepare_run_dir(path: Path, overwrite: bool) -> None:
if path.exists():
if not overwrite:
raise FileExistsError(f"Run directory already exists. Pass --overwrite to replace it: {path}")
shutil.rmtree(path)
path.mkdir(parents=True, exist_ok=True)
def load_json_if_exists(path: Path) -> dict:
if not path.exists():
return {}
with path.open("r", encoding="utf-8") as file:
return json.load(file)
def is_temporal_representation(representation: str) -> bool:
return representation in {"temporal", "sequence"}
def load_split_array(cache: Path, split: str, representation: str) -> np.ndarray:
if is_temporal_representation(representation):
candidates = [cache / f"X_seq_{split}.npy", cache / f"X_{split}.npy"]
else:
candidates = [cache / f"X_{split}.npy"]
for path in candidates:
if path.exists():
mmap_mode = "r" if canonical_representation_name(representation) in {"spatial", "spatiotemporal"} else None
return np.load(path, mmap_mode=mmap_mode)
raise FileNotFoundError(f"Missing X array for {split}. Tried: {candidates}")
def finite_check_array(x: np.ndarray, max_exact_values: int = 50_000_000) -> bool:
"""Avoid a full multi-GB scan for patch caches during smoke runs."""
if x.size <= max_exact_values:
return bool(np.isfinite(x).all())
rng = np.random.default_rng(0)
sample_size = min(512, x.shape[0])
rows = rng.choice(x.shape[0], size=sample_size, replace=False)
return bool(np.isfinite(x[rows]).all())
def load_cache(cache: Path, task: str, representation: str) -> dict[str, Any]:
required_common = ["y", "fire_id", "sample_index"]
data: dict[str, Any] = {"cache_dir": str(cache)}
for split in ["train", "val", "test"]:
for kind in required_common:
suffix = "npy" if kind in {"y", "fire_id"} else "parquet"
file = cache / f"{kind}_{split}.{suffix}"
if not file.exists():
raise FileNotFoundError(f"Missing required cache file: {file}")
if is_temporal_representation(representation):
x_seq_path = cache / f"X_seq_{split}.npy"
x_static_path = cache / f"X_static_{split}.npy"
if not x_seq_path.exists() or not x_static_path.exists():
raise FileNotFoundError(f"Missing temporal cache arrays: {x_seq_path}, {x_static_path}")
X = {
"seq": np.load(x_seq_path),
"static": np.load(x_static_path),
}
else:
X = load_split_array(cache, split, representation)
y = np.load(cache / f"y_{split}.npy")
fire_id = np.load(cache / f"fire_id_{split}.npy", allow_pickle=True).astype(str)
index = pd.read_parquet(cache / f"sample_index_{split}.parquet")
data[split] = {"X": X, "y": y, "fire_id": fire_id, "index": index}
data["metadata"] = load_json_if_exists(cache / "metadata.json")
data["feature_names"] = load_json_if_exists(cache / "feature_names.json").get("feature_names", [])
data["channel_names"] = load_json_if_exists(cache / "channel_names.json").get("channel_names", [])
data["relative_days"] = load_json_if_exists(cache / "relative_days.json").get("relative_days", [])
data["temporal_feature_names"] = load_json_if_exists(cache / "temporal_feature_names.json").get("feature_names", [])
data["static_feature_names"] = load_json_if_exists(cache / "static_feature_names.json").get("feature_names", [])
validate_cache(data, task)
return data
def validate_cache(data: dict[str, Any], task: str) -> None:
target_col = "ia_failure_label" if task == "ia_failure" else "log_containment_hours"
print("Pre-training cache validation")
for split in ["train", "val", "test"]:
X = data[split]["X"]
y = data[split]["y"]
fire_id = data[split]["fire_id"]
index = data[split]["index"].copy()
if isinstance(X, dict):
x_len = len(X["seq"])
if len(X["static"]) != x_len:
raise ValueError(f"{split}: X_seq and X_static lengths do not match.")
x_shape = f"X_seq={X['seq'].shape}, X_static={X['static'].shape}"
finite_ok = np.isfinite(X["seq"]).all() and np.isfinite(X["static"]).all()
else:
x_len = len(X)
x_shape = f"X={X.shape}"
finite_ok = finite_check_array(X)
if x_len != len(y) or x_len != len(fire_id) or x_len != len(index):
raise ValueError(f"{split}: X/y/fire_id/sample_index lengths do not match.")
for col in ["fire_id", "year", "split"]:
if col not in index.columns:
raise ValueError(f"{split}: sample_index missing required column {col}")
if target_col not in index.columns:
raise ValueError(f"{split}: sample_index missing target column {target_col}")
if not np.array_equal(index["fire_id"].astype(str).to_numpy(), fire_id):
raise ValueError(f"{split}: fire_id array order does not match sample_index.")
if task == "ia_failure":
values = set(np.unique(y).astype(int).tolist())
if not values <= {0, 1}:
raise ValueError(f"{split}: ia_failure y has invalid values: {values}")
else:
if not np.isfinite(y).all():
raise ValueError(f"{split}: containment_time y has non-finite values.")
if not finite_ok:
raise ValueError(f"{split}: X contains NaN or infinite values.")
if task == "ia_failure":
print(f" {split}: {x_shape}, N={len(y)}, positive_rate={float(np.mean(y)):.4f}")
else:
print(
f" {split}: {x_shape}, N={len(y)}, y_log_mean={float(np.mean(y)):.4f}, "
f"y_log_std={float(np.std(y)):.4f}"
)
def device_info(device_arg: str, gpu_id: int | None) -> dict[str, Any]:
info = {"device": "cpu", "gpu_name": None, "gpu_memory_total": None, "torch_cuda_available": False}
try:
import torch
cuda_available = torch.cuda.is_available()
info["torch_cuda_available"] = bool(cuda_available)
if device_arg == "cuda" and not cuda_available:
raise RuntimeError("CUDA requested but torch.cuda.is_available() is false.")
if device_arg == "auto":
device = "cuda" if cuda_available else "cpu"
else:
device = device_arg
if device == "cuda":
index = gpu_id if gpu_id is not None else 0
info["device"] = f"cuda:{index}"
info["gpu_name"] = torch.cuda.get_device_name(index)
info["gpu_memory_total"] = int(torch.cuda.get_device_properties(index).total_memory)
else:
info["device"] = "cpu"
except ImportError:
if device_arg == "cuda":
raise
return info
def expected_calibration_error(y_true: np.ndarray, y_score: np.ndarray, n_bins: int = 15) -> float:
y_true = np.asarray(y_true).astype(float)
y_score = np.asarray(y_score).astype(float)
edges = np.linspace(0.0, 1.0, n_bins + 1)
ece = 0.0
for i in range(n_bins):
lo, hi = edges[i], edges[i + 1]
mask = (y_score >= lo) & (y_score <= hi if i == n_bins - 1 else y_score < hi)
if not np.any(mask):
continue
confidence = float(np.mean(y_score[mask]))
accuracy = float(np.mean(y_true[mask]))
ece += float(np.mean(mask)) * abs(accuracy - confidence)
return ece
def precision_recall_at_k(y_true: np.ndarray, y_score: np.ndarray, percent: int) -> tuple[float, float]:
n = len(y_true)
k = max(1, int(math.ceil((percent / 100.0) * n)))
order = np.argsort(-y_score)[:k]
positives = float(np.sum(y_true == 1))
top_pos = float(np.sum(y_true[order] == 1))
precision = top_pos / k
recall = top_pos / positives if positives > 0 else float("nan")
return precision, recall
def safe_metric(fn, default: float = float("nan")) -> float:
try:
return float(fn())
except Exception:
return default
def classification_metrics(y_true: np.ndarray, y_score: np.ndarray, threshold: float) -> dict[str, float]:
y_true = np.asarray(y_true).astype(int)
y_score = np.clip(np.asarray(y_score).astype(float), 1e-7, 1.0 - 1e-7)
y_pred = (y_score >= threshold).astype(int)
metrics = {
"auprc": safe_metric(lambda: average_precision_score(y_true, y_score)),
"auroc": safe_metric(lambda: roc_auc_score(y_true, y_score)),
"f1": safe_metric(lambda: f1_score(y_true, y_pred, zero_division=0)),
"precision": safe_metric(lambda: precision_score(y_true, y_pred, zero_division=0)),
"recall": safe_metric(lambda: recall_score(y_true, y_pred, zero_division=0)),
"balanced_accuracy": safe_metric(lambda: balanced_accuracy_score(y_true, y_pred)),
"brier": safe_metric(lambda: brier_score_loss(y_true, y_score)),
"bce": safe_metric(lambda: log_loss(y_true, y_score, labels=[0, 1])),
"ece": expected_calibration_error(y_true, y_score),
}
for percent in [1, 5, 10]:
precision, recall = precision_recall_at_k(y_true, y_score, percent)
metrics[f"precision_at_{percent}"] = precision
metrics[f"recall_at_{percent}"] = recall
return metrics
def score_logit_diagnostics(y_score: np.ndarray, prefix: str) -> dict[str, float]:
score = np.clip(np.asarray(y_score).astype(float), 1e-7, 1.0 - 1e-7)
logit = safe_logit(score)
return {
f"{prefix}_y_score_mean": float(np.mean(score)),
f"{prefix}_y_score_std": float(np.std(score)),
f"{prefix}_y_score_min": float(np.min(score)),
f"{prefix}_y_score_max": float(np.max(score)),
f"{prefix}_y_logit_mean": float(np.mean(logit)),
f"{prefix}_y_logit_std": float(np.std(logit)),
f"{prefix}_y_logit_min": float(np.min(logit)),
f"{prefix}_y_logit_max": float(np.max(logit)),
}
def train_epoch_metrics(y_true: np.ndarray, y_score: np.ndarray) -> dict[str, float]:
threshold, _ = best_f1_threshold(y_true, y_score)
metrics = classification_metrics(y_true, y_score, threshold)
return {
"train_auprc": metrics["auprc"],
"train_auroc": metrics["auroc"],
"train_f1": metrics["f1"],
}
def subset_indices(y: np.ndarray, limit: int | None, seed: int) -> np.ndarray:
n = len(y)
if limit is None or limit >= n:
return np.arange(n)
if limit <= 0:
raise ValueError("Sample limits must be positive when provided.")
rng = np.random.default_rng(seed)
y = np.asarray(y)
if set(np.unique(y).astype(int).tolist()) <= {0, 1} and len(np.unique(y)) == 2:
pos = np.where(y == 1)[0]
neg = np.where(y == 0)[0]
n_pos = max(1, int(round(limit * len(pos) / n)))
n_pos = min(n_pos, len(pos), limit)
n_neg = min(limit - n_pos, len(neg))
chosen = np.concatenate([rng.choice(pos, size=n_pos, replace=False), rng.choice(neg, size=n_neg, replace=False)])
if len(chosen) < limit:
remaining = np.setdiff1d(np.arange(n), chosen, assume_unique=False)
chosen = np.concatenate([chosen, rng.choice(remaining, size=limit - len(chosen), replace=False)])
return np.sort(chosen)
return np.arange(limit)
def subset_split(split_data: dict[str, Any], indices: np.ndarray) -> dict[str, Any]:
X = split_data["X"]
if isinstance(X, dict):
X = {name: value[indices] for name, value in X.items()}
else:
X = X[indices]
return {
"X": X,
"y": split_data["y"][indices],
"fire_id": split_data["fire_id"][indices],
"index": split_data["index"].iloc[indices].reset_index(drop=True),
}
def apply_debug_sample_limits(data: dict[str, Any], args) -> dict[str, Any]:
limits = {"train": args.limit_train_samples, "val": args.limit_val_samples}
if limits["train"] is None and limits["val"] is None:
return data
new_data = data.copy()
for split, limit in limits.items():
if limit is not None:
idx = subset_indices(data[split]["y"], int(limit), args.seed)
new_data[split] = subset_split(data[split], idx)
print(f"Debug subset: {split} limited to {len(idx)} samples.")
return new_data
def compute_channel_standardization_stats(X: np.ndarray, out_dir: Path, chunk_size: int = 256) -> tuple[np.ndarray, np.ndarray]:
shape = X.shape
if len(shape) == 4:
channels = shape[1]
reduce_axes = (0, 2, 3)
count_per_sample = shape[2] * shape[3]
elif len(shape) == 5:
channels = shape[2]
reduce_axes = (0, 1, 3, 4)
count_per_sample = shape[1] * shape[3] * shape[4]
else:
raise ValueError(f"Channel standardization expects spatial or spatiotemporal X, got shape {shape}")
total = np.zeros(channels, dtype=np.float64)
total_sq = np.zeros(channels, dtype=np.float64)
count = 0
for start_idx in range(0, len(X), chunk_size):
arr = np.asarray(X[start_idx : start_idx + chunk_size], dtype=np.float32)
total += arr.sum(axis=reduce_axes, dtype=np.float64)
total_sq += np.square(arr, dtype=np.float32).sum(axis=reduce_axes, dtype=np.float64)
count += arr.shape[0] * count_per_sample
mean = total / max(1, count)
var = np.maximum(total_sq / max(1, count) - mean**2, 0.0)
std = np.sqrt(var)
std[std < 1e-6] = 1.0
np.savez(out_dir / "channel_standardization_stats.npz", mean=mean.astype(np.float32), std=std.astype(np.float32))
return mean.astype(np.float32), std.astype(np.float32)
def standardize_patch_batch(batch: np.ndarray, mean: np.ndarray | None, std: np.ndarray | None) -> np.ndarray:
arr = np.asarray(batch, dtype=np.float32)
if mean is None or std is None:
return arr
if arr.ndim == 4:
return (arr - mean[None, :, None, None]) / std[None, :, None, None]
if arr.ndim == 5:
return (arr - mean[None, None, :, None, None]) / std[None, None, :, None, None]
raise ValueError(f"Unexpected patch batch shape: {arr.shape}")
def best_f1_threshold(y_true: np.ndarray, y_score: np.ndarray) -> tuple[float, float]:
best_threshold = 0.5
best_f1 = -1.0
for threshold in np.arange(0.01, 1.0, 0.01):
pred = (y_score >= threshold).astype(int)
score = f1_score(y_true, pred, zero_division=0)
if score > best_f1:
best_f1 = float(score)
best_threshold = float(threshold)
return best_threshold, best_f1
def regression_metrics(y_true_log: np.ndarray, y_pred_log: np.ndarray, containment_hours_true: np.ndarray | None = None) -> dict[str, float]:
y_true_log = np.asarray(y_true_log).astype(float)
y_pred_log = np.asarray(y_pred_log).astype(float)
if containment_hours_true is None:
containment_hours_true = np.expm1(y_true_log)
containment_hours_pred = np.maximum(0.0, np.expm1(y_pred_log))
return {
"mae_hours": safe_metric(lambda: mean_absolute_error(containment_hours_true, containment_hours_pred)),
"rmse_hours": safe_metric(lambda: mean_squared_error(containment_hours_true, containment_hours_pred, squared=False)),
"median_ae_hours": safe_metric(lambda: median_absolute_error(containment_hours_true, containment_hours_pred)),
"log_mae": safe_metric(lambda: mean_absolute_error(y_true_log, y_pred_log)),
"log_rmse": safe_metric(lambda: mean_squared_error(y_true_log, y_pred_log, squared=False)),
"r2": safe_metric(lambda: r2_score(y_true_log, y_pred_log)),
"spearman": safe_metric(lambda: spearmanr(y_true_log, y_pred_log).correlation),
"pearson": safe_metric(lambda: pearsonr(y_true_log, y_pred_log)[0]),
}
def classification_predictions(index: pd.DataFrame, y_true: np.ndarray, y_score: np.ndarray, threshold: float, model_name: str, seed: int) -> pd.DataFrame:
score = np.clip(np.asarray(y_score).astype(float), 1e-7, 1.0 - 1e-7)
pred = (score >= threshold).astype(int)
return pd.DataFrame(
{
"fire_id": index["fire_id"].astype(str).to_numpy(),
"year": index["year"].to_numpy(),
"split": index["split"].to_numpy(),
"y_true": y_true.astype(int),
"y_score": score,
"y_logit": safe_logit(score),
"y_pred": pred,
"threshold": threshold,
"model_name": model_name,
"seed": seed,
}
)
def regression_predictions(index: pd.DataFrame, y_true_log: np.ndarray, y_pred_log: np.ndarray, model_name: str, seed: int) -> pd.DataFrame:
true_hours = index["containment_hours"].to_numpy(dtype=float) if "containment_hours" in index.columns else np.expm1(y_true_log)
pred_hours = np.maximum(0.0, np.expm1(y_pred_log))
return pd.DataFrame(
{
"fire_id": index["fire_id"].astype(str).to_numpy(),
"year": index["year"].to_numpy(),
"split": index["split"].to_numpy(),
"y_true_log": y_true_log,
"y_pred_log": y_pred_log,
"containment_hours_true": true_hours,
"containment_hours_pred": pred_hours,
"model_name": model_name,
"seed": seed,
}
)
def base_metrics_payload(args, model_name: str, cache: Path, out_dir: Path, data: dict[str, Any], runtime_seconds: float, device: dict[str, Any]) -> dict[str, Any]:
payload = {
"task": args.task,
"representation": args.representation,
"model_name": model_name,
"weather_days": args.weather_days,
"input_protocol": args.input_protocol,
"seed": args.seed,
"train_size": int(len(data["train"]["y"])),
"val_size": int(len(data["val"]["y"])),
"test_size": int(len(data["test"]["y"])),
"created_at": created_at(),
"runtime_seconds": float(runtime_seconds),
"device": device.get("device"),
"gpu_name": device.get("gpu_name"),
"gpu_memory_total": device.get("gpu_memory_total"),
"input_cache_dir": str(cache),
"output_dir": str(out_dir),
"sampling_strategy": args.sampling_strategy,
"grad_accum_steps": int(args.grad_accum_steps),
"effective_batch_size": int((args.batch_size or default_batch_size(args.representation)) * args.grad_accum_steps),
"standardize_channels": bool(args.standardize_channels),
"limit_train_samples": args.limit_train_samples,
"limit_val_samples": args.limit_val_samples,
"disable_pos_weight": bool(args.disable_pos_weight),
"pos_weight_scale": float(args.pos_weight_scale),
"loss_type": args.loss_type,
"label_smoothing": float(args.label_smoothing),
"focal_gamma": float(args.focal_gamma),
"lr_scheduler_type": args.lr_scheduler_type,
"warmup_epochs": int(args.warmup_epochs),
"min_lr_ratio": float(args.min_lr_ratio),
}
if args.task == "ia_failure":
for split in ["train", "val", "test"]:
y = data[split]["y"].astype(int)
payload[f"{split}_positive"] = int(np.sum(y == 1))
payload[f"{split}_positive_rate"] = float(np.mean(y))
return payload
def ia_pos_weight_settings(args, y_train: np.ndarray) -> tuple[float, float | None, str]:
"""Return raw/effective IA class weight settings without changing defaults."""
y = np.asarray(y_train).astype(int)
num_pos = int(np.sum(y == 1))
num_neg = int(np.sum(y == 0))
raw_pos_weight = float(num_neg / max(1, num_pos))
if args.disable_pos_weight:
return raw_pos_weight, None, "BCEWithLogitsLoss unweighted"
effective_pos_weight = float(raw_pos_weight * args.pos_weight_scale)
return raw_pos_weight, effective_pos_weight, "BCEWithLogitsLoss pos_weight"
def bce_with_optional_pos_weight(nn_module, args, y_train: np.ndarray, torch_device):
import torch
class SmoothedBCEWithLogitsLoss(nn_module.Module):
def __init__(self, pos_weight=None, smoothing: float = 0.0):
super().__init__()
self.register_buffer("pos_weight", pos_weight if pos_weight is not None else None)
self.smoothing = float(smoothing)
def forward(self, logits, targets):
targets = targets.float()
if self.smoothing > 0:
targets = targets * (1.0 - self.smoothing) + 0.5 * self.smoothing
return nn_module.functional.binary_cross_entropy_with_logits(
logits,
targets,
pos_weight=self.pos_weight,
)
class FocalWithLogitsLoss(nn_module.Module):
def __init__(self, pos_weight=None, smoothing: float = 0.0, gamma: float = 2.0):
super().__init__()
self.register_buffer("pos_weight", pos_weight if pos_weight is not None else None)
self.smoothing = float(smoothing)
self.gamma = float(gamma)
def forward(self, logits, targets):
targets = targets.float()
if self.smoothing > 0:
targets = targets * (1.0 - self.smoothing) + 0.5 * self.smoothing
bce = nn_module.functional.binary_cross_entropy_with_logits(
logits,
targets,
pos_weight=self.pos_weight,
reduction="none",
)
prob = torch.sigmoid(logits)
pt = prob * targets + (1.0 - prob) * (1.0 - targets)
focal = (1.0 - pt).clamp(min=1e-6).pow(self.gamma) * bce
return focal.mean()
raw_pos_weight, effective_pos_weight, strategy = ia_pos_weight_settings(args, y_train)
pos_weight_tensor = None
if effective_pos_weight is None:
strategy = f"{args.loss_type} unweighted"
else:
pos_weight_tensor = torch.tensor(effective_pos_weight, dtype=torch.float32, device=torch_device)
strategy = f"{args.loss_type} pos_weight"
if args.loss_type == "bce":
criterion = SmoothedBCEWithLogitsLoss(pos_weight=pos_weight_tensor, smoothing=args.label_smoothing)
elif args.loss_type == "focal":
criterion = FocalWithLogitsLoss(pos_weight=pos_weight_tensor, smoothing=args.label_smoothing, gamma=args.focal_gamma)
else:
raise ValueError(f"Unsupported loss_type={args.loss_type}")
criterion_unweighted = nn_module.BCEWithLogitsLoss()
return criterion, criterion_unweighted, raw_pos_weight, effective_pos_weight, strategy
def build_neural_scheduler(optimizer, args, task: str):
scheduler_type = args.lr_scheduler_type
if args.use_lr_scheduler and scheduler_type == "none":
scheduler_type = "plateau"
if scheduler_type == "none":
return None, "none"
if scheduler_type == "plateau":
mode = "max" if task == "ia_failure" else "min"
return torch_scheduler_reduce_on_plateau(optimizer, mode=mode), "plateau"
if scheduler_type == "cosine":
import math
import torch
total_epochs = max(1, int(args.max_epochs))
warmup_epochs = max(0, int(args.warmup_epochs))
min_lr_ratio = max(0.0, min(1.0, float(args.min_lr_ratio)))
def lr_lambda(epoch_idx: int):
epoch_num = epoch_idx + 1
if warmup_epochs > 0 and epoch_num <= warmup_epochs:
return max(min_lr_ratio, epoch_num / warmup_epochs)
decay_steps = max(1, total_epochs - warmup_epochs)
progress = min(1.0, max(0.0, (epoch_num - warmup_epochs) / decay_steps))
cosine = 0.5 * (1.0 + math.cos(math.pi * progress))
return min_lr_ratio + (1.0 - min_lr_ratio) * cosine
return torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lr_lambda), "cosine"
raise ValueError(f"Unsupported lr_scheduler_type={args.lr_scheduler_type}")
def torch_scheduler_reduce_on_plateau(optimizer, mode: str):
import torch
return torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode=mode, factor=0.5, patience=5)
def step_neural_scheduler(scheduler, scheduler_type: str, monitor: float | None = None) -> None:
if scheduler is None:
return
if scheduler_type == "plateau":
scheduler.step(monitor)
else:
scheduler.step()
def save_common_artifacts(out_dir: Path, cache: Path) -> None:
for name in ["feature_names.json", "channel_names.json", "relative_days.json", "temporal_feature_names.json", "static_feature_names.json"]:
src = cache / name
if src.exists():
shutil.copy2(src, out_dir / name)
def _plot_lines(
history_df: pd.DataFrame,
output_path: Path,
title: str,
y_label: str,
columns: list[tuple[str, str]],
best_epoch: int | None = None,
) -> None:
present = [(col, label) for col, label in columns if col in history_df.columns]
if not present or history_df.empty:
return
epoch = history_df["epoch"] if "epoch" in history_df.columns else np.arange(1, len(history_df) + 1)
plt.figure(figsize=(8, 5))
for col, label in present:
plt.plot(epoch, history_df[col], marker="o", linewidth=1.8, markersize=3, label=label)
if best_epoch is not None and best_epoch > 0:
plt.axvline(best_epoch, color="black", linestyle="--", linewidth=1.2, alpha=0.7, label=f"best epoch {best_epoch}")
plt.title(title)
plt.xlabel("epoch")
plt.ylabel(y_label)
plt.grid(True, alpha=0.25)
plt.legend()
plt.tight_layout()
plt.savefig(output_path, dpi=160)
plt.close()
def plot_training_curves(history_df: pd.DataFrame, output_dir: Path, task: str, best_epoch: int | None = None) -> None:
"""Save training-curve PNGs when metric columns are available."""
if history_df is None or history_df.empty:
return
output_dir = Path(output_dir)
weighted_loss = False
if task == "ia_failure":
if "pos_weight_effective" in history_df.columns:
weights = pd.to_numeric(history_df["pos_weight_effective"], errors="coerce").dropna()
weighted_loss = bool(len(weights) and np.any(np.abs(weights.to_numpy(dtype=float) - 1.0) > 1e-9))
else:
weighted_loss = "val_bce_unweighted" in history_df.columns or "train_bce_unweighted" in history_df.columns
loss_columns = [
("train_loss", "train_loss (weighted objective)" if weighted_loss else "train_loss"),
("val_loss", "val_loss (weighted objective)" if weighted_loss else "val_loss"),
]
_plot_lines(
history_df,
output_dir / "loss_curve.png",
"Training and Validation Loss",
"loss",
loss_columns,
best_epoch=best_epoch,
)
_plot_lines(
history_df,
output_dir / "bce_unweighted_curve.png",
"Unweighted BCE / NLL",
"BCE",
[("train_bce_unweighted", "train_BCE_unweighted"), ("val_bce_unweighted", "val_BCE_unweighted")],
best_epoch=best_epoch,
)
if task == "ia_failure":
_plot_lines(
history_df,
output_dir / "val_auprc_curve.png",
"Validation AUPRC",
"AUPRC",
[("val_auprc", "val_AUPRC")],
best_epoch=best_epoch,
)
_plot_lines(
history_df,
output_dir / "val_auroc_curve.png",
"Validation AUROC",
"AUROC",
[("val_auroc", "val_AUROC")],
best_epoch=best_epoch,
)
_plot_lines(
history_df,
output_dir / "metric_curve.png",
"Validation Metrics",
"metric value",
[("val_auprc", "val_AUPRC"), ("val_auroc", "val_AUROC"), ("val_f1", "val_F1")],
best_epoch=best_epoch,
)
elif task == "containment_time":
_plot_lines(
history_df,
output_dir / "val_mae_curve.png",
"Validation MAE",
"MAE hours",
[("val_mae_hours", "val_MAE_hours")],
best_epoch=best_epoch,
)
_plot_lines(
history_df,
output_dir / "val_rmse_curve.png",
"Validation RMSE",
"RMSE hours",
[("val_rmse_hours", "val_RMSE_hours")],
best_epoch=best_epoch,
)
_plot_lines(
history_df,
output_dir / "metric_curve.png",
"Validation Metrics",
"metric value",
[
("val_mae_hours", "val_MAE_hours"),
("val_rmse_hours", "val_RMSE_hours"),
("val_log_mae", "val_log_MAE"),
("val_log_rmse", "val_log_RMSE"),
],
best_epoch=best_epoch,
)
def train_logistic_or_ridge(args, data: dict[str, Any], out_dir: Path, cache: Path, device: dict[str, Any]) -> None:
start = time.time()
effective_name = output_model_name(args.task, "logistic_regression")
X_train, y_train = data["train"]["X"], data["train"]["y"]
X_val, y_val = data["val"]["X"], data["val"]["y"]
X_test, y_test = data["test"]["X"], data["test"]["y"]
if args.task == "ia_failure":
try:
model = LogisticRegression(
class_weight="balanced",
max_iter=5000,
solver="lbfgs",
C=1.0,
random_state=args.seed,
n_jobs=-1,
verbose=0,
)
model.fit(X_train, y_train)
except Exception as exc:
print(f"Warning: LogisticRegression solver='lbfgs' failed ({exc}); retrying solver='saga'.")
model = LogisticRegression(
class_weight="balanced",
max_iter=5000,
solver="saga",
C=1.0,
random_state=args.seed,
n_jobs=-1,
)
model.fit(X_train, y_train)
val_score = model.predict_proba(X_val)[:, 1]
test_score = model.predict_proba(X_test)[:, 1]
threshold, _ = best_f1_threshold(y_val, val_score)
val_metrics = classification_metrics(y_val, val_score, threshold)
test_metrics = classification_metrics(y_test, test_score, threshold)
history = pd.DataFrame([{f"val_{k}": v for k, v in val_metrics.items()} | {"threshold": threshold}])
pred_val = classification_predictions(data["val"]["index"], y_val, val_score, threshold, effective_name, args.seed)
pred_test = classification_predictions(data["test"]["index"], y_test, test_score, threshold, effective_name, args.seed)
imbalance = {
"class_imbalance_strategy": 'LogisticRegression class_weight="balanced"',
"pos_weight_or_scale_pos_weight": float(np.sum(y_train == 0) / max(1, np.sum(y_train == 1))),
"best_threshold_from_val": threshold,
}
imbalance.update(score_logit_diagnostics(val_score, "val"))
imbalance.update(score_logit_diagnostics(test_score, "test"))
else:
model = Ridge(alpha=1.0, random_state=args.seed)
model.fit(X_train, y_train)
val_pred = model.predict(X_val)
test_pred = model.predict(X_test)
val_metrics = regression_metrics(y_val, val_pred, data["val"]["index"].get("containment_hours", pd.Series(np.expm1(y_val))).to_numpy(dtype=float))
test_metrics = regression_metrics(y_test, test_pred, data["test"]["index"].get("containment_hours", pd.Series(np.expm1(y_test))).to_numpy(dtype=float))
history = pd.DataFrame([{f"val_{k}": v for k, v in val_metrics.items()}])
pred_val = regression_predictions(data["val"]["index"], y_val, val_pred, effective_name, args.seed)
pred_test = regression_predictions(data["test"]["index"], y_test, test_pred, effective_name, args.seed)
imbalance = {"class_imbalance_strategy": None, "pos_weight_or_scale_pos_weight": None}
with (out_dir / "model.pkl").open("wb") as file:
pickle.dump(model, file)
history.to_csv(out_dir / "history.csv", index=False)
pred_val.to_parquet(out_dir / "predictions_val.parquet", index=False)
pred_test.to_parquet(out_dir / "predictions_test.parquet", index=False)
runtime = time.time() - start
metrics = base_metrics_payload(args, effective_name, cache, out_dir, data, runtime, device)
metrics.update(imbalance)
metrics.update({f"val_{k}": v for k, v in val_metrics.items()})
metrics.update({f"test_{k}": v for k, v in test_metrics.items()})
write_json(out_dir / "metrics.json", metrics)
def xgb_predict_scores(model: Any, X: np.ndarray, task: str) -> np.ndarray:
if task == "ia_failure":
return model.predict_proba(X)[:, 1]
return model.predict(X)
def build_xgboost_model(args, device: dict[str, Any], use_cuda: bool, scale_pos_weight: float | None):
from xgboost import XGBClassifier, XGBRegressor
common = {
"n_estimators": 1000,
"learning_rate": 0.03,
"max_depth": 4,
"subsample": 0.8,
"colsample_bytree": 0.8,
"tree_method": "hist",
"device": "cuda" if use_cuda else "cpu",
"random_state": args.seed,
"n_jobs": -1,
}
if args.task == "ia_failure":
kwargs = {**common, "eval_metric": "aucpr"}
if scale_pos_weight is not None:
kwargs["scale_pos_weight"] = scale_pos_weight
return XGBClassifier(**kwargs)
return XGBRegressor(
**common,
objective="reg:squarederror",
eval_metric="rmse",
)
def fit_xgboost_with_fallback(model, X_train, y_train, X_val, y_val):
try:
model.fit(X_train, y_train, eval_set=[(X_val, y_val)], verbose=False, early_stopping_rounds=50)
return model, "early_stopping_rounds=50"
except TypeError as exc:
print(f"Warning: XGBoost early stopping API not supported ({exc}); retrying without early stopping.")
model.fit(X_train, y_train, eval_set=[(X_val, y_val)], verbose=False)
return model, "no_early_stopping_api"
def train_xgboost(args, data: dict[str, Any], out_dir: Path, cache: Path, device: dict[str, Any]) -> None:
start = time.time()
try:
import xgboost # noqa: F401
except ImportError as exc:
raise ImportError("xgboost is required for --model xgboost.") from exc
X_train, y_train = data["train"]["X"], data["train"]["y"]
X_val, y_val = data["val"]["X"], data["val"]["y"]
X_test, y_test = data["test"]["X"], data["test"]["y"]
scale_pos_weight = None
raw_scale_pos_weight = None
imbalance_strategy = None
if args.task == "ia_failure":
raw_scale_pos_weight, scale_pos_weight, imbalance_strategy = ia_pos_weight_settings(args, y_train)
use_cuda = str(device.get("device", "cpu")).startswith("cuda")
model = build_xgboost_model(args, device, use_cuda=use_cuda, scale_pos_weight=scale_pos_weight)
fit_note = ""
try:
model, fit_note = fit_xgboost_with_fallback(model, X_train, y_train, X_val, y_val)
except Exception as exc:
if use_cuda:
print(f"Warning: XGBoost CUDA fit failed ({exc}); retrying on CPU.")
model = build_xgboost_model(args, device, use_cuda=False, scale_pos_weight=scale_pos_weight)
model, fit_note = fit_xgboost_with_fallback(model, X_train, y_train, X_val, y_val)
else:
raise
if args.task == "ia_failure":
val_score = xgb_predict_scores(model, X_val, args.task)
test_score = xgb_predict_scores(model, X_test, args.task)
threshold, _ = best_f1_threshold(y_val, val_score)
val_metrics = classification_metrics(y_val, val_score, threshold)
test_metrics = classification_metrics(y_test, test_score, threshold)
pred_val = classification_predictions(data["val"]["index"], y_val, val_score, threshold, "xgboost", args.seed)
pred_test = classification_predictions(data["test"]["index"], y_test, test_score, threshold, "xgboost", args.seed)