Datasets:
Download modis_s2/evaluate.py from riccardode/s2_res: direct link, hf CLI and curl.
- Browser
- Download file 3.65 kB
-
https://huggingface.co/datasets/riccardode/s2_res/resolve/main/modis_s2/evaluate.py
- Command line
-
hf download hf://datasets/riccardode/s2_res/modis_s2/evaluate.py
-
curl -L -o evaluate.py https://huggingface.co/datasets/riccardode/s2_res/resolve/main/modis_s2/evaluate.py
3.65 kB
| """Evaluate an exported set using the original pooled validation metrics.""" | |
| import argparse | |
| from collections import defaultdict | |
| import json | |
| from pathlib import Path | |
| import time | |
| import numpy as np | |
| import torch | |
| from .io import ROOT, load_model, load_sample, predict | |
| from .metrics import metrics, ssim_centers, sums | |
| def evaluate(data, model_root=ROOT, device="cpu", precision="fp32", output=Path("metrics.json")): | |
| model = load_model(device, model_root) | |
| files = sorted(Path(data).glob("*/inputs.npz")) | |
| if not files: | |
| raise ValueError(f"No exported samples found in {data}") | |
| totals = defaultdict(lambda: np.zeros(5, dtype=np.float64)) | |
| records = [] | |
| started = time.monotonic() | |
| for i, path in enumerate(files, 1): | |
| inputs, meta = load_sample(path.parent, device, model_root) | |
| prediction = predict(model, inputs, precision) | |
| with np.load(path.with_name("target.npz"), allow_pickle=False) as target: | |
| y, valid = target["ndvi"], target["valid"].astype(bool) | |
| if prediction.shape != y.shape or valid.shape != y.shape: | |
| raise ValueError(f"Target grid mismatch: {meta['id']}") | |
| anchor = inputs["anchor"][0].float().cpu().numpy() | |
| modis_support = inputs["same_day"][0, 2].bool().cpu().numpy() | |
| groups = {"all": valid, "common_modis": valid & modis_support, | |
| "outside_common_modis": valid & ~modis_support, | |
| "common_last_clear_s2": valid & anchor[1].astype(bool)} | |
| if modis_support.mean() >= .8: | |
| groups["scene_modis_coverage_at_least_80pct"] = valid | |
| if meta["source_cohort"] == "additional_256_v2": | |
| groups["added_val"] = valid | |
| scene = {"id": meta["id"], "groups": {}} | |
| for group, mask in groups.items(): | |
| centers = ssim_centers(mask) | |
| for name, values in [("model", prediction), ("last_clear_s2", anchor[0])]: | |
| if name == "last_clear_s2" and group != "common_last_clear_s2": | |
| continue | |
| values = sums(values, y, mask, centers) | |
| totals[(group, name)] += values | |
| scene["groups"].setdefault(group, {})[name] = metrics(values) | |
| records.append(scene) | |
| if i % 10 == 0 or i == len(files): | |
| print(f"Evaluated {i}/{len(files)} scenes ({time.monotonic()-started:.0f} s)", flush=True) | |
| summary = {} | |
| for (group, name), values in totals.items(): | |
| summary.setdefault(group, {})[name] = metrics(values) | |
| result = {"scenes": len(records), "device": device, "precision": precision, | |
| "seconds": time.monotonic()-started, "summary": summary, "per_scene": records, | |
| "split": "validation", "independent_test": False} | |
| output = Path(output) | |
| output.parent.mkdir(parents=True, exist_ok=True) | |
| output.write_text(json.dumps(result, indent=2, allow_nan=False)) | |
| print(json.dumps(summary["all"]["model"], indent=2)) | |
| return result | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--data", type=Path, required=True) | |
| parser.add_argument("--output", type=Path, default=Path("metrics.json")) | |
| parser.add_argument("--model-dir", type=Path, default=ROOT) | |
| parser.add_argument("--device", choices=("cpu", "cuda"), default="cpu") | |
| parser.add_argument("--precision", choices=("fp32", "bf16"), default="fp32") | |
| parser.add_argument("--threads", type=int, default=2) | |
| args = parser.parse_args() | |
| torch.set_num_threads(args.threads) | |
| evaluate(args.data, args.model_dir, args.device, args.precision, args.output) | |
| if __name__ == "__main__": | |
| main() | |