File size: 3,487 Bytes
bffb03e | 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 | """Evaluate SatMAE++ masked and multi-scale reconstruction."""
import json
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np, yaml
ROOT = Path(__file__).resolve().parents[1]
def validate_config(cfg):
data, model = cfg["data"], cfg["model"]
if data["image_size"] != model["image_size"] or data["channels"] != model["in_channels"]:
raise ValueError("data and model image shape settings must match")
if data["scales"] != model["scales"]:
raise ValueError("data.scales and model.scales must match")
def patchify(images, patch_size):
batch, channels, height, width = images.shape
patches = images.reshape(batch, channels, height // patch_size, patch_size,
width // patch_size, patch_size)
return patches.transpose(0, 2, 4, 1, 3, 5).reshape(batch, -1, channels * patch_size**2)
def main():
import argparse
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--config", type=Path, default=ROOT / "conf/config.yaml")
args = parser.parse_args()
cfg = yaml.safe_load(args.config.read_text())
validate_config(cfg)
source = ROOT / cfg["paths"]["inference_dir"] / "reconstruction.npz"
if not source.exists(): raise FileNotFoundError("Run inference before evaluation")
archive = np.load(source); target, prediction = archive["target"], archive["prediction"]
mse = float(np.mean((prediction - target) ** 2)); masked = archive["mask"].astype(bool)
patch_error = np.mean((patchify(prediction, cfg["model"]["patch_size"]) -
patchify(target, cfg["model"]["patch_size"])) ** 2, axis=-1)
if masked.size != patch_error.shape[0] * patch_error.shape[1]:
groups = masked.reshape(masked.shape[0], -1, patch_error.shape[1])
masked = groups.any(axis=1)
masked_mse = float(patch_error[masked].mean()) if masked.any() else mse
result = {"reconstruction_mse": mse, "masked_mse": masked_mse,
"data_source": "synthetic", "protocol": cfg["data"]["protocol"]}
out = ROOT / cfg["paths"]["evaluation_dir"]; out.mkdir(parents=True, exist_ok=True)
scales, scale_errors = cfg["model"]["scales"], []
for scale in scales:
value = archive[f"prediction_{scale}"]
scaled = archive[f"target_{scale}"]
scale_errors.append(float(np.mean((value - scaled) ** 2)))
result["scale_mse"] = {str(s): e for s, e in zip(scales, scale_errors)}
(out / "metrics.json").write_text(json.dumps(result, indent=2) + "\n")
figure, axes = plt.subplots(1, len(scales) + 1, figsize=(3 * (len(scales) + 1), 3))
axes[0].imshow(np.clip(target[0, :3].transpose(1, 2, 0), 0, 1)); axes[0].set_title("Original"); axes[0].axis("off")
for axis, scale in zip(axes[1:], scales):
image = archive[f"prediction_{scale}"][0]
axis.imshow(np.clip(image[:3].transpose(1, 2, 0), 0, 1)); axis.set_title(f"Scale x{scale}"); axis.axis("off")
figure.tight_layout(); figure.savefig(out / "multiscale_reconstruction.png", dpi=160); plt.close(figure)
figure, axis = plt.subplots(figsize=(5, 3)); axis.plot(scales, scale_errors, marker="o"); axis.set(xlabel="Reconstruction scale", ylabel="MSE", title="Multi-scale Reconstruction Comparison"); axis.grid(alpha=0.25); figure.tight_layout(); figure.savefig(out / "scale_comparison.png", dpi=160); plt.close(figure)
print(json.dumps(result, indent=2)); print("evaluation=", out)
if __name__ == "__main__": main()
|