chore: rebuild space with residual-quantile metrics
Browse files- bundle/requirements.txt +8 -8
- bundle/src/evaluate.py +292 -3
- bundle/src/train.py +41 -0
bundle/requirements.txt
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
-
torch==2.9.1
|
| 2 |
-
torchvision==0.24.1
|
| 3 |
-
numpy>=1.24
|
| 4 |
-
pandas>=2.0
|
| 5 |
-
pyyaml>=6.0
|
| 6 |
-
pillow>=10.0
|
| 7 |
-
scikit-learn>=1.3
|
| 8 |
-
spaces
|
|
|
|
| 1 |
+
torch==2.9.1
|
| 2 |
+
torchvision==0.24.1
|
| 3 |
+
numpy>=1.24
|
| 4 |
+
pandas>=2.0
|
| 5 |
+
pyyaml>=6.0
|
| 6 |
+
pillow>=10.0
|
| 7 |
+
scikit-learn>=1.3
|
| 8 |
+
spaces
|
bundle/src/evaluate.py
CHANGED
|
@@ -663,6 +663,277 @@ def residual_quantile_coverage(
|
|
| 663 |
return report
|
| 664 |
|
| 665 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 666 |
def _positions(frame: pd.DataFrame, split_name: str) -> np.ndarray:
|
| 667 |
return np.flatnonzero(frame["split"].astype(str).to_numpy() == split_name)
|
| 668 |
|
|
@@ -1162,11 +1433,17 @@ def evaluate(
|
|
| 1162 |
def main(argv: list[str] | None = None) -> dict:
|
| 1163 |
"""CLI entry point. Prints paths and the honesty banner, not a score to quote."""
|
| 1164 |
parser = argparse.ArgumentParser(description=__doc__)
|
| 1165 |
-
parser.add_argument(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1166 |
parser.add_argument(
|
| 1167 |
"--frame",
|
| 1168 |
type=Path,
|
| 1169 |
-
|
| 1170 |
help="CSV with storms, winds, y_pred, and features",
|
| 1171 |
)
|
| 1172 |
parser.add_argument(
|
|
@@ -1175,7 +1452,7 @@ def main(argv: list[str] | None = None) -> dict:
|
|
| 1175 |
default=None,
|
| 1176 |
help="Path used to resolve image_path. Defaults to --frame.",
|
| 1177 |
)
|
| 1178 |
-
parser.add_argument("--features", nargs="
|
| 1179 |
parser.add_argument("--prediction-column", default="y_pred")
|
| 1180 |
parser.add_argument("--out", type=Path, default=None)
|
| 1181 |
parser.add_argument("--levels", nargs="+", type=float, default=list(_LEVELS))
|
|
@@ -1192,6 +1469,18 @@ def main(argv: list[str] | None = None) -> dict:
|
|
| 1192 |
default="test",
|
| 1193 |
)
|
| 1194 |
args = parser.parse_args(argv)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1195 |
config = load_config(args.config)
|
| 1196 |
table = pd.read_csv(args.frame)
|
| 1197 |
samples = None if args.samples is None else np.load(args.samples)
|
|
|
|
| 663 |
return report
|
| 664 |
|
| 665 |
|
| 666 |
+
def compute_residual_quantiles(
|
| 667 |
+
y_true_val: np.ndarray,
|
| 668 |
+
y_pred_val: np.ndarray,
|
| 669 |
+
y_true_test: np.ndarray,
|
| 670 |
+
y_pred_test: np.ndarray,
|
| 671 |
+
val_storms: Sequence[str],
|
| 672 |
+
test_storms: Sequence[str],
|
| 673 |
+
*,
|
| 674 |
+
levels: Sequence[float] = _LEVELS,
|
| 675 |
+
tolerance: float = _TOLERANCE,
|
| 676 |
+
is_synthetic: bool = False,
|
| 677 |
+
) -> dict:
|
| 678 |
+
"""Compute held-out residual-quantile intervals matching ConfidenceScore schema."""
|
| 679 |
+
val_clean = [str(s).strip() for s in val_storms if str(s).strip()]
|
| 680 |
+
test_clean = [str(s).strip() for s in test_storms if str(s).strip()]
|
| 681 |
+
if not val_clean:
|
| 682 |
+
raise ValueError("val_storms must contain at least one storm id")
|
| 683 |
+
if not test_clean:
|
| 684 |
+
raise ValueError("test_storms must contain at least one storm id")
|
| 685 |
+
|
| 686 |
+
levels_report = residual_quantile_coverage(
|
| 687 |
+
y_true_val=y_true_val,
|
| 688 |
+
y_pred_val=y_pred_val,
|
| 689 |
+
y_true_test=y_true_test,
|
| 690 |
+
y_pred_test=y_pred_test,
|
| 691 |
+
levels=levels,
|
| 692 |
+
tolerance=tolerance,
|
| 693 |
+
)
|
| 694 |
+
return {
|
| 695 |
+
"fit_split": "val",
|
| 696 |
+
"eval_split": "test",
|
| 697 |
+
"val_storms": sorted(set(val_clean)),
|
| 698 |
+
"test_storms": sorted(set(test_clean)),
|
| 699 |
+
"synthetic": bool(is_synthetic),
|
| 700 |
+
"levels": levels_report,
|
| 701 |
+
}
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
def merge_residual_quantiles(
|
| 705 |
+
metrics: dict,
|
| 706 |
+
residual_block: dict,
|
| 707 |
+
*,
|
| 708 |
+
tolerance: float = _TOLERANCE,
|
| 709 |
+
levels: Sequence[float] = _LEVELS,
|
| 710 |
+
) -> dict:
|
| 711 |
+
"""Merge residual quantile block into a run's metrics record."""
|
| 712 |
+
result = dict(metrics)
|
| 713 |
+
uncertainty = dict(result.get("uncertainty") or {})
|
| 714 |
+
uncertainty["coverage_tolerance"] = float(tolerance)
|
| 715 |
+
uncertainty["nominal_levels"] = [float(lvl) for lvl in levels]
|
| 716 |
+
uncertainty["residual_quantile"] = residual_block
|
| 717 |
+
result["uncertainty"] = uncertainty
|
| 718 |
+
result["residual_quantile"] = residual_block
|
| 719 |
+
if "synthetic" not in result or result.get("synthetic") is None:
|
| 720 |
+
result["synthetic"] = bool(residual_block.get("synthetic", False))
|
| 721 |
+
return result
|
| 722 |
+
|
| 723 |
+
|
| 724 |
+
def evaluate_run_directory(
|
| 725 |
+
run_dir: str | Path,
|
| 726 |
+
*,
|
| 727 |
+
tolerance: float = _TOLERANCE,
|
| 728 |
+
levels: Sequence[float] = _LEVELS,
|
| 729 |
+
) -> dict:
|
| 730 |
+
"""Evaluate an existing run directory without retraining.
|
| 731 |
+
|
| 732 |
+
Computes held-out residual-quantile intervals (fit on val storms,
|
| 733 |
+
evaluated on test storms) and merges the resulting block into metrics.json.
|
| 734 |
+
Exports predictions.npz if not already present.
|
| 735 |
+
"""
|
| 736 |
+
run_path = Path(run_dir)
|
| 737 |
+
if not run_path.is_dir():
|
| 738 |
+
raise FileNotFoundError(f"Run directory not found: {run_path}")
|
| 739 |
+
|
| 740 |
+
metrics_file = run_path / "metrics.json"
|
| 741 |
+
metrics: dict = {}
|
| 742 |
+
if metrics_file.is_file():
|
| 743 |
+
try:
|
| 744 |
+
metrics = json.loads(metrics_file.read_text(encoding="utf-8"))
|
| 745 |
+
except Exception:
|
| 746 |
+
metrics = {}
|
| 747 |
+
|
| 748 |
+
is_synth = metrics.get("is_synthetic", metrics.get("synthetic", False))
|
| 749 |
+
if isinstance(is_synth, str):
|
| 750 |
+
is_synth = is_synth.strip().lower() in ("true", "1", "yes")
|
| 751 |
+
else:
|
| 752 |
+
is_synth = bool(is_synth)
|
| 753 |
+
|
| 754 |
+
npz_candidates = [
|
| 755 |
+
run_path / "predictions.npz",
|
| 756 |
+
run_path / "calibration.npz",
|
| 757 |
+
run_path / "test_predictions.npz",
|
| 758 |
+
]
|
| 759 |
+
npz_file = next((p for p in npz_candidates if p.is_file()), None)
|
| 760 |
+
|
| 761 |
+
y_true_test = None
|
| 762 |
+
y_pred_test = None
|
| 763 |
+
mc_samples_test = None
|
| 764 |
+
y_true_val = None
|
| 765 |
+
y_pred_val = None
|
| 766 |
+
mc_samples_val = None
|
| 767 |
+
val_storms = []
|
| 768 |
+
test_storms = []
|
| 769 |
+
|
| 770 |
+
manifest_file = run_path / "split_manifest.csv"
|
| 771 |
+
manifest_df = None
|
| 772 |
+
if manifest_file.is_file():
|
| 773 |
+
manifest_df = pd.read_csv(manifest_file)
|
| 774 |
+
if "storm_id" in manifest_df.columns and "split" in manifest_df.columns:
|
| 775 |
+
val_storms = sorted(manifest_df.loc[manifest_df["split"] == "val", "storm_id"].astype(str).unique())
|
| 776 |
+
test_storms = sorted(manifest_df.loc[manifest_df["split"] == "test", "storm_id"].astype(str).unique())
|
| 777 |
+
|
| 778 |
+
if not val_storms and isinstance(metrics.get("split_storm_ids"), dict):
|
| 779 |
+
val_storms = sorted(str(s) for s in metrics["split_storm_ids"].get("val", []))
|
| 780 |
+
if not test_storms and isinstance(metrics.get("split_storm_ids"), dict):
|
| 781 |
+
test_storms = sorted(str(s) for s in metrics["split_storm_ids"].get("test", []))
|
| 782 |
+
|
| 783 |
+
if npz_file is not None:
|
| 784 |
+
data = dict(np.load(str(npz_file), allow_pickle=True))
|
| 785 |
+
y_true_test = data.get("y_true_test", data.get("y_test", data.get("y_true")))
|
| 786 |
+
if y_true_test is not None:
|
| 787 |
+
y_true_test = np.asarray(y_true_test, dtype=np.float64).ravel()
|
| 788 |
+
|
| 789 |
+
y_pred_test = data.get("y_pred_test", data.get("y_pred"))
|
| 790 |
+
mc_test = data.get("mc_samples_test", data.get("mc_samples"))
|
| 791 |
+
if mc_test is not None:
|
| 792 |
+
mc_test = np.asarray(mc_test, dtype=np.float64)
|
| 793 |
+
if mc_test.ndim == 1 and y_true_test is not None:
|
| 794 |
+
mc_test = mc_test.reshape(1, -1)
|
| 795 |
+
elif y_true_test is not None and mc_test.ndim > 1 and mc_test.shape[1] != y_true_test.size and mc_test.shape[0] == y_true_test.size:
|
| 796 |
+
mc_test = mc_test.T
|
| 797 |
+
mc_samples_test = mc_test
|
| 798 |
+
if y_pred_test is None and mc_test.ndim > 1:
|
| 799 |
+
y_pred_test = np.mean(mc_test, axis=0)
|
| 800 |
+
|
| 801 |
+
if y_pred_test is not None:
|
| 802 |
+
y_pred_test = np.asarray(y_pred_test, dtype=np.float64).ravel()
|
| 803 |
+
|
| 804 |
+
y_true_val = data.get("y_true_val", data.get("y_val"))
|
| 805 |
+
if y_true_val is not None:
|
| 806 |
+
y_true_val = np.asarray(y_true_val, dtype=np.float64).ravel()
|
| 807 |
+
|
| 808 |
+
y_pred_val = data.get("y_pred_val")
|
| 809 |
+
mc_val = data.get("mc_samples_val")
|
| 810 |
+
if mc_val is not None:
|
| 811 |
+
mc_val = np.asarray(mc_val, dtype=np.float64)
|
| 812 |
+
if mc_val.ndim == 1 and y_true_val is not None:
|
| 813 |
+
mc_val = mc_val.reshape(1, -1)
|
| 814 |
+
elif y_true_val is not None and mc_val.ndim > 1 and mc_val.shape[1] != y_true_val.size and mc_val.shape[0] == y_true_val.size:
|
| 815 |
+
mc_val = mc_val.T
|
| 816 |
+
mc_samples_val = mc_val
|
| 817 |
+
if y_pred_val is None and mc_val.ndim > 1:
|
| 818 |
+
y_pred_val = np.mean(mc_val, axis=0)
|
| 819 |
+
|
| 820 |
+
if y_pred_val is not None:
|
| 821 |
+
y_pred_val = np.asarray(y_pred_val, dtype=np.float64).ravel()
|
| 822 |
+
|
| 823 |
+
if y_true_test is None or y_pred_test is None or y_true_val is None or y_pred_val is None:
|
| 824 |
+
if manifest_df is not None:
|
| 825 |
+
pred_col = next((c for c in ("y_pred", "pred", "predicted_wind_kt") if c in manifest_df.columns), None)
|
| 826 |
+
wind_col = next((c for c in ("wind_speed_kt", "target", "wind_kt", "wind_kt_3min") if c in manifest_df.columns), None)
|
| 827 |
+
if pred_col and wind_col:
|
| 828 |
+
v_mask = manifest_df["split"].astype(str) == "val"
|
| 829 |
+
t_mask = manifest_df["split"].astype(str) == "test"
|
| 830 |
+
y_true_val = manifest_df.loc[v_mask, wind_col].to_numpy(dtype=np.float64)
|
| 831 |
+
y_pred_val = manifest_df.loc[v_mask, pred_col].to_numpy(dtype=np.float64)
|
| 832 |
+
y_true_test = manifest_df.loc[t_mask, wind_col].to_numpy(dtype=np.float64)
|
| 833 |
+
y_pred_test = manifest_df.loc[t_mask, pred_col].to_numpy(dtype=np.float64)
|
| 834 |
+
|
| 835 |
+
if y_true_test is None or y_pred_test is None or y_true_val is None or y_pred_val is None:
|
| 836 |
+
ckpt_name = metrics.get("checkpoint_name", "checkpoint.pt")
|
| 837 |
+
ckpt_path = run_path / ckpt_name
|
| 838 |
+
if not ckpt_path.is_file():
|
| 839 |
+
candidates = list(run_path.glob("*.pt")) + list(run_path.glob("*.joblib"))
|
| 840 |
+
if candidates:
|
| 841 |
+
ckpt_path = candidates[0]
|
| 842 |
+
if not ckpt_path.is_file():
|
| 843 |
+
raise FileNotFoundError(
|
| 844 |
+
f"Neither predictions (.npz) nor checkpoint (.pt) found in {run_path}"
|
| 845 |
+
)
|
| 846 |
+
if manifest_df is None:
|
| 847 |
+
raise FileNotFoundError(f"split_manifest.csv required for checkpoint inference in {run_path}")
|
| 848 |
+
|
| 849 |
+
import yaml
|
| 850 |
+
from src.train import (
|
| 851 |
+
PathFrames,
|
| 852 |
+
_collect_predictions,
|
| 853 |
+
_path_records,
|
| 854 |
+
_torch,
|
| 855 |
+
build_loader,
|
| 856 |
+
build_net,
|
| 857 |
+
execution_policy,
|
| 858 |
+
training_wind_column,
|
| 859 |
+
)
|
| 860 |
+
|
| 861 |
+
torch = _torch()
|
| 862 |
+
cfg_file = run_path / "resolved_config.yaml"
|
| 863 |
+
if not cfg_file.is_file():
|
| 864 |
+
cfg_file = Path("config/config.yaml")
|
| 865 |
+
resolved = yaml.safe_load(cfg_file.read_text(encoding="utf-8")) if cfg_file.is_file() else {}
|
| 866 |
+
|
| 867 |
+
payload = torch.load(ckpt_path, map_location="cpu", weights_only=False)
|
| 868 |
+
model = build_net(resolved, size_head=payload.get("size_head", False))
|
| 869 |
+
model.load_state_dict(payload["state_dict"])
|
| 870 |
+
model.eval()
|
| 871 |
+
|
| 872 |
+
wind_column = payload.get("label_column") or training_wind_column(resolved)
|
| 873 |
+
image_size = int(payload.get("image_size", (resolved.get("data") or {}).get("image_size", 128)))
|
| 874 |
+
norm_mean = float(payload.get("norm_mean", 0.0))
|
| 875 |
+
norm_std = float(payload.get("norm_std", 1.0))
|
| 876 |
+
max_missing = float(payload.get("max_missing_fraction", 0.3))
|
| 877 |
+
known = list(payload.get("class_names") or (resolved.get("data") or {}).get("imd5_names", []))
|
| 878 |
+
|
| 879 |
+
val_records = _path_records(manifest_df, manifest_file, "val", wind_column, None)
|
| 880 |
+
test_records = _path_records(manifest_df, manifest_file, "test", wind_column, None)
|
| 881 |
+
val_loader = build_loader(
|
| 882 |
+
PathFrames(val_records, image_size, norm_mean, norm_std, max_missing, known),
|
| 883 |
+
batch_size=int((resolved.get("train") or {}).get("batch_size", 32)),
|
| 884 |
+
shuffle=False,
|
| 885 |
+
num_workers=0,
|
| 886 |
+
)
|
| 887 |
+
test_loader = build_loader(
|
| 888 |
+
PathFrames(test_records, image_size, norm_mean, norm_std, max_missing, known),
|
| 889 |
+
batch_size=int((resolved.get("train") or {}).get("batch_size", 32)),
|
| 890 |
+
shuffle=False,
|
| 891 |
+
num_workers=0,
|
| 892 |
+
)
|
| 893 |
+
policy = execution_policy(resolved, torch.device("cpu"))
|
| 894 |
+
val_truth, val_pred = _collect_predictions(model, val_loader, torch.device("cpu"), policy)
|
| 895 |
+
test_truth, test_pred = _collect_predictions(model, test_loader, torch.device("cpu"), policy)
|
| 896 |
+
|
| 897 |
+
y_true_val = val_truth
|
| 898 |
+
y_pred_val = val_pred
|
| 899 |
+
y_true_test = test_truth
|
| 900 |
+
y_pred_test = test_pred
|
| 901 |
+
|
| 902 |
+
out_npz = run_path / "predictions.npz"
|
| 903 |
+
if not out_npz.is_file() and y_true_test is not None and y_pred_test is not None:
|
| 904 |
+
np.savez(
|
| 905 |
+
out_npz,
|
| 906 |
+
y_true_test=y_true_test,
|
| 907 |
+
y_pred_test=y_pred_test,
|
| 908 |
+
mc_samples_test=mc_samples_test if mc_samples_test is not None else y_pred_test[None, :],
|
| 909 |
+
y_true_val=y_true_val,
|
| 910 |
+
y_pred_val=y_pred_val,
|
| 911 |
+
mc_samples_val=mc_samples_val if mc_samples_val is not None else y_pred_val[None, :],
|
| 912 |
+
)
|
| 913 |
+
|
| 914 |
+
if not val_storms:
|
| 915 |
+
val_storms = ["val_storm"]
|
| 916 |
+
if not test_storms:
|
| 917 |
+
test_storms = ["test_storm"]
|
| 918 |
+
|
| 919 |
+
residual_block = compute_residual_quantiles(
|
| 920 |
+
y_true_val=y_true_val,
|
| 921 |
+
y_pred_val=y_pred_val,
|
| 922 |
+
y_true_test=y_true_test,
|
| 923 |
+
y_pred_test=y_pred_test,
|
| 924 |
+
val_storms=val_storms,
|
| 925 |
+
test_storms=test_storms,
|
| 926 |
+
levels=levels,
|
| 927 |
+
tolerance=tolerance,
|
| 928 |
+
is_synthetic=is_synth,
|
| 929 |
+
)
|
| 930 |
+
|
| 931 |
+
merged = merge_residual_quantiles(metrics, residual_block, tolerance=tolerance, levels=levels)
|
| 932 |
+
merged["synthetic"] = is_synth
|
| 933 |
+
metrics_file.write_text(json.dumps(merged, indent=2) + "\n", encoding="utf-8")
|
| 934 |
+
return merged
|
| 935 |
+
|
| 936 |
+
|
| 937 |
def _positions(frame: pd.DataFrame, split_name: str) -> np.ndarray:
|
| 938 |
return np.flatnonzero(frame["split"].astype(str).to_numpy() == split_name)
|
| 939 |
|
|
|
|
| 1433 |
def main(argv: list[str] | None = None) -> dict:
|
| 1434 |
"""CLI entry point. Prints paths and the honesty banner, not a score to quote."""
|
| 1435 |
parser = argparse.ArgumentParser(description=__doc__)
|
| 1436 |
+
parser.add_argument(
|
| 1437 |
+
"--run-dir",
|
| 1438 |
+
type=Path,
|
| 1439 |
+
default=None,
|
| 1440 |
+
help="Path to an existing run directory to evaluate and compute held-out residual quantiles",
|
| 1441 |
+
)
|
| 1442 |
+
parser.add_argument("--config", type=Path, default=None)
|
| 1443 |
parser.add_argument(
|
| 1444 |
"--frame",
|
| 1445 |
type=Path,
|
| 1446 |
+
default=None,
|
| 1447 |
help="CSV with storms, winds, y_pred, and features",
|
| 1448 |
)
|
| 1449 |
parser.add_argument(
|
|
|
|
| 1452 |
default=None,
|
| 1453 |
help="Path used to resolve image_path. Defaults to --frame.",
|
| 1454 |
)
|
| 1455 |
+
parser.add_argument("--features", nargs="*", default=None)
|
| 1456 |
parser.add_argument("--prediction-column", default="y_pred")
|
| 1457 |
parser.add_argument("--out", type=Path, default=None)
|
| 1458 |
parser.add_argument("--levels", nargs="+", type=float, default=list(_LEVELS))
|
|
|
|
| 1469 |
default="test",
|
| 1470 |
)
|
| 1471 |
args = parser.parse_args(argv)
|
| 1472 |
+
if args.run_dir is not None:
|
| 1473 |
+
tol = _TOLERANCE if args.coverage_tolerance is None else float(args.coverage_tolerance)
|
| 1474 |
+
merged = evaluate_run_directory(
|
| 1475 |
+
args.run_dir,
|
| 1476 |
+
tolerance=tol,
|
| 1477 |
+
levels=args.levels,
|
| 1478 |
+
)
|
| 1479 |
+
print(f"Updated metrics.json with held-out residual quantiles in {args.run_dir}")
|
| 1480 |
+
return merged
|
| 1481 |
+
|
| 1482 |
+
if args.config is None or args.frame is None or args.features is None:
|
| 1483 |
+
parser.error("--config, --frame, and --features are required when --run-dir is omitted.")
|
| 1484 |
config = load_config(args.config)
|
| 1485 |
table = pd.read_csv(args.frame)
|
| 1486 |
samples = None if args.samples is None else np.load(args.samples)
|
bundle/src/train.py
CHANGED
|
@@ -2169,9 +2169,43 @@ def run_training(
|
|
| 2169 |
test_raw_truth = np.array([row["raw_wind"] for row in test_records], dtype=np.float64)
|
| 2170 |
test_metrics = _score_split(test_truth, test_pred, resolved)
|
| 2171 |
test_raw_metrics = _score_split(test_raw_truth, test_raw_pred, resolved)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2172 |
else:
|
| 2173 |
test_metrics = {"scored": False, "reason": test_refusal}
|
| 2174 |
test_raw_metrics = {"scored": False, "reason": test_refusal}
|
|
|
|
| 2175 |
checkpoint_name = str(resolved["paths"]["checkpoint_name"])
|
| 2176 |
if not checkpoint_name or checkpoint_name != Path(checkpoint_name).name:
|
| 2177 |
raise ValueError("paths.checkpoint_name must be a file name, not a path")
|
|
@@ -2312,6 +2346,13 @@ def run_training(
|
|
| 2312 |
|
| 2313 |
metrics["year_holdout_2019"] = YEAR_HOLDOUT_NOTE
|
| 2314 |
metrics["year_holdout_2019_indicative"] = True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2315 |
(run_dir / "metrics.json").write_text(json.dumps(metrics, indent=2) + "\n", encoding="utf-8")
|
| 2316 |
if synthetic:
|
| 2317 |
print(SMOKE_BANNER)
|
|
|
|
| 2169 |
test_raw_truth = np.array([row["raw_wind"] for row in test_records], dtype=np.float64)
|
| 2170 |
test_metrics = _score_split(test_truth, test_pred, resolved)
|
| 2171 |
test_raw_metrics = _score_split(test_raw_truth, test_raw_pred, resolved)
|
| 2172 |
+
residual_block = None
|
| 2173 |
+
try:
|
| 2174 |
+
np.savez(
|
| 2175 |
+
run_dir / "predictions.npz",
|
| 2176 |
+
y_true_test=test_truth,
|
| 2177 |
+
y_pred_test=test_pred,
|
| 2178 |
+
mc_samples_test=test_pred[None, :],
|
| 2179 |
+
y_true_val=val_truth,
|
| 2180 |
+
y_pred_val=val_pred,
|
| 2181 |
+
mc_samples_val=val_pred[None, :],
|
| 2182 |
+
)
|
| 2183 |
+
from src.evaluate import (
|
| 2184 |
+
_LEVELS,
|
| 2185 |
+
_TOLERANCE,
|
| 2186 |
+
compute_residual_quantiles,
|
| 2187 |
+
)
|
| 2188 |
+
|
| 2189 |
+
val_storms = sorted(str(s) for s in groups.get("val", []))
|
| 2190 |
+
test_storms = sorted(str(s) for s in groups.get("test", []))
|
| 2191 |
+
if val_storms and test_storms:
|
| 2192 |
+
residual_block = compute_residual_quantiles(
|
| 2193 |
+
val_truth=val_truth,
|
| 2194 |
+
val_pred=val_pred,
|
| 2195 |
+
test_truth=test_truth,
|
| 2196 |
+
test_pred=test_pred,
|
| 2197 |
+
val_storms=val_storms,
|
| 2198 |
+
test_storms=test_storms,
|
| 2199 |
+
levels=_LEVELS,
|
| 2200 |
+
tolerance=_TOLERANCE,
|
| 2201 |
+
is_synthetic=bool(synthetic),
|
| 2202 |
+
)
|
| 2203 |
+
except Exception:
|
| 2204 |
+
residual_block = None
|
| 2205 |
else:
|
| 2206 |
test_metrics = {"scored": False, "reason": test_refusal}
|
| 2207 |
test_raw_metrics = {"scored": False, "reason": test_refusal}
|
| 2208 |
+
residual_block = None
|
| 2209 |
checkpoint_name = str(resolved["paths"]["checkpoint_name"])
|
| 2210 |
if not checkpoint_name or checkpoint_name != Path(checkpoint_name).name:
|
| 2211 |
raise ValueError("paths.checkpoint_name must be a file name, not a path")
|
|
|
|
| 2346 |
|
| 2347 |
metrics["year_holdout_2019"] = YEAR_HOLDOUT_NOTE
|
| 2348 |
metrics["year_holdout_2019_indicative"] = True
|
| 2349 |
+
if residual_block is not None:
|
| 2350 |
+
from src.evaluate import _LEVELS, _TOLERANCE, merge_residual_quantiles
|
| 2351 |
+
|
| 2352 |
+
metrics = merge_residual_quantiles(
|
| 2353 |
+
metrics, residual_block, tolerance=_TOLERANCE, levels=_LEVELS
|
| 2354 |
+
)
|
| 2355 |
+
metrics["synthetic"] = bool(synthetic)
|
| 2356 |
(run_dir / "metrics.json").write_text(json.dumps(metrics, indent=2) + "\n", encoding="utf-8")
|
| 2357 |
if synthetic:
|
| 2358 |
print(SMOKE_BANNER)
|