| """Shared training and evaluation utilities.""" |
|
|
| import math |
|
|
| import numpy as np |
|
|
| try: |
| from src.metric import pearsonr_score |
| except ImportError: |
| from metric import pearsonr_score |
|
|
|
|
| def validate_finite_loss(loss_value: float, batch_idx: int) -> None: |
| """Fail fast when training diverges.""" |
| if math.isnan(loss_value) or math.isinf(loss_value): |
| raise RuntimeError(f"NaN/Inf loss encountered on step {batch_idx + 1}; exiting") |
|
|
|
|
| def compute_subject_metrics( |
| samples: np.ndarray, |
| outputs: np.ndarray, |
| subjects: list[int], |
| ) -> tuple[float, dict[str, np.ndarray | float]]: |
| """Compute per-subject and global Pearson metrics.""" |
| metrics: dict[str, np.ndarray | float] = {} |
|
|
| dim = samples.shape[-1] |
| acc = 0.0 |
| acc_map = np.zeros(dim) |
|
|
| for ii, sub in enumerate(subjects): |
| y_true = samples[ii].reshape(-1, dim) |
| y_pred = outputs[ii].reshape(-1, dim) |
|
|
| acc_map_i = pearsonr_score(y_true, y_pred) |
| acc_i = float(np.mean(acc_map_i)) |
|
|
| metrics[f"accmap_sub-{sub}"] = acc_map_i |
| metrics[f"acc_sub-{sub}"] = acc_i |
|
|
| acc_map += acc_map_i / len(subjects) |
| acc += acc_i / len(subjects) |
|
|
| metrics["accmap_avg"] = acc_map |
| metrics["acc_avg"] = acc |
|
|
| return acc, metrics |
|
|
|
|
| def format_subject_accuracies(metrics: dict[str, np.ndarray | float]) -> str: |
| """Render a stable, compact per-subject accuracy string for logs.""" |
| values = [ |
| f"{val:.3f}" |
| for key, val in metrics.items() |
| if key.startswith("acc_sub-") and isinstance(val, (float, np.floating)) |
| ] |
| return ",".join(values) |
|
|