Upload code/metrics.py
Browse files- code/metrics.py +99 -0
code/metrics.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@dataclass
|
| 12 |
+
class LossConfig:
|
| 13 |
+
rec_weight: float = 1.0
|
| 14 |
+
z_weight: float = 2.0
|
| 15 |
+
z_bin_weight: float = 0.2
|
| 16 |
+
z_candidate_weight: float = 0.0
|
| 17 |
+
z_nll_weight: float = 0.05
|
| 18 |
+
line_weight_power: float = 1.0
|
| 19 |
+
clean_z_only: bool = False
|
| 20 |
+
zwarn_weight: float = 0.3
|
| 21 |
+
high_z_boost: float = 1.0
|
| 22 |
+
high_z_threshold: float = math.log1p(1.0)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def masked_huber(pred: torch.Tensor, target: torch.Tensor, mask: torch.Tensor, weight: torch.Tensor | None = None) -> torch.Tensor:
|
| 26 |
+
loss = F.smooth_l1_loss(pred, target, reduction="none", beta=0.5)
|
| 27 |
+
m = mask.float()
|
| 28 |
+
if weight is not None:
|
| 29 |
+
loss = loss * weight.float()
|
| 30 |
+
denom = m.sum().clamp_min(1.0)
|
| 31 |
+
return (loss * m).sum() / denom
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def redshift_losses(model, out: dict[str, torch.Tensor], y: torch.Tensor, zwarn: torch.Tensor, cfg: LossConfig) -> dict[str, torch.Tensor]:
|
| 35 |
+
clean = (~zwarn.bool()) & torch.isfinite(y) if cfg.clean_z_only else torch.isfinite(y)
|
| 36 |
+
y_pred_all = out.get("y_pred", out["y_mu"])
|
| 37 |
+
if clean.sum() == 0:
|
| 38 |
+
zero = y_pred_all.sum() * 0.0
|
| 39 |
+
return {"z_huber": zero, "z_bin": zero, "z_candidate": zero, "z_nll": zero}
|
| 40 |
+
y_mu = y_pred_all[clean]
|
| 41 |
+
y_true = y[clean]
|
| 42 |
+
y_logvar = out["y_logvar"][clean]
|
| 43 |
+
sample_weight = torch.where(zwarn[clean].bool(), torch.full_like(y_true, cfg.zwarn_weight), torch.ones_like(y_true))
|
| 44 |
+
if cfg.high_z_boost != 1.0:
|
| 45 |
+
high_z_weight = torch.where(
|
| 46 |
+
y_true >= cfg.high_z_threshold,
|
| 47 |
+
torch.full_like(y_true, cfg.high_z_boost),
|
| 48 |
+
torch.ones_like(y_true),
|
| 49 |
+
)
|
| 50 |
+
sample_weight = sample_weight * high_z_weight
|
| 51 |
+
huber = F.smooth_l1_loss(y_mu, y_true, beta=0.01, reduction="none")
|
| 52 |
+
z_huber = (huber * sample_weight).sum() / sample_weight.sum().clamp_min(1.0)
|
| 53 |
+
bins = model.y_to_bin(y_true)
|
| 54 |
+
z_bin_each = F.cross_entropy(out["z_bin_logits"][clean], bins, reduction="none")
|
| 55 |
+
z_bin = (z_bin_each * sample_weight).sum() / sample_weight.sum().clamp_min(1.0)
|
| 56 |
+
if "candidate_y" in out:
|
| 57 |
+
candidate_y = out["candidate_y"][clean]
|
| 58 |
+
true_candidate_y = candidate_y.gather(1, bins.unsqueeze(1)).squeeze(1)
|
| 59 |
+
z_candidate_each = F.smooth_l1_loss(true_candidate_y, y_true, beta=0.01, reduction="none")
|
| 60 |
+
z_candidate = (z_candidate_each * sample_weight).sum() / sample_weight.sum().clamp_min(1.0)
|
| 61 |
+
else:
|
| 62 |
+
z_candidate = y_mu.sum() * 0.0
|
| 63 |
+
z_nll_each = 0.5 * (torch.exp(-y_logvar) * (y_mu - y_true).pow(2) + y_logvar)
|
| 64 |
+
z_nll = (z_nll_each * sample_weight).sum() / sample_weight.sum().clamp_min(1.0)
|
| 65 |
+
return {"z_huber": z_huber, "z_bin": z_bin, "z_candidate": z_candidate, "z_nll": z_nll}
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def total_loss(model, out: dict[str, torch.Tensor], batch: dict[str, torch.Tensor], cfg: LossConfig) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
|
| 69 |
+
line_weight = batch["line_weight"].pow(cfg.line_weight_power)
|
| 70 |
+
rec = masked_huber(out["rec"], batch["target_flux"], batch["loss_mask"], weight=line_weight)
|
| 71 |
+
z_parts = redshift_losses(model, out, batch["y"], batch["zwarn"], cfg)
|
| 72 |
+
total = (
|
| 73 |
+
cfg.rec_weight * rec
|
| 74 |
+
+ cfg.z_weight * z_parts["z_huber"]
|
| 75 |
+
+ cfg.z_bin_weight * z_parts["z_bin"]
|
| 76 |
+
+ cfg.z_candidate_weight * z_parts["z_candidate"]
|
| 77 |
+
+ cfg.z_nll_weight * z_parts["z_nll"]
|
| 78 |
+
)
|
| 79 |
+
metrics = {"loss": total.detach(), "rec": rec.detach(), **{k: v.detach() for k, v in z_parts.items()}}
|
| 80 |
+
return total, metrics
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def redshift_metrics(y_true: np.ndarray, y_pred: np.ndarray) -> dict[str, float]:
|
| 84 |
+
z_true = np.expm1(y_true)
|
| 85 |
+
z_pred = np.expm1(y_pred)
|
| 86 |
+
dz_norm = (z_pred - z_true) / (1.0 + z_true)
|
| 87 |
+
med = np.nanmedian(dz_norm)
|
| 88 |
+
nmad = 1.4826 * np.nanmedian(np.abs(dz_norm - med))
|
| 89 |
+
return {
|
| 90 |
+
"mae_z": float(np.nanmean(np.abs(z_pred - z_true))),
|
| 91 |
+
"mae_log1p": float(np.nanmean(np.abs(y_pred - y_true))),
|
| 92 |
+
"rmse_z": float(math.sqrt(np.nanmean((z_pred - z_true) ** 2))),
|
| 93 |
+
"nmad": float(nmad),
|
| 94 |
+
"cat_0p003": float(np.nanmean(np.abs(dz_norm) > 0.003)),
|
| 95 |
+
"cat_0p01": float(np.nanmean(np.abs(dz_norm) > 0.01)),
|
| 96 |
+
"cat_0p05": float(np.nanmean(np.abs(dz_norm) > 0.05)),
|
| 97 |
+
"pred_std_z": float(np.nanstd(z_pred)),
|
| 98 |
+
"true_std_z": float(np.nanstd(z_true)),
|
| 99 |
+
}
|