| from __future__ import annotations |
|
|
| import argparse |
| import json |
| from pathlib import Path |
|
|
| import torch |
| import yaml |
| from torch.utils.data import DataLoader |
|
|
| from src.metrics import ( |
| assd_voxels, |
| binary_classification_metrics, |
| concordance_index, |
| dice_score, |
| expected_calibration_error, |
| iou_score, |
| ) |
| from src.models import CohortAwareCTModel |
| from src.train import build_dataset, collate_optional |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser(description="Evaluate a trained checkpoint.") |
| parser.add_argument("--config", required=True) |
| parser.add_argument("--checkpoint", required=True) |
| parser.add_argument("--output-json") |
| args = parser.parse_args() |
|
|
| cfg = yaml.safe_load(Path(args.config).read_text()) |
| dataset = build_dataset(cfg) |
| loader = DataLoader(dataset, batch_size=cfg["train"].get("batch_size", 2), shuffle=False, collate_fn=collate_optional) |
| model_cfg = cfg["model"] |
| model = CohortAwareCTModel( |
| in_channels=model_cfg.get("in_channels", 1), |
| feature_dim=model_cfg.get("feature_dim", 256), |
| clinical_dim=model_cfg.get("clinical_dim", 0), |
| survival_bins=model_cfg.get("survival_bins", 0), |
| use_pet=model_cfg.get("use_pet", True), |
| use_support=model_cfg.get("use_support", True), |
| clinical_use_missingness=model_cfg.get("clinical_use_missingness", True), |
| gate_mode=model_cfg.get("gate_mode", "selective"), |
| ) |
| try: |
| state = torch.load(args.checkpoint, map_location="cpu", weights_only=True) |
| except TypeError: |
| state = torch.load(args.checkpoint, map_location="cpu") |
| model.load_state_dict(state["model"]) |
| model.eval() |
|
|
| logits = [] |
| ct_logits = [] |
| pet_logits = [] |
| utilities = [] |
| labels = [] |
| dice = [] |
| ious = [] |
| assds = [] |
| risks = [] |
| times = [] |
| events = [] |
| with torch.no_grad(): |
| for batch in loader: |
| outputs = model(batch) |
| if "label" in batch and not torch.isnan(batch["label"]).all(): |
| logits.append(outputs["fused_logit"]) |
| ct_logits.append(outputs["ct_logit"]) |
| pet_logits.append(outputs["pet_logit"]) |
| utilities.append(outputs["pet_utility"]) |
| labels.append(batch["label"]) |
| if "mask" in batch: |
| dice.append(dice_score(outputs["support_logits"], batch["mask"])) |
| ious.append(iou_score(outputs["support_logits"], batch["mask"])) |
| assds.append(assd_voxels(outputs["support_logits"], batch["mask"])) |
| if "hazard_logits" in outputs and "time" in batch and "event" in batch: |
| hazard = torch.sigmoid(outputs["hazard_logits"]) |
| risks.append(hazard.sum(dim=1)) |
| times.append(batch["time"]) |
| events.append(batch["event"]) |
| metrics: dict[str, float] = {} |
| if logits: |
| all_logits = torch.cat(logits) |
| all_labels = torch.cat(labels) |
| metrics.update(binary_classification_metrics(all_logits, all_labels)) |
| metrics["ece"] = expected_calibration_error(all_logits, all_labels) |
| metrics["ct_only_brier"] = binary_classification_metrics(torch.cat(ct_logits), all_labels)["brier"] |
| metrics["pet_fusion_brier"] = binary_classification_metrics(torch.cat(pet_logits), all_labels)["brier"] |
| metrics["selected_pet_ratio"] = float((torch.cat(utilities) >= 0.5).float().mean()) |
| if dice: |
| metrics["dice"] = sum(dice) / len(dice) |
| metrics["iou"] = sum(ious) / len(ious) |
| metrics["assd"] = sum(assds) / len(assds) |
| if risks: |
| metrics["c_index"] = concordance_index(torch.cat(risks), torch.cat(times), torch.cat(events)) |
| if args.output_json: |
| out = Path(args.output_json) |
| out.parent.mkdir(parents=True, exist_ok=True) |
| out.write_text(json.dumps(metrics, indent=2, sort_keys=True) + "\n") |
| print(metrics) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|