Add src
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- src/trifuse/__init__.py +0 -0
- src/trifuse/__pycache__/__init__.cpython-312.pyc +0 -0
- src/trifuse/__pycache__/experiments.cpython-312.pyc +0 -0
- src/trifuse/analysis/__init__.py +0 -0
- src/trifuse/analysis/__pycache__/__init__.cpython-312.pyc +0 -0
- src/trifuse/analysis/__pycache__/gradcam.cpython-312.pyc +0 -0
- src/trifuse/analysis/__pycache__/subgroup.cpython-312.pyc +0 -0
- src/trifuse/analysis/confound.py +112 -0
- src/trifuse/analysis/gradcam.py +92 -0
- src/trifuse/analysis/subgroup.py +76 -0
- src/trifuse/data/__init__.py +0 -0
- src/trifuse/data/__pycache__/__init__.cpython-312.pyc +0 -0
- src/trifuse/data/__pycache__/cohort.cpython-312.pyc +0 -0
- src/trifuse/data/__pycache__/datasets.cpython-312.pyc +0 -0
- src/trifuse/data/__pycache__/preprocess_2d.cpython-312.pyc +0 -0
- src/trifuse/data/__pycache__/preprocess_3d.cpython-312.pyc +0 -0
- src/trifuse/data/__pycache__/splits.cpython-312.pyc +0 -0
- src/trifuse/data/cohort.py +174 -0
- src/trifuse/data/datasets.py +168 -0
- src/trifuse/data/download.py +56 -0
- src/trifuse/data/preprocess_2d.py +90 -0
- src/trifuse/data/preprocess_3d.py +113 -0
- src/trifuse/data/splits.py +90 -0
- src/trifuse/eval/__init__.py +0 -0
- src/trifuse/eval/__pycache__/__init__.cpython-312.pyc +0 -0
- src/trifuse/eval/__pycache__/metrics.cpython-312.pyc +0 -0
- src/trifuse/eval/__pycache__/runner.cpython-312.pyc +0 -0
- src/trifuse/eval/__pycache__/stats.cpython-312.pyc +0 -0
- src/trifuse/eval/metrics.py +71 -0
- src/trifuse/eval/runner.py +152 -0
- src/trifuse/eval/stats.py +71 -0
- src/trifuse/experiments.py +67 -0
- src/trifuse/models/__init__.py +0 -0
- src/trifuse/models/__pycache__/__init__.cpython-312.pyc +0 -0
- src/trifuse/models/__pycache__/baselines_tab.cpython-312.pyc +0 -0
- src/trifuse/models/__pycache__/cnn2d.cpython-312.pyc +0 -0
- src/trifuse/models/__pycache__/cnn3d.cpython-312.pyc +0 -0
- src/trifuse/models/__pycache__/fusion.cpython-312.pyc +0 -0
- src/trifuse/models/__pycache__/hybrids.cpython-312.pyc +0 -0
- src/trifuse/models/__pycache__/registry.cpython-312.pyc +0 -0
- src/trifuse/models/__pycache__/transformers.cpython-312.pyc +0 -0
- src/trifuse/models/__pycache__/trifuse.cpython-312.pyc +0 -0
- src/trifuse/models/baselines_tab.py +43 -0
- src/trifuse/models/cnn2d.py +72 -0
- src/trifuse/models/cnn3d.py +21 -0
- src/trifuse/models/fusion.py +50 -0
- src/trifuse/models/hybrids.py +129 -0
- src/trifuse/models/registry.py +50 -0
- src/trifuse/models/transformers.py +76 -0
- src/trifuse/models/trifuse.py +128 -0
src/trifuse/__init__.py
ADDED
|
File without changes
|
src/trifuse/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (129 Bytes). View file
|
|
|
src/trifuse/__pycache__/experiments.cpython-312.pyc
ADDED
|
Binary file (3.07 kB). View file
|
|
|
src/trifuse/analysis/__init__.py
ADDED
|
File without changes
|
src/trifuse/analysis/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (138 Bytes). View file
|
|
|
src/trifuse/analysis/__pycache__/gradcam.cpython-312.pyc
ADDED
|
Binary file (5.79 kB). View file
|
|
|
src/trifuse/analysis/__pycache__/subgroup.cpython-312.pyc
ADDED
|
Binary file (4.86 kB). View file
|
|
|
src/trifuse/analysis/confound.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Demographic confound & shortcut-baseline analysis (P10, Table 5 part 1).
|
| 2 |
+
|
| 3 |
+
Purpose: show how much of the 3-class signal is recoverable from demographics /
|
| 4 |
+
morphometry ALONE (no MRI). If an age-only model is already strong, the dataset
|
| 5 |
+
has confounding that must be discussed honestly rather than hidden.
|
| 6 |
+
|
| 7 |
+
Shortcut baselines:
|
| 8 |
+
- age-only logistic regression
|
| 9 |
+
- demographic XGBoost (age, sex, education, ses)
|
| 10 |
+
- full-structured XGBoost (demographic + eTIV, nWBV, ASF)
|
| 11 |
+
|
| 12 |
+
All evaluated on the SAME subject-level folds/seeds as the main experiments,
|
| 13 |
+
using out-of-fold predictions so numbers are directly comparable to Table 3.
|
| 14 |
+
Never uses CDR or MMSE (label leakage).
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import pandas as pd
|
| 22 |
+
from sklearn.linear_model import LogisticRegression
|
| 23 |
+
from sklearn.preprocessing import StandardScaler
|
| 24 |
+
|
| 25 |
+
from trifuse.data.splits import make_folds, split_for, SEEDS, N_FOLDS
|
| 26 |
+
from trifuse.eval.metrics import compute_metrics
|
| 27 |
+
from trifuse.models.baselines_tab import make_xgb
|
| 28 |
+
|
| 29 |
+
DEMO_COLS = ["age", "sex", "education", "ses"]
|
| 30 |
+
FULL_COLS = ["age", "sex", "education", "ses", "etiv", "nwbv", "asf"]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _oof_predict(df: pd.DataFrame, feature_cols: list[str], model_kind: str) -> pd.DataFrame:
|
| 34 |
+
"""Run repeated CV, return per-subject OOF predictions (one row per subject per seed)."""
|
| 35 |
+
folds = make_folds(df)
|
| 36 |
+
records = []
|
| 37 |
+
for seed in SEEDS:
|
| 38 |
+
for fold in range(N_FOLDS):
|
| 39 |
+
tr_ids, va_ids, te_ids = split_for(folds, df, seed, fold)
|
| 40 |
+
tr = df[df["subject_id"].isin(set(tr_ids) | set(va_ids))]
|
| 41 |
+
te = df[df["subject_id"].isin(te_ids)]
|
| 42 |
+
|
| 43 |
+
Xtr = tr[feature_cols].to_numpy(dtype=float)
|
| 44 |
+
ytr = tr["class_id"].to_numpy(dtype=int)
|
| 45 |
+
Xte = te[feature_cols].to_numpy(dtype=float)
|
| 46 |
+
yte = te["class_id"].to_numpy(dtype=int)
|
| 47 |
+
|
| 48 |
+
# impute (train medians) + standardize
|
| 49 |
+
med = np.nanmedian(Xtr, axis=0)
|
| 50 |
+
Xtr = np.where(np.isnan(Xtr), med, Xtr)
|
| 51 |
+
Xte = np.where(np.isnan(Xte), med, Xte)
|
| 52 |
+
sc = StandardScaler().fit(Xtr)
|
| 53 |
+
Xtr, Xte = sc.transform(Xtr), sc.transform(Xte)
|
| 54 |
+
|
| 55 |
+
if model_kind == "logreg":
|
| 56 |
+
clf = LogisticRegression(max_iter=1000, class_weight="balanced")
|
| 57 |
+
clf.fit(Xtr, ytr)
|
| 58 |
+
prob = clf.predict_proba(Xte)
|
| 59 |
+
else: # xgboost
|
| 60 |
+
clf = make_xgb(n_classes=3, seed=seed)
|
| 61 |
+
clf.fit(Xtr, ytr)
|
| 62 |
+
prob = clf.predict_proba(Xte)
|
| 63 |
+
|
| 64 |
+
pred = prob.argmax(1)
|
| 65 |
+
for sid, yt, yp, pr in zip(te_ids, yte, pred, prob):
|
| 66 |
+
records.append({"subject_id": sid, "seed": seed, "fold": fold,
|
| 67 |
+
"y_true": int(yt), "y_pred": int(yp),
|
| 68 |
+
"p0": pr[0], "p1": pr[1], "p2": pr[2]})
|
| 69 |
+
return pd.DataFrame(records)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def run_confound(subjects_csv: str | Path, out_dir: str | Path) -> pd.DataFrame:
|
| 73 |
+
df = pd.read_csv(subjects_csv)
|
| 74 |
+
df = df[df["class_id"].notna()].reset_index(drop=True)
|
| 75 |
+
df["class_id"] = df["class_id"].astype(int)
|
| 76 |
+
out_dir = Path(out_dir); out_dir.mkdir(parents=True, exist_ok=True)
|
| 77 |
+
|
| 78 |
+
configs = [
|
| 79 |
+
("age_only_logreg", ["age"], "logreg"),
|
| 80 |
+
("demographic_xgb", DEMO_COLS, "xgboost"),
|
| 81 |
+
("full_structured_xgb", FULL_COLS, "xgboost"),
|
| 82 |
+
]
|
| 83 |
+
summary = []
|
| 84 |
+
for name, cols, kind in configs:
|
| 85 |
+
oof = _oof_predict(df, cols, kind)
|
| 86 |
+
oof.to_csv(out_dir / f"oof_{name}.csv", index=False)
|
| 87 |
+
# aggregate metric per seed then mean+/-std
|
| 88 |
+
per_seed = []
|
| 89 |
+
for seed in SEEDS:
|
| 90 |
+
s = oof[oof["seed"] == seed]
|
| 91 |
+
m = compute_metrics(s["y_true"].to_numpy(), s["y_pred"].to_numpy(),
|
| 92 |
+
s[["p0", "p1", "p2"]].to_numpy())
|
| 93 |
+
per_seed.append(m)
|
| 94 |
+
macro_f1 = np.array([m["macro_f1"] for m in per_seed])
|
| 95 |
+
bal_acc = np.array([m["balanced_accuracy"] for m in per_seed])
|
| 96 |
+
ad_recall = np.array([m["recall_AD"] for m in per_seed])
|
| 97 |
+
summary.append({
|
| 98 |
+
"model": name,
|
| 99 |
+
"macro_f1_mean": macro_f1.mean(), "macro_f1_std": macro_f1.std(),
|
| 100 |
+
"bal_acc_mean": bal_acc.mean(), "bal_acc_std": bal_acc.std(),
|
| 101 |
+
"ad_recall_mean": ad_recall.mean(), "ad_recall_std": ad_recall.std(),
|
| 102 |
+
})
|
| 103 |
+
res = pd.DataFrame(summary)
|
| 104 |
+
res.to_csv(out_dir / "confound_summary.csv", index=False)
|
| 105 |
+
return res
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
if __name__ == "__main__":
|
| 109 |
+
import sys
|
| 110 |
+
csv = sys.argv[1] if len(sys.argv) > 1 else "data/metadata/subjects_clean.csv"
|
| 111 |
+
out = sys.argv[2] if len(sys.argv) > 2 else "results/tables/confound"
|
| 112 |
+
print(run_confound(csv, out).to_string(index=False))
|
src/trifuse/analysis/gradcam.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Interpretability: Grad-CAM for 2D CNN encoders and attention rollout for the
|
| 2 |
+
slice-plane Transformer in TriFuse-AD.
|
| 3 |
+
|
| 4 |
+
Qualitative only. We do NOT claim the model "detects the hippocampus" - we report
|
| 5 |
+
that attended regions overlap with anatomy known to be relevant in AD (medial
|
| 6 |
+
temporal lobe, ventricles, cortical atrophy).
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn.functional as F
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class GradCAM:
|
| 18 |
+
"""Grad-CAM on a target conv layer of a 2D CNN.
|
| 19 |
+
|
| 20 |
+
Usage:
|
| 21 |
+
cam = GradCAM(model, target_layer)
|
| 22 |
+
heat = cam(input_tensor, class_idx) # (H, W) in [0,1]
|
| 23 |
+
cam.remove()
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(self, model: torch.nn.Module, target_layer: torch.nn.Module):
|
| 27 |
+
self.model = model
|
| 28 |
+
self.target_layer = target_layer
|
| 29 |
+
self._acts: torch.Tensor | None = None
|
| 30 |
+
self._grads: torch.Tensor | None = None
|
| 31 |
+
self._fh = target_layer.register_forward_hook(self._fwd)
|
| 32 |
+
self._bh = target_layer.register_full_backward_hook(self._bwd)
|
| 33 |
+
|
| 34 |
+
def _fwd(self, _module, _inp, out):
|
| 35 |
+
self._acts = out.detach()
|
| 36 |
+
|
| 37 |
+
def _bwd(self, _module, _gin, gout):
|
| 38 |
+
self._grads = gout[0].detach()
|
| 39 |
+
|
| 40 |
+
def __call__(self, x: torch.Tensor, class_idx: int | None = None) -> np.ndarray:
|
| 41 |
+
self.model.eval()
|
| 42 |
+
logits = self.model(x)
|
| 43 |
+
if isinstance(logits, dict):
|
| 44 |
+
logits = logits["logits"]
|
| 45 |
+
if class_idx is None:
|
| 46 |
+
class_idx = int(logits.argmax(1)[0])
|
| 47 |
+
self.model.zero_grad(set_to_none=True)
|
| 48 |
+
logits[0, class_idx].backward(retain_graph=True)
|
| 49 |
+
|
| 50 |
+
# global-average-pool gradients -> channel weights
|
| 51 |
+
weights = self._grads.mean(dim=(2, 3), keepdim=True) # (1,C,1,1)
|
| 52 |
+
cam = (weights * self._acts).sum(dim=1) # (1,H',W')
|
| 53 |
+
cam = F.relu(cam)
|
| 54 |
+
cam = cam - cam.min()
|
| 55 |
+
cam = cam / (cam.max() + 1e-8)
|
| 56 |
+
cam = F.interpolate(cam.unsqueeze(1), size=x.shape[-2:], mode="bilinear",
|
| 57 |
+
align_corners=False)[0, 0]
|
| 58 |
+
return cam.cpu().numpy()
|
| 59 |
+
|
| 60 |
+
def remove(self):
|
| 61 |
+
self._fh.remove()
|
| 62 |
+
self._bh.remove()
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@torch.no_grad()
|
| 66 |
+
def attention_rollout(attn_maps: list[torch.Tensor]) -> np.ndarray:
|
| 67 |
+
"""Attention rollout (Abnar & Zuidema 2020) over stacked attention matrices.
|
| 68 |
+
|
| 69 |
+
attn_maps: list of (heads, T, T) attention tensors from each Transformer layer.
|
| 70 |
+
Returns the CLS->token attention (T-1,) after rollout, normalized to [0,1].
|
| 71 |
+
"""
|
| 72 |
+
result = None
|
| 73 |
+
for a in attn_maps:
|
| 74 |
+
a = a.mean(0) # average heads -> (T,T)
|
| 75 |
+
a = a + torch.eye(a.size(0), device=a.device) # add residual
|
| 76 |
+
a = a / a.sum(dim=-1, keepdim=True)
|
| 77 |
+
result = a if result is None else a @ result
|
| 78 |
+
cls_to_tokens = result[0, 1:] # CLS row, drop CLS->CLS
|
| 79 |
+
cls_to_tokens = cls_to_tokens - cls_to_tokens.min()
|
| 80 |
+
cls_to_tokens = cls_to_tokens / (cls_to_tokens.max() + 1e-8)
|
| 81 |
+
return cls_to_tokens.cpu().numpy()
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def overlay_heatmap(gray: np.ndarray, heat: np.ndarray, alpha: float = 0.45) -> np.ndarray:
|
| 85 |
+
"""Overlay a [0,1] heatmap on a grayscale slice (both HxW) -> RGB uint8."""
|
| 86 |
+
import matplotlib
|
| 87 |
+
|
| 88 |
+
gray = (gray - gray.min()) / (np.ptp(gray) + 1e-8)
|
| 89 |
+
rgb = np.stack([gray] * 3, axis=-1)
|
| 90 |
+
cmap = matplotlib.colormaps["jet"](heat)[..., :3]
|
| 91 |
+
out = (1 - alpha) * rgb + alpha * cmap
|
| 92 |
+
return (np.clip(out, 0, 1) * 255).astype(np.uint8)
|
src/trifuse/analysis/subgroup.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Subgroup robustness analysis (P10, Table 5 part 2).
|
| 2 |
+
|
| 3 |
+
Evaluates any model's saved OOF predictions sliced by demographic subgroup:
|
| 4 |
+
age bands (60-69, 70-79, 80+) and sex. Tests whether a model's performance is
|
| 5 |
+
stable across groups or driven by an age->label correlation.
|
| 6 |
+
|
| 7 |
+
Consumes the per-subject OOF prediction CSVs written by eval/runner.py (columns:
|
| 8 |
+
subject_id, seed, fold, y_true, y_pred, prob_0, prob_1, prob_2) joined to the
|
| 9 |
+
cohort table for age/sex, so no re-training is needed.
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
import pandas as pd
|
| 17 |
+
|
| 18 |
+
from trifuse.eval.metrics import compute_metrics
|
| 19 |
+
|
| 20 |
+
AGE_BANDS = [("60-69", 60, 70), ("70-79", 70, 80), ("80+", 80, 200)]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _band(age: float) -> str:
|
| 24 |
+
for name, lo, hi in AGE_BANDS:
|
| 25 |
+
if lo <= age < hi:
|
| 26 |
+
return name
|
| 27 |
+
return "other"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def subgroup_table(oof_csv: str | Path, subjects_csv: str | Path) -> pd.DataFrame:
|
| 31 |
+
"""Return per-subgroup metrics (pooled over all seeds/folds) for one model."""
|
| 32 |
+
oof = pd.read_csv(oof_csv)
|
| 33 |
+
sub = pd.read_csv(subjects_csv)[["subject_id", "age", "sex"]]
|
| 34 |
+
df = oof.merge(sub, on="subject_id", how="left")
|
| 35 |
+
df["age_band"] = df["age"].apply(_band)
|
| 36 |
+
df["sex_str"] = df["sex"].map({0: "Male", 1: "Female"}).fillna("Unknown")
|
| 37 |
+
|
| 38 |
+
prob_cols = ["prob_0", "prob_1", "prob_2"]
|
| 39 |
+
|
| 40 |
+
def _row(name: str, sl: pd.DataFrame) -> dict:
|
| 41 |
+
if len(sl) == 0:
|
| 42 |
+
return {"subgroup": name, "n": 0}
|
| 43 |
+
m = compute_metrics(sl["y_true"].to_numpy(), sl["y_pred"].to_numpy(),
|
| 44 |
+
sl[prob_cols].to_numpy())
|
| 45 |
+
return {"subgroup": name, "n": int(sl["subject_id"].nunique()),
|
| 46 |
+
"macro_f1": m["macro_f1"], "balanced_accuracy": m["balanced_accuracy"],
|
| 47 |
+
"ad_recall": m["recall_AD"]}
|
| 48 |
+
|
| 49 |
+
rows = [_row("Overall", df)]
|
| 50 |
+
for name, _, _ in AGE_BANDS:
|
| 51 |
+
rows.append(_row(name, df[df["age_band"] == name]))
|
| 52 |
+
for sx in ["Male", "Female"]:
|
| 53 |
+
rows.append(_row(sx, df[df["sex_str"] == sx]))
|
| 54 |
+
return pd.DataFrame(rows)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def run_subgroup(oof_csvs: dict[str, str | Path], subjects_csv: str | Path,
|
| 58 |
+
out_dir: str | Path) -> pd.DataFrame:
|
| 59 |
+
"""oof_csvs: {model_name: path}. Builds a combined subgroup table across models."""
|
| 60 |
+
out_dir = Path(out_dir); out_dir.mkdir(parents=True, exist_ok=True)
|
| 61 |
+
frames = []
|
| 62 |
+
for name, path in oof_csvs.items():
|
| 63 |
+
t = subgroup_table(path, subjects_csv)
|
| 64 |
+
t.insert(0, "model", name)
|
| 65 |
+
frames.append(t)
|
| 66 |
+
res = pd.concat(frames, ignore_index=True)
|
| 67 |
+
res.to_csv(out_dir / "subgroup_summary.csv", index=False)
|
| 68 |
+
return res
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
if __name__ == "__main__":
|
| 72 |
+
import sys, glob
|
| 73 |
+
subj = sys.argv[1] if len(sys.argv) > 1 else "data/metadata/subjects_clean.csv"
|
| 74 |
+
oof_dir = sys.argv[2] if len(sys.argv) > 2 else "results/oof"
|
| 75 |
+
csvs = {Path(p).stem.replace("oof_", ""): p for p in glob.glob(f"{oof_dir}/oof_*.csv")}
|
| 76 |
+
print(run_subgroup(csvs, subj, "results/tables/subgroup").to_string(index=False))
|
src/trifuse/data/__init__.py
ADDED
|
File without changes
|
src/trifuse/data/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (134 Bytes). View file
|
|
|
src/trifuse/data/__pycache__/cohort.cpython-312.pyc
ADDED
|
Binary file (8.95 kB). View file
|
|
|
src/trifuse/data/__pycache__/datasets.cpython-312.pyc
ADDED
|
Binary file (10.5 kB). View file
|
|
|
src/trifuse/data/__pycache__/preprocess_2d.cpython-312.pyc
ADDED
|
Binary file (4.96 kB). View file
|
|
|
src/trifuse/data/__pycache__/preprocess_3d.cpython-312.pyc
ADDED
|
Binary file (6.57 kB). View file
|
|
|
src/trifuse/data/__pycache__/splits.cpython-312.pyc
ADDED
|
Binary file (5.38 kB). View file
|
|
|
src/trifuse/data/cohort.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build the analysis cohort from OASIS-1 per-subject metadata + processed volumes.
|
| 2 |
+
|
| 3 |
+
The central OASIS-1 demographics spreadsheet URL is dead, so we reconstruct the
|
| 4 |
+
full metadata table by parsing each subject's `OAS1_XXXX_MR1.txt` (present in every
|
| 5 |
+
subject folder) and pairing it with the atlas-registered, brain-masked processed
|
| 6 |
+
volume `*_111_t88_masked_gfc.img`.
|
| 7 |
+
|
| 8 |
+
Cohort protocol (see plan):
|
| 9 |
+
- one row per subject (no repeat scans, no reliability sessions)
|
| 10 |
+
- age >= 60 only -> breaks the "young brain = CN" age shortcut
|
| 11 |
+
- label from CDR: 0 -> CN, 0.5 -> VMD (very mild dementia), >=1 -> AD
|
| 12 |
+
- CDR & MMSE are NEVER model inputs (label leakage); kept only for analysis.
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import glob
|
| 17 |
+
import re
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
import pandas as pd
|
| 21 |
+
|
| 22 |
+
# --- paths -------------------------------------------------------------------
|
| 23 |
+
ROOT = Path(__file__).resolve().parents[3]
|
| 24 |
+
RAW = ROOT / "data" / "raw"
|
| 25 |
+
META_DIR = ROOT / "data" / "metadata"
|
| 26 |
+
|
| 27 |
+
MIN_AGE = 60
|
| 28 |
+
CLASS_NAMES = ["CN", "VMD", "AD"]
|
| 29 |
+
|
| 30 |
+
# subject dir looks like discN/OAS1_0043_MR1/
|
| 31 |
+
SUBJECT_RE = re.compile(r"OAS1_\d{4}_MR1")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _parse_txt(txt_path: Path) -> dict:
|
| 35 |
+
"""Parse the OAS1_XXXX_MR1.txt header block into a flat dict.
|
| 36 |
+
|
| 37 |
+
Fields are 'KEY: value'. Empty values (young subjects lack CDR/Educ/SES)
|
| 38 |
+
become None. We only read the top demographic block; per-scan blocks below
|
| 39 |
+
repeat 'TYPE:'/'TR:' etc. and are ignored (we stop at the first scan block).
|
| 40 |
+
"""
|
| 41 |
+
fields: dict[str, str] = {}
|
| 42 |
+
for raw_line in txt_path.read_text(errors="ignore").splitlines():
|
| 43 |
+
if raw_line.strip().startswith("mpr-") or raw_line.strip().startswith("SCAN NUMBER"):
|
| 44 |
+
break # reached per-scan section; demographics are all above
|
| 45 |
+
if ":" not in raw_line:
|
| 46 |
+
continue
|
| 47 |
+
key, _, val = raw_line.partition(":")
|
| 48 |
+
key = key.strip().upper()
|
| 49 |
+
val = val.strip()
|
| 50 |
+
if key in {"SESSION ID", "AGE", "M/F", "HAND", "EDUC", "SES",
|
| 51 |
+
"CDR", "MMSE", "ETIV", "ASF", "NWBV"}:
|
| 52 |
+
fields[key] = val if val != "" else None
|
| 53 |
+
return fields
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _to_float(v):
|
| 57 |
+
if v is None or v == "":
|
| 58 |
+
return None
|
| 59 |
+
try:
|
| 60 |
+
return float(v)
|
| 61 |
+
except ValueError:
|
| 62 |
+
return None
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _cdr_to_class(cdr: float | None) -> int | None:
|
| 66 |
+
if cdr is None:
|
| 67 |
+
return None
|
| 68 |
+
if cdr == 0.0:
|
| 69 |
+
return 0 # CN
|
| 70 |
+
if cdr == 0.5:
|
| 71 |
+
return 1 # VMD / very mild dementia (NOT clinical MCI)
|
| 72 |
+
if cdr >= 1.0:
|
| 73 |
+
return 2 # AD (mild/moderate dementia)
|
| 74 |
+
return None
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _find_masked_volume(subject_dir: Path) -> Path | None:
|
| 78 |
+
hits = glob.glob(str(subject_dir / "PROCESSED" / "MPRAGE" / "T88_111"
|
| 79 |
+
/ "*_111_t88_masked_gfc.img"))
|
| 80 |
+
return Path(hits[0]) if hits else None
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def scan_subjects(raw_dir: Path = RAW) -> pd.DataFrame:
|
| 84 |
+
"""Walk extracted discs, parse every subject's txt + locate its masked volume.
|
| 85 |
+
|
| 86 |
+
Returns the FULL table (all ages, all CDR states) before cohort filtering,
|
| 87 |
+
so the caller can report how many subjects each filter removes.
|
| 88 |
+
"""
|
| 89 |
+
rows = []
|
| 90 |
+
seen: set[str] = set()
|
| 91 |
+
for txt in sorted(raw_dir.glob("disc*/OAS1_*_MR1/OAS1_*_MR1.txt")):
|
| 92 |
+
sid_session = txt.parent.name # OAS1_0043_MR1
|
| 93 |
+
subject_id = sid_session.replace("_MR1", "") # OAS1_0043
|
| 94 |
+
if subject_id in seen:
|
| 95 |
+
continue # one row per subject; ignore any duplicate session dirs
|
| 96 |
+
seen.add(subject_id)
|
| 97 |
+
|
| 98 |
+
f = _parse_txt(txt)
|
| 99 |
+
vol = _find_masked_volume(txt.parent)
|
| 100 |
+
cdr = _to_float(f.get("CDR"))
|
| 101 |
+
rows.append({
|
| 102 |
+
"subject_id": subject_id,
|
| 103 |
+
"session_id": sid_session,
|
| 104 |
+
"age": _to_float(f.get("AGE")),
|
| 105 |
+
"sex": 1 if (f.get("M/F") or "").lower().startswith("m") else 0,
|
| 106 |
+
"sex_str": f.get("M/F"),
|
| 107 |
+
"education": _to_float(f.get("EDUC")),
|
| 108 |
+
"ses": _to_float(f.get("SES")),
|
| 109 |
+
"cdr": cdr,
|
| 110 |
+
"mmse": _to_float(f.get("MMSE")),
|
| 111 |
+
"etiv": _to_float(f.get("ETIV")),
|
| 112 |
+
"nwbv": _to_float(f.get("NWBV")),
|
| 113 |
+
"asf": _to_float(f.get("ASF")),
|
| 114 |
+
"class_id": _cdr_to_class(cdr),
|
| 115 |
+
"volume_path": str(vol) if vol else None,
|
| 116 |
+
})
|
| 117 |
+
return pd.DataFrame(rows)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def build_cohort(raw_dir: Path = RAW, min_age: int = MIN_AGE) -> tuple[pd.DataFrame, dict]:
|
| 121 |
+
"""Apply the cohort protocol and return (clean_df, provenance_stats)."""
|
| 122 |
+
full = scan_subjects(raw_dir)
|
| 123 |
+
stats = {"n_subjects_total": len(full)}
|
| 124 |
+
|
| 125 |
+
# must have a CDR-derived label (drops young no-assessment subjects)
|
| 126 |
+
has_label = full[full["class_id"].notna()].copy()
|
| 127 |
+
stats["n_with_cdr_label"] = len(has_label)
|
| 128 |
+
|
| 129 |
+
# must have a readable masked volume
|
| 130 |
+
has_vol = has_label[has_label["volume_path"].notna()].copy()
|
| 131 |
+
stats["n_with_volume"] = len(has_vol)
|
| 132 |
+
|
| 133 |
+
# age >= min_age (break the age shortcut)
|
| 134 |
+
cohort = has_vol[has_vol["age"] >= min_age].copy()
|
| 135 |
+
stats["n_age_ge_%d" % min_age] = len(cohort)
|
| 136 |
+
|
| 137 |
+
cohort["class_id"] = cohort["class_id"].astype(int)
|
| 138 |
+
cohort = cohort.sort_values("subject_id").reset_index(drop=True)
|
| 139 |
+
|
| 140 |
+
stats["class_counts"] = {
|
| 141 |
+
CLASS_NAMES[i]: int((cohort["class_id"] == i).sum()) for i in range(3)
|
| 142 |
+
}
|
| 143 |
+
stats["age_bands"] = {
|
| 144 |
+
"60-69": int(((cohort.age >= 60) & (cohort.age < 70)).sum()),
|
| 145 |
+
"70-79": int(((cohort.age >= 70) & (cohort.age < 80)).sum()),
|
| 146 |
+
"80+": int((cohort.age >= 80).sum()),
|
| 147 |
+
}
|
| 148 |
+
stats["sex_counts"] = {
|
| 149 |
+
"M": int((cohort.sex == 1).sum()), "F": int((cohort.sex == 0).sum()),
|
| 150 |
+
}
|
| 151 |
+
stats["missing"] = {
|
| 152 |
+
c: int(cohort[c].isna().sum()) for c in ["education", "ses", "etiv", "nwbv", "asf", "mmse"]
|
| 153 |
+
}
|
| 154 |
+
return cohort, stats
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def main():
|
| 158 |
+
META_DIR.mkdir(parents=True, exist_ok=True)
|
| 159 |
+
cohort, stats = build_cohort()
|
| 160 |
+
|
| 161 |
+
# the model-input columns exclude cdr & mmse (leakage); keep them in the CSV
|
| 162 |
+
# for analysis but the datasets module must not read them as features.
|
| 163 |
+
out_cols = ["subject_id", "session_id", "age", "sex", "education", "ses",
|
| 164 |
+
"etiv", "nwbv", "asf", "cdr", "mmse", "class_id", "volume_path"]
|
| 165 |
+
cohort[out_cols].to_csv(META_DIR / "subjects_clean.csv", index=False)
|
| 166 |
+
|
| 167 |
+
import json
|
| 168 |
+
(META_DIR / "dataset_statistics.json").write_text(json.dumps(stats, indent=2))
|
| 169 |
+
print(json.dumps(stats, indent=2))
|
| 170 |
+
print(f"\nwrote {META_DIR/'subjects_clean.csv'} ({len(cohort)} subjects)")
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
if __name__ == "__main__":
|
| 174 |
+
main()
|
src/trifuse/data/datasets.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PyTorch datasets for the three modalities.
|
| 2 |
+
|
| 3 |
+
All datasets return a uniform batch dict so the trainer is modality-agnostic:
|
| 4 |
+
{"slices": (T,3,H,W) | "vol": (1,D,H,W), "tab": (F,), "y": int, "subject_id": str}
|
| 5 |
+
|
| 6 |
+
Tabular features are standardized with statistics FIT ON THE TRAINING FOLD ONLY
|
| 7 |
+
(passed in as `tab_stats`) — never on the full dataset — to prevent leakage.
|
| 8 |
+
Missing tabular values are median/mode-imputed from training-fold stats too.
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
import pandas as pd
|
| 16 |
+
import torch
|
| 17 |
+
from torch.utils.data import Dataset
|
| 18 |
+
|
| 19 |
+
ROOT = Path(__file__).resolve().parents[3]
|
| 20 |
+
PROC2D = ROOT / "data" / "processed_2d"
|
| 21 |
+
PROC3D = ROOT / "data" / "processed_3d"
|
| 22 |
+
|
| 23 |
+
# imagenet stats for pretrained backbones (applied after per-volume z-score,
|
| 24 |
+
# so slices are re-scaled into the pretrained input regime)
|
| 25 |
+
IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
|
| 26 |
+
IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def fit_tab_stats(df: pd.DataFrame, features) -> dict:
|
| 30 |
+
"""Compute train-fold imputation + standardization stats for tab features."""
|
| 31 |
+
stats = {}
|
| 32 |
+
for f in features:
|
| 33 |
+
col = df[f].astype(float)
|
| 34 |
+
med = float(col.median())
|
| 35 |
+
vals = col.fillna(med)
|
| 36 |
+
mu, sd = float(vals.mean()), float(vals.std())
|
| 37 |
+
stats[f] = {"median": med, "mean": mu, "std": sd if sd > 1e-6 else 1.0}
|
| 38 |
+
return stats
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _encode_tab(row, features, stats) -> np.ndarray:
|
| 42 |
+
out = np.zeros(len(features), dtype=np.float32)
|
| 43 |
+
for i, f in enumerate(features):
|
| 44 |
+
v = row[f]
|
| 45 |
+
s = stats[f]
|
| 46 |
+
if pd.isna(v):
|
| 47 |
+
v = s["median"]
|
| 48 |
+
out[i] = (float(v) - s["mean"]) / s["std"]
|
| 49 |
+
return out
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class SliceDataset(Dataset):
|
| 53 |
+
"""2D / 2.5D tri-planar slices. planes/n_slices select which of the 27 to load.
|
| 54 |
+
|
| 55 |
+
modality:
|
| 56 |
+
slice2d -> single center axial slice returned as (1,3,H,W)
|
| 57 |
+
slice25d -> the requested planes x n_slices as (T,3,H,W)
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
def __init__(self, df, features, tab_stats, planes=("axial",), n_slices=9,
|
| 61 |
+
modality="slice25d", augment=False):
|
| 62 |
+
self.df = df.reset_index(drop=True)
|
| 63 |
+
self.features = features
|
| 64 |
+
self.stats = tab_stats
|
| 65 |
+
self.planes = planes
|
| 66 |
+
self.n_slices = n_slices
|
| 67 |
+
self.modality = modality
|
| 68 |
+
self.augment = augment
|
| 69 |
+
|
| 70 |
+
def __len__(self):
|
| 71 |
+
return len(self.df)
|
| 72 |
+
|
| 73 |
+
def _load_plane(self, sid, plane):
|
| 74 |
+
arr = np.load(PROC2D / sid / plane / "slices.npy").astype(np.float32) # (9,H,W)
|
| 75 |
+
# select n_slices centered subset if fewer requested
|
| 76 |
+
if self.n_slices < arr.shape[0]:
|
| 77 |
+
start = (arr.shape[0] - self.n_slices) // 2
|
| 78 |
+
arr = arr[start:start + self.n_slices]
|
| 79 |
+
return arr
|
| 80 |
+
|
| 81 |
+
def _to_rgb(self, sl): # (H,W) -> (3,H,W) imagenet-normalized
|
| 82 |
+
x = np.stack([sl, sl, sl], axis=0)
|
| 83 |
+
x = (x - IMAGENET_MEAN[:, None, None]) / IMAGENET_STD[:, None, None]
|
| 84 |
+
return x.astype(np.float32)
|
| 85 |
+
|
| 86 |
+
def _augment(self, arr): # light aug on a (n,H,W) stack
|
| 87 |
+
if not self.augment:
|
| 88 |
+
return arr
|
| 89 |
+
if np.random.rand() < 0.5:
|
| 90 |
+
arr = arr + np.random.normal(0, 0.02, arr.shape).astype(np.float32)
|
| 91 |
+
if np.random.rand() < 0.5:
|
| 92 |
+
arr = arr * np.random.uniform(0.95, 1.05)
|
| 93 |
+
return arr
|
| 94 |
+
|
| 95 |
+
def __getitem__(self, idx):
|
| 96 |
+
row = self.df.iloc[idx]
|
| 97 |
+
sid = row["subject_id"]
|
| 98 |
+
if self.modality == "slice2d":
|
| 99 |
+
axial = self._load_plane(sid, "axial")
|
| 100 |
+
center = axial[len(axial) // 2]
|
| 101 |
+
slices = self._to_rgb(self._augment(center[None]))[0][None] # (1,3,H,W)
|
| 102 |
+
else:
|
| 103 |
+
planes = []
|
| 104 |
+
for p in self.planes:
|
| 105 |
+
stack = self._augment(self._load_plane(sid, p))
|
| 106 |
+
planes.append(np.stack([self._to_rgb(s) for s in stack])) # (n,3,H,W)
|
| 107 |
+
slices = np.concatenate(planes, axis=0) # (T,3,H,W)
|
| 108 |
+
return {
|
| 109 |
+
"slices": torch.from_numpy(slices),
|
| 110 |
+
"tab": torch.from_numpy(_encode_tab(row, self.features, self.stats)),
|
| 111 |
+
"y": int(row["class_id"]),
|
| 112 |
+
"subject_id": sid,
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class VolumeDataset(Dataset):
|
| 117 |
+
"""Whole-brain 3D volumes for CNN3D / transformer / hybrid models."""
|
| 118 |
+
|
| 119 |
+
def __init__(self, df, features, tab_stats, target="cnn3d", augment=False):
|
| 120 |
+
self.df = df.reset_index(drop=True)
|
| 121 |
+
self.features = features
|
| 122 |
+
self.stats = tab_stats
|
| 123 |
+
self.target = target # cnn3d (128^3) or tf3d (96x112x112)
|
| 124 |
+
self.augment = augment
|
| 125 |
+
|
| 126 |
+
def __len__(self):
|
| 127 |
+
return len(self.df)
|
| 128 |
+
|
| 129 |
+
def __getitem__(self, idx):
|
| 130 |
+
row = self.df.iloc[idx]
|
| 131 |
+
sid = row["subject_id"]
|
| 132 |
+
vol = np.load(PROC3D / self.target / f"{sid}.npy").astype(np.float32)
|
| 133 |
+
if self.augment and np.random.rand() < 0.5:
|
| 134 |
+
vol = vol + np.random.normal(0, 0.02, vol.shape).astype(np.float32)
|
| 135 |
+
return {
|
| 136 |
+
"vol": torch.from_numpy(vol[None]), # (1,D,H,W)
|
| 137 |
+
"tab": torch.from_numpy(_encode_tab(row, self.features, self.stats)),
|
| 138 |
+
"y": int(row["class_id"]),
|
| 139 |
+
"subject_id": sid,
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class TabularDataset(Dataset):
|
| 144 |
+
def __init__(self, df, features, tab_stats):
|
| 145 |
+
self.df = df.reset_index(drop=True)
|
| 146 |
+
self.features = features
|
| 147 |
+
self.stats = tab_stats
|
| 148 |
+
|
| 149 |
+
def __len__(self):
|
| 150 |
+
return len(self.df)
|
| 151 |
+
|
| 152 |
+
def __getitem__(self, idx):
|
| 153 |
+
row = self.df.iloc[idx]
|
| 154 |
+
return {
|
| 155 |
+
"tab": torch.from_numpy(_encode_tab(row, self.features, self.stats)),
|
| 156 |
+
"y": int(row["class_id"]),
|
| 157 |
+
"subject_id": row["subject_id"],
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def collate(items):
|
| 162 |
+
"""Uniform collate that stacks whichever tensors are present."""
|
| 163 |
+
out = {"y": torch.tensor([it["y"] for it in items]),
|
| 164 |
+
"subject_id": [it["subject_id"] for it in items]}
|
| 165 |
+
for key in ("slices", "vol", "tab"):
|
| 166 |
+
if key in items[0]:
|
| 167 |
+
out[key] = torch.stack([it[key] for it in items])
|
| 168 |
+
return out
|
src/trifuse/data/download.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Download + extract OASIS-1 cross-sectional dataset (discs 1-12).
|
| 3 |
+
|
| 4 |
+
The WashU host throttles per-connection (~48 KB/s single) but not in aggregate:
|
| 5 |
+
16 segmented connections reach ~1.9 MB/s. We use aria2c for segmented download
|
| 6 |
+
+ built-in resume. Idempotent: skips discs already extracted.
|
| 7 |
+
"""
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
import tarfile
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
RAW = Path(__file__).resolve().parents[3] / "data" / "raw"
|
| 14 |
+
BASE = "https://download.nrg.wustl.edu/data"
|
| 15 |
+
N_DISCS = 12
|
| 16 |
+
MIN_DISC_BYTES = 1_000_000_000
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def download_all() -> None:
|
| 20 |
+
"""aria2c downloads all discs: -x16 conns/host, -s16 segments, -j3 files at once."""
|
| 21 |
+
urls = [f"{BASE}/oasis_cross-sectional_disc{i}.tar.gz" for i in range(1, N_DISCS + 1)]
|
| 22 |
+
(RAW / "urls.txt").write_text("\n".join(urls) + "\n")
|
| 23 |
+
subprocess.run(
|
| 24 |
+
["aria2c", "-x16", "-s16", "-j3", "-c", "-k", "1M",
|
| 25 |
+
"--retry-wait=5", "--max-tries=0", # 0 = infinite retries
|
| 26 |
+
"--timeout=30", "--connect-timeout=30",
|
| 27 |
+
"--summary-interval=30", "--console-log-level=warn",
|
| 28 |
+
"-d", str(RAW), "-i", str(RAW / "urls.txt")],
|
| 29 |
+
check=True,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def extract_all() -> None:
|
| 34 |
+
for i in range(1, N_DISCS + 1):
|
| 35 |
+
tar_path = RAW / f"oasis_cross-sectional_disc{i}.tar.gz"
|
| 36 |
+
marker = tar_path.with_suffix(".extracted")
|
| 37 |
+
if marker.exists():
|
| 38 |
+
print(f"[skip] disc{i} already extracted", flush=True)
|
| 39 |
+
continue
|
| 40 |
+
if not (tar_path.exists() and tar_path.stat().st_size >= MIN_DISC_BYTES):
|
| 41 |
+
sys.exit(f"disc{i} missing/incomplete: {tar_path}")
|
| 42 |
+
print(f"[tar ] disc{i}", flush=True)
|
| 43 |
+
with tarfile.open(tar_path, "r:gz") as t:
|
| 44 |
+
t.extractall(RAW, filter="data")
|
| 45 |
+
marker.touch()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def main() -> None:
|
| 49 |
+
RAW.mkdir(parents=True, exist_ok=True)
|
| 50 |
+
download_all()
|
| 51 |
+
extract_all()
|
| 52 |
+
print("[done] all discs downloaded + extracted", flush=True)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
if __name__ == "__main__":
|
| 56 |
+
main()
|
src/trifuse/data/preprocess_2d.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""2.5D tri-planar slice extraction from processed 3D volumes.
|
| 2 |
+
|
| 3 |
+
From each normalized volume we take 3 planes (axial, coronal, sagittal) x 9 slices
|
| 4 |
+
at depth fractions 30..70%, giving 27 slices per subject. Each slice is resized to
|
| 5 |
+
224x224 and saved as float16 .npy. The channel dimension (3, for pretrained CNN
|
| 6 |
+
compatibility) is added at load time, not stored, to save disk.
|
| 7 |
+
|
| 8 |
+
Depth fractions are computed on the *cropped-normalized* volume that preprocess_3d
|
| 9 |
+
produced (background already trimmed), so 50% lands near brain center.
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
from scipy.ndimage import zoom
|
| 18 |
+
|
| 19 |
+
ROOT = Path(__file__).resolve().parents[3]
|
| 20 |
+
PLANES = ("axial", "coronal", "sagittal")
|
| 21 |
+
DEPTH_FRACTIONS = (0.30, 0.35, 0.40, 0.45, 0.50, 0.55, 0.60, 0.65, 0.70)
|
| 22 |
+
SLICE_SIZE = 224
|
| 23 |
+
|
| 24 |
+
# volume axes after as_closest_canonical (RAS): 0=L-R (sagittal), 1=P-A (coronal),
|
| 25 |
+
# 2=I-S (axial). A slice through an axis shows the *other* two dims.
|
| 26 |
+
PLANE_AXIS = {"sagittal": 0, "coronal": 1, "axial": 2}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _resize2d(sl: np.ndarray, size: int = SLICE_SIZE) -> np.ndarray:
|
| 30 |
+
factors = [size / sl.shape[0], size / sl.shape[1]]
|
| 31 |
+
out = zoom(sl, factors, order=1)
|
| 32 |
+
out = out[:size, :size]
|
| 33 |
+
pad = [(0, size - out.shape[0]), (0, size - out.shape[1])]
|
| 34 |
+
if pad[0][1] or pad[1][1]:
|
| 35 |
+
out = np.pad(out, pad)
|
| 36 |
+
return out.astype(np.float16)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def extract_slices(vol: np.ndarray) -> dict[str, np.ndarray]:
|
| 40 |
+
"""Return {plane: (9, 224, 224) float16} for one volume."""
|
| 41 |
+
out = {}
|
| 42 |
+
for plane, axis in PLANE_AXIS.items():
|
| 43 |
+
n = vol.shape[axis]
|
| 44 |
+
slabs = []
|
| 45 |
+
for frac in DEPTH_FRACTIONS:
|
| 46 |
+
idx = int(round(frac * (n - 1)))
|
| 47 |
+
sl = np.take(vol, idx, axis=axis)
|
| 48 |
+
slabs.append(_resize2d(sl))
|
| 49 |
+
out[plane] = np.stack(slabs) # (9, 224, 224)
|
| 50 |
+
return out
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def main() -> None:
|
| 54 |
+
ap = argparse.ArgumentParser()
|
| 55 |
+
ap.add_argument("--subjects_csv", default="data/metadata/subjects_clean.csv")
|
| 56 |
+
ap.add_argument("--vol_dir", default="data/processed_3d/cnn3d",
|
| 57 |
+
help="which processed-3d target to slice from (uses 128^3)")
|
| 58 |
+
ap.add_argument("--out_root", default="data/processed_2d")
|
| 59 |
+
ap.add_argument("--limit", type=int, default=0)
|
| 60 |
+
args = ap.parse_args()
|
| 61 |
+
|
| 62 |
+
import pandas as pd
|
| 63 |
+
|
| 64 |
+
df = pd.read_csv(args.subjects_csv)
|
| 65 |
+
if args.limit:
|
| 66 |
+
df = df.head(args.limit)
|
| 67 |
+
vol_dir = Path(args.vol_dir)
|
| 68 |
+
out_root = Path(args.out_root)
|
| 69 |
+
|
| 70 |
+
n_ok = 0
|
| 71 |
+
for _, row in df.iterrows():
|
| 72 |
+
sid = row["subject_id"]
|
| 73 |
+
vpath = vol_dir / f"{sid}.npy"
|
| 74 |
+
if not vpath.exists():
|
| 75 |
+
print(f"MISS volume for {sid}")
|
| 76 |
+
continue
|
| 77 |
+
vol = np.load(vpath)
|
| 78 |
+
slices = extract_slices(vol)
|
| 79 |
+
for plane, arr in slices.items():
|
| 80 |
+
d = out_root / sid / plane
|
| 81 |
+
d.mkdir(parents=True, exist_ok=True)
|
| 82 |
+
np.save(d / "slices.npy", arr)
|
| 83 |
+
n_ok += 1
|
| 84 |
+
if n_ok % 25 == 0:
|
| 85 |
+
print(f" sliced {n_ok}/{len(df)}")
|
| 86 |
+
print(f"done: {n_ok}/{len(df)} subjects -> {out_root}")
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
if __name__ == "__main__":
|
| 90 |
+
main()
|
src/trifuse/data/preprocess_3d.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""3D preprocessing: OASIS-1 Analyze volume -> normalized .npy.
|
| 2 |
+
|
| 3 |
+
Pipeline per subject (one volume, the atlas-registered brain-masked gain-field-
|
| 4 |
+
corrected average): read Analyze (.hdr/.img) -> canonical orientation -> nonzero
|
| 5 |
+
bounding-box crop -> percentile clip (0.5-99.5 on brain voxels) -> z-score on
|
| 6 |
+
brain -> resize to target. Two targets are written:
|
| 7 |
+
- 128^3 for 3D CNN (resnet3d)
|
| 8 |
+
- 96x112x112 for 3D transformer/hybrid (swin3d, hcct, vswin_lite)
|
| 9 |
+
|
| 10 |
+
Saved as float32 .npy under processed_3d/<target>/<subject_id>.npy.
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
import nibabel as nib
|
| 18 |
+
import numpy as np
|
| 19 |
+
from scipy.ndimage import zoom
|
| 20 |
+
|
| 21 |
+
TARGETS = {
|
| 22 |
+
"cnn3d": (128, 128, 128),
|
| 23 |
+
"tf3d": (96, 112, 112),
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def load_analyze(hdr_path: Path) -> np.ndarray:
|
| 28 |
+
"""Load an Analyze/NIfTI volume as float32, reoriented to canonical (RAS)."""
|
| 29 |
+
img = nib.load(str(hdr_path))
|
| 30 |
+
img = nib.as_closest_canonical(img) # consistent orientation across subjects
|
| 31 |
+
arr = np.asanyarray(img.dataobj).astype(np.float32)
|
| 32 |
+
arr = np.squeeze(arr) # OASIS T88 volumes carry a trailing singleton axis
|
| 33 |
+
return arr
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def nonzero_bbox_crop(vol: np.ndarray) -> np.ndarray:
|
| 37 |
+
mask = vol > 0
|
| 38 |
+
if not mask.any():
|
| 39 |
+
return vol
|
| 40 |
+
coords = np.array(np.nonzero(mask))
|
| 41 |
+
lo = coords.min(axis=1)
|
| 42 |
+
hi = coords.max(axis=1) + 1
|
| 43 |
+
return vol[lo[0]:hi[0], lo[1]:hi[1], lo[2]:hi[2]]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def clip_and_zscore(vol: np.ndarray) -> np.ndarray:
|
| 47 |
+
brain = vol[vol > 0]
|
| 48 |
+
if brain.size == 0:
|
| 49 |
+
return vol
|
| 50 |
+
lo, hi = np.percentile(brain, [0.5, 99.5])
|
| 51 |
+
vol = np.clip(vol, lo, hi)
|
| 52 |
+
brain = vol[vol > 0]
|
| 53 |
+
mu, sd = brain.mean(), brain.std()
|
| 54 |
+
if sd < 1e-6:
|
| 55 |
+
sd = 1.0
|
| 56 |
+
out = (vol - mu) / sd
|
| 57 |
+
out[vol <= 0] = 0.0 # keep background at 0 after normalization
|
| 58 |
+
return out.astype(np.float32)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def resize_to(vol: np.ndarray, shape: tuple[int, int, int]) -> np.ndarray:
|
| 62 |
+
factors = [s / v for s, v in zip(shape, vol.shape)]
|
| 63 |
+
out = zoom(vol, factors, order=1) # trilinear
|
| 64 |
+
# guard against off-by-one from rounding
|
| 65 |
+
out = out[: shape[0], : shape[1], : shape[2]]
|
| 66 |
+
pad = [(0, s - o) for s, o in zip(shape, out.shape)]
|
| 67 |
+
if any(p[1] > 0 for p in pad):
|
| 68 |
+
out = np.pad(out, pad)
|
| 69 |
+
return out.astype(np.float32)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def preprocess_one(hdr_path: Path) -> dict[str, np.ndarray]:
|
| 73 |
+
vol = load_analyze(hdr_path)
|
| 74 |
+
vol = nonzero_bbox_crop(vol)
|
| 75 |
+
vol = clip_and_zscore(vol)
|
| 76 |
+
return {name: resize_to(vol, shape) for name, shape in TARGETS.items()}
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def main() -> None:
|
| 80 |
+
ap = argparse.ArgumentParser()
|
| 81 |
+
ap.add_argument("--subjects_csv", default="data/metadata/subjects_clean.csv")
|
| 82 |
+
ap.add_argument("--out_root", default="data/processed_3d")
|
| 83 |
+
ap.add_argument("--limit", type=int, default=0, help="process only first N (debug)")
|
| 84 |
+
args = ap.parse_args()
|
| 85 |
+
|
| 86 |
+
import pandas as pd
|
| 87 |
+
|
| 88 |
+
df = pd.read_csv(args.subjects_csv)
|
| 89 |
+
if args.limit:
|
| 90 |
+
df = df.head(args.limit)
|
| 91 |
+
out_root = Path(args.out_root)
|
| 92 |
+
for name in TARGETS:
|
| 93 |
+
(out_root / name).mkdir(parents=True, exist_ok=True)
|
| 94 |
+
|
| 95 |
+
n_ok = 0
|
| 96 |
+
for _, row in df.iterrows():
|
| 97 |
+
sid = row["subject_id"]
|
| 98 |
+
hdr = Path(row["volume_path"])
|
| 99 |
+
try:
|
| 100 |
+
outs = preprocess_one(hdr)
|
| 101 |
+
except Exception as e: # noqa: BLE001 - report and continue
|
| 102 |
+
print(f"FAIL {sid}: {e}")
|
| 103 |
+
continue
|
| 104 |
+
for name, arr in outs.items():
|
| 105 |
+
np.save(out_root / name / f"{sid}.npy", arr)
|
| 106 |
+
n_ok += 1
|
| 107 |
+
if n_ok % 25 == 0:
|
| 108 |
+
print(f" processed {n_ok}/{len(df)}")
|
| 109 |
+
print(f"done: {n_ok}/{len(df)} volumes -> {out_root}")
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
if __name__ == "__main__":
|
| 113 |
+
main()
|
src/trifuse/data/splits.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Subject-level repeated stratified cross-validation splits.
|
| 2 |
+
|
| 3 |
+
Leakage prevention is the whole point: splitting happens at the subject level (one
|
| 4 |
+
volume per subject, so no subject appears in both train and test). Stratification
|
| 5 |
+
uses a composite key of class x age-band x sex so folds stay balanced on all three.
|
| 6 |
+
|
| 7 |
+
For each of 3 seeds we build a 5-fold split (15 evaluations total). Within each
|
| 8 |
+
outer fold, the training portion is further split 80/20 into train/val for
|
| 9 |
+
early stopping. All fitting (impute/standardize/class-weights) must happen on the
|
| 10 |
+
train portion only -- handled downstream, not here.
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
import pandas as pd
|
| 16 |
+
from sklearn.model_selection import StratifiedKFold, train_test_split
|
| 17 |
+
|
| 18 |
+
SEEDS = [7, 13, 21]
|
| 19 |
+
N_FOLDS = 5
|
| 20 |
+
VAL_FRACTION = 0.2
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def age_band(age: float) -> str:
|
| 24 |
+
if age < 70:
|
| 25 |
+
return "60s"
|
| 26 |
+
if age < 80:
|
| 27 |
+
return "70s"
|
| 28 |
+
return "80+"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _strata_key(df: pd.DataFrame) -> pd.Series:
|
| 32 |
+
bands = df["age"].apply(age_band)
|
| 33 |
+
return df["class_id"].astype(str) + "_" + bands + "_" + df["sex"].astype(str)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _merge_rare(strata: pd.Series, min_count: int = 2) -> pd.Series:
|
| 37 |
+
"""StratifiedKFold needs every stratum to have >= n_splits members ideally;
|
| 38 |
+
collapse ultra-rare composite strata down to the class label alone."""
|
| 39 |
+
counts = strata.value_counts()
|
| 40 |
+
rare = set(counts[counts < min_count].index)
|
| 41 |
+
return strata.map(lambda s: s.split("_")[0] if s in rare else s)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def make_folds(df: pd.DataFrame) -> pd.DataFrame:
|
| 45 |
+
"""Return a long-form dataframe: one row per (subject, seed) giving fold id
|
| 46 |
+
and the train/val/test role for the fold where the subject is in test.
|
| 47 |
+
|
| 48 |
+
Output columns: subject_id, seed, fold (int, the test fold this subject
|
| 49 |
+
belongs to). Downstream, evaluation `(seed, fold)` uses fold==test, and the
|
| 50 |
+
remaining subjects are the train pool (val carved out per model run).
|
| 51 |
+
"""
|
| 52 |
+
records = []
|
| 53 |
+
strata_full = _merge_rare(_strata_key(df))
|
| 54 |
+
for seed in SEEDS:
|
| 55 |
+
skf = StratifiedKFold(n_splits=N_FOLDS, shuffle=True, random_state=seed)
|
| 56 |
+
fold_of = np.empty(len(df), dtype=int)
|
| 57 |
+
for fold_idx, (_, test_idx) in enumerate(skf.split(df, strata_full)):
|
| 58 |
+
fold_of[test_idx] = fold_idx
|
| 59 |
+
for sid, fold in zip(df["subject_id"].to_numpy(), fold_of):
|
| 60 |
+
records.append({"subject_id": sid, "seed": seed, "fold": int(fold)})
|
| 61 |
+
return pd.DataFrame.from_records(records)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def split_for(folds: pd.DataFrame, df: pd.DataFrame, seed: int, fold: int):
|
| 65 |
+
"""Return (train_ids, val_ids, test_ids) for one (seed, fold) evaluation.
|
| 66 |
+
|
| 67 |
+
Test = subjects whose assigned fold == `fold` for this seed. Remaining are
|
| 68 |
+
split into train/val (stratified on class) using the same seed for
|
| 69 |
+
reproducibility.
|
| 70 |
+
"""
|
| 71 |
+
fs = folds[folds["seed"] == seed]
|
| 72 |
+
test_ids = fs.loc[fs["fold"] == fold, "subject_id"].tolist()
|
| 73 |
+
trainval_ids = fs.loc[fs["fold"] != fold, "subject_id"].tolist()
|
| 74 |
+
|
| 75 |
+
sub = df[df["subject_id"].isin(trainval_ids)]
|
| 76 |
+
strat = sub["class_id"]
|
| 77 |
+
train_ids, val_ids = train_test_split(
|
| 78 |
+
sub["subject_id"].tolist(),
|
| 79 |
+
test_size=VAL_FRACTION,
|
| 80 |
+
random_state=seed,
|
| 81 |
+
stratify=strat,
|
| 82 |
+
)
|
| 83 |
+
return train_ids, val_ids, test_ids
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def assert_no_leakage(train_ids, val_ids, test_ids) -> None:
|
| 87 |
+
s_tr, s_va, s_te = set(train_ids), set(val_ids), set(test_ids)
|
| 88 |
+
assert not (s_tr & s_te), "train/test subject overlap"
|
| 89 |
+
assert not (s_tr & s_va), "train/val subject overlap"
|
| 90 |
+
assert not (s_va & s_te), "val/test subject overlap"
|
src/trifuse/eval/__init__.py
ADDED
|
File without changes
|
src/trifuse/eval/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (134 Bytes). View file
|
|
|
src/trifuse/eval/__pycache__/metrics.cpython-312.pyc
ADDED
|
Binary file (3.49 kB). View file
|
|
|
src/trifuse/eval/__pycache__/runner.cpython-312.pyc
ADDED
|
Binary file (10.2 kB). View file
|
|
|
src/trifuse/eval/__pycache__/stats.cpython-312.pyc
ADDED
|
Binary file (4.62 kB). View file
|
|
|
src/trifuse/eval/metrics.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Evaluation metrics for 3-class Alzheimer staging.
|
| 2 |
+
|
| 3 |
+
Primary metric is Macro-F1 (class imbalance: AD is the minority). All metrics
|
| 4 |
+
computed from (y_true, y_pred) label arrays plus optional probabilities for AUC.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
from sklearn.metrics import (
|
| 10 |
+
accuracy_score,
|
| 11 |
+
balanced_accuracy_score,
|
| 12 |
+
confusion_matrix,
|
| 13 |
+
f1_score,
|
| 14 |
+
precision_score,
|
| 15 |
+
recall_score,
|
| 16 |
+
roc_auc_score,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
CLASS_NAMES = ["CN", "VMD", "AD"] # 0, 1, 2
|
| 20 |
+
N_CLASSES = 3
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def compute_metrics(
|
| 24 |
+
y_true: np.ndarray,
|
| 25 |
+
y_pred: np.ndarray,
|
| 26 |
+
y_prob: np.ndarray | None = None,
|
| 27 |
+
) -> dict[str, float]:
|
| 28 |
+
"""Return the full metric dict for one set of predictions.
|
| 29 |
+
|
| 30 |
+
y_prob: (N, 3) class probabilities; if given, OvR macro-AUC is added.
|
| 31 |
+
"""
|
| 32 |
+
y_true = np.asarray(y_true).astype(int)
|
| 33 |
+
y_pred = np.asarray(y_pred).astype(int)
|
| 34 |
+
labels = list(range(N_CLASSES))
|
| 35 |
+
|
| 36 |
+
out: dict[str, float] = {
|
| 37 |
+
"accuracy": float(accuracy_score(y_true, y_pred)),
|
| 38 |
+
"balanced_accuracy": float(balanced_accuracy_score(y_true, y_pred)),
|
| 39 |
+
"macro_f1": float(f1_score(y_true, y_pred, labels=labels, average="macro", zero_division=0)),
|
| 40 |
+
"macro_precision": float(precision_score(y_true, y_pred, labels=labels, average="macro", zero_division=0)),
|
| 41 |
+
"macro_recall": float(recall_score(y_true, y_pred, labels=labels, average="macro", zero_division=0)),
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
per_f1 = f1_score(y_true, y_pred, labels=labels, average=None, zero_division=0)
|
| 45 |
+
per_recall = recall_score(y_true, y_pred, labels=labels, average=None, zero_division=0)
|
| 46 |
+
per_prec = precision_score(y_true, y_pred, labels=labels, average=None, zero_division=0)
|
| 47 |
+
for i, name in enumerate(CLASS_NAMES):
|
| 48 |
+
out[f"f1_{name}"] = float(per_f1[i])
|
| 49 |
+
out[f"recall_{name}"] = float(per_recall[i])
|
| 50 |
+
out[f"precision_{name}"] = float(per_prec[i])
|
| 51 |
+
|
| 52 |
+
if y_prob is not None:
|
| 53 |
+
y_prob = np.asarray(y_prob, dtype=float)
|
| 54 |
+
# OvR macro-AUC; guard against a class absent from y_true in this split.
|
| 55 |
+
present = np.unique(y_true)
|
| 56 |
+
if len(present) == N_CLASSES:
|
| 57 |
+
try:
|
| 58 |
+
out["macro_auc"] = float(
|
| 59 |
+
roc_auc_score(y_true, y_prob, multi_class="ovr", average="macro", labels=labels)
|
| 60 |
+
)
|
| 61 |
+
except ValueError:
|
| 62 |
+
out["macro_auc"] = float("nan")
|
| 63 |
+
else:
|
| 64 |
+
out["macro_auc"] = float("nan")
|
| 65 |
+
return out
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def confusion(y_true: np.ndarray, y_pred: np.ndarray) -> np.ndarray:
|
| 69 |
+
return confusion_matrix(np.asarray(y_true).astype(int),
|
| 70 |
+
np.asarray(y_pred).astype(int),
|
| 71 |
+
labels=list(range(N_CLASSES)))
|
src/trifuse/eval/runner.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Experiment runner: the 15-evaluation cross-validation harness.
|
| 2 |
+
|
| 3 |
+
For a given model config, runs every (seed, fold) evaluation:
|
| 4 |
+
1. subject-level train/val/test split (from splits.make_folds)
|
| 5 |
+
2. fit tabular stats on TRAIN ONLY (no leakage)
|
| 6 |
+
3. build modality-appropriate datasets/loaders
|
| 7 |
+
4. train with early stopping on val Macro-F1
|
| 8 |
+
5. predict on the held-out test fold -> persist per-subject OOF rows
|
| 9 |
+
|
| 10 |
+
Hyperparameters are frozen per config; the test fold is NEVER used for selection.
|
| 11 |
+
Results land in results/<name>/: oof.csv (pooled predictions), runs.json (per-run
|
| 12 |
+
metrics), summary.json (mean±std + bootstrap CI).
|
| 13 |
+
|
| 14 |
+
XGBoost models take a separate sklearn path (fit/predict, no torch trainer).
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import json
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import pandas as pd
|
| 23 |
+
import torch
|
| 24 |
+
from torch.utils.data import DataLoader
|
| 25 |
+
|
| 26 |
+
from ..data.datasets import (SliceDataset, VolumeDataset, TabularDataset,
|
| 27 |
+
collate, fit_tab_stats)
|
| 28 |
+
from ..data.splits import make_folds, split_for, assert_no_leakage, SEEDS, N_FOLDS
|
| 29 |
+
from ..models.registry import build_model
|
| 30 |
+
from ..models.baselines_tab import make_xgb
|
| 31 |
+
from ..training.config import TrainConfig
|
| 32 |
+
from ..training.trainer import fit, predict
|
| 33 |
+
from .metrics import compute_metrics
|
| 34 |
+
from .stats import aggregate_runs, bootstrap_ci
|
| 35 |
+
|
| 36 |
+
ROOT = Path(__file__).resolve().parents[3]
|
| 37 |
+
RESULTS = ROOT / "results"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _make_dataset(cfg: TrainConfig, sub_df, tab_stats, augment):
|
| 41 |
+
if cfg.modality == "tabular":
|
| 42 |
+
return TabularDataset(sub_df, cfg.tab_features, tab_stats)
|
| 43 |
+
if cfg.modality == "vol3d":
|
| 44 |
+
target = "tf3d" if cfg.model in ("swin3d", "hcct", "vswin_lite") else "cnn3d"
|
| 45 |
+
return VolumeDataset(sub_df, cfg.tab_features, tab_stats, target=target, augment=augment)
|
| 46 |
+
return SliceDataset(sub_df, cfg.tab_features, tab_stats, planes=tuple(cfg.planes),
|
| 47 |
+
n_slices=cfg.n_slices, modality=cfg.modality, augment=augment)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _loader(ds, cfg, shuffle):
|
| 51 |
+
return DataLoader(ds, batch_size=cfg.batch_size, shuffle=shuffle,
|
| 52 |
+
num_workers=cfg.num_workers, collate_fn=collate,
|
| 53 |
+
pin_memory=True, drop_last=False)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _run_xgb(cfg, df, folds, feature_subset, device=None):
|
| 57 |
+
"""XGBoost path for tabular / confound baselines."""
|
| 58 |
+
oof_rows, run_metrics = [], []
|
| 59 |
+
for seed in SEEDS:
|
| 60 |
+
for fold in range(N_FOLDS):
|
| 61 |
+
tr, va, te = split_for(folds, df, seed, fold)
|
| 62 |
+
assert_no_leakage(tr, va, te)
|
| 63 |
+
train_df = df[df.subject_id.isin(tr + va)]
|
| 64 |
+
test_df = df[df.subject_id.isin(te)]
|
| 65 |
+
stats = fit_tab_stats(train_df, feature_subset)
|
| 66 |
+
|
| 67 |
+
def X(sub):
|
| 68 |
+
return np.stack([
|
| 69 |
+
[(sub.iloc[i][f] if not pd.isna(sub.iloc[i][f]) else stats[f]["median"])
|
| 70 |
+
for f in feature_subset]
|
| 71 |
+
for i in range(len(sub))
|
| 72 |
+
]).astype(np.float32)
|
| 73 |
+
|
| 74 |
+
clf = make_xgb(seed=seed)
|
| 75 |
+
clf.fit(X(train_df), train_df["class_id"].to_numpy())
|
| 76 |
+
prob = clf.predict_proba(X(test_df))
|
| 77 |
+
pred = prob.argmax(1)
|
| 78 |
+
y = test_df["class_id"].to_numpy()
|
| 79 |
+
run_metrics.append(compute_metrics(y, pred, prob))
|
| 80 |
+
for sid, yt, yp, pr in zip(test_df.subject_id, y, pred, prob):
|
| 81 |
+
oof_rows.append({"subject_id": sid, "seed": seed, "fold": fold,
|
| 82 |
+
"y_true": int(yt), "y_pred": int(yp),
|
| 83 |
+
**{f"prob_{k}": float(pr[k]) for k in range(3)}})
|
| 84 |
+
return oof_rows, run_metrics
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _run_torch(cfg, df, folds, device):
|
| 88 |
+
oof_rows, run_metrics = [], []
|
| 89 |
+
for seed in SEEDS:
|
| 90 |
+
for fold in range(N_FOLDS):
|
| 91 |
+
torch.manual_seed(seed)
|
| 92 |
+
tr, va, te = split_for(folds, df, seed, fold)
|
| 93 |
+
assert_no_leakage(tr, va, te)
|
| 94 |
+
train_df = df[df.subject_id.isin(tr)]
|
| 95 |
+
val_df = df[df.subject_id.isin(va)]
|
| 96 |
+
test_df = df[df.subject_id.isin(te)]
|
| 97 |
+
|
| 98 |
+
tab_stats = fit_tab_stats(train_df, cfg.tab_features)
|
| 99 |
+
counts = np.bincount(train_df["class_id"], minlength=3).tolist()
|
| 100 |
+
|
| 101 |
+
dl_tr = _loader(_make_dataset(cfg, train_df, tab_stats, augment=True), cfg, True)
|
| 102 |
+
dl_va = _loader(_make_dataset(cfg, val_df, tab_stats, augment=False), cfg, False)
|
| 103 |
+
dl_te = _loader(_make_dataset(cfg, test_df, tab_stats, augment=False), cfg, False)
|
| 104 |
+
|
| 105 |
+
cfg_run = TrainConfig(**{**cfg.to_dict(), "seed": seed})
|
| 106 |
+
model = build_model(cfg_run, n_tab_features=len(cfg.tab_features), pretrained=True)
|
| 107 |
+
fit(model, dl_tr, dl_va, cfg_run, counts, device=device)
|
| 108 |
+
|
| 109 |
+
sids, y, pred, prob = predict(model, dl_te, cfg.modality, device)
|
| 110 |
+
run_metrics.append(compute_metrics(y, pred, prob))
|
| 111 |
+
for sid, yt, yp, pr in zip(sids, y, pred, prob):
|
| 112 |
+
oof_rows.append({"subject_id": sid, "seed": seed, "fold": fold,
|
| 113 |
+
"y_true": int(yt), "y_pred": int(yp),
|
| 114 |
+
**{f"prob_{k}": float(pr[k]) for k in range(3)}})
|
| 115 |
+
del model
|
| 116 |
+
if device == "cuda":
|
| 117 |
+
torch.cuda.empty_cache()
|
| 118 |
+
print(f" [{cfg.name}] seed={seed} fold={fold} "
|
| 119 |
+
f"macro_f1={run_metrics[-1]['macro_f1']:.4f}", flush=True)
|
| 120 |
+
return oof_rows, run_metrics
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def run_experiment(cfg: TrainConfig, subjects_csv=None, device="cuda",
|
| 124 |
+
feature_subset=None) -> dict:
|
| 125 |
+
subjects_csv = subjects_csv or (ROOT / "data" / "metadata" / "subjects_clean.csv")
|
| 126 |
+
df = pd.read_csv(subjects_csv)
|
| 127 |
+
folds = make_folds(df)
|
| 128 |
+
|
| 129 |
+
if cfg.model == "xgboost":
|
| 130 |
+
feats = feature_subset or list(cfg.tab_features)
|
| 131 |
+
oof_rows, run_metrics = _run_xgb(cfg, df, folds, feats)
|
| 132 |
+
else:
|
| 133 |
+
oof_rows, run_metrics = _run_torch(cfg, df, folds, device)
|
| 134 |
+
|
| 135 |
+
out_dir = RESULTS / cfg.name
|
| 136 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 137 |
+
oof = pd.DataFrame(oof_rows)
|
| 138 |
+
oof.to_csv(out_dir / "oof.csv", index=False)
|
| 139 |
+
|
| 140 |
+
summary = aggregate_runs(run_metrics)
|
| 141 |
+
point, lo, hi = bootstrap_ci(oof)
|
| 142 |
+
payload = {
|
| 143 |
+
"name": cfg.name, "model": cfg.model, "n_runs": len(run_metrics),
|
| 144 |
+
"summary": {k: {"mean": v[0], "std": v[1]} for k, v in summary.items()},
|
| 145 |
+
"macro_f1_bootstrap": {"point": point, "ci_lo": lo, "ci_hi": hi},
|
| 146 |
+
"config": cfg.to_dict(),
|
| 147 |
+
}
|
| 148 |
+
(out_dir / "runs.json").write_text(json.dumps(run_metrics, indent=2))
|
| 149 |
+
(out_dir / "summary.json").write_text(json.dumps(payload, indent=2, default=str))
|
| 150 |
+
print(f"[{cfg.name}] macro_f1 = {summary['macro_f1'][0]:.4f} ± "
|
| 151 |
+
f"{summary['macro_f1'][1]:.4f} (CI {lo:.3f}-{hi:.3f})", flush=True)
|
| 152 |
+
return payload
|
src/trifuse/eval/stats.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Statistical analysis of cross-validation results.
|
| 2 |
+
|
| 3 |
+
Aggregates per-(seed,fold) metrics into mean±std, computes bootstrap 95% CIs from
|
| 4 |
+
pooled out-of-fold (OOF) predictions, and runs a paired test comparing the proposed
|
| 5 |
+
model against the best baseline across the 15 evaluations.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pandas as pd
|
| 11 |
+
from sklearn.metrics import f1_score
|
| 12 |
+
|
| 13 |
+
from .metrics import compute_metrics
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def aggregate_runs(run_metrics: list[dict]) -> dict[str, tuple[float, float]]:
|
| 17 |
+
"""[{metric: value}, ...] over runs -> {metric: (mean, std)}."""
|
| 18 |
+
keys = run_metrics[0].keys()
|
| 19 |
+
out = {}
|
| 20 |
+
for k in keys:
|
| 21 |
+
vals = np.array([m[k] for m in run_metrics if not np.isnan(m[k])])
|
| 22 |
+
if len(vals):
|
| 23 |
+
out[k] = (float(vals.mean()), float(vals.std()))
|
| 24 |
+
return out
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def bootstrap_ci(oof: pd.DataFrame, metric: str = "macro_f1",
|
| 28 |
+
n_boot: int = 2000, seed: int = 0) -> tuple[float, float, float]:
|
| 29 |
+
"""Bootstrap 95% CI for a metric over pooled OOF predictions.
|
| 30 |
+
|
| 31 |
+
oof: columns subject_id, y_true, y_pred (+ prob_0..2). Resamples subjects.
|
| 32 |
+
Returns (point_estimate, lo, hi).
|
| 33 |
+
"""
|
| 34 |
+
rng = np.random.default_rng(seed)
|
| 35 |
+
y_true = oof["y_true"].to_numpy()
|
| 36 |
+
y_pred = oof["y_pred"].to_numpy()
|
| 37 |
+
n = len(oof)
|
| 38 |
+
point = f1_score(y_true, y_pred, labels=[0, 1, 2], average="macro", zero_division=0)
|
| 39 |
+
stats = np.empty(n_boot)
|
| 40 |
+
for b in range(n_boot):
|
| 41 |
+
idx = rng.integers(0, n, n)
|
| 42 |
+
stats[b] = f1_score(y_true[idx], y_pred[idx], labels=[0, 1, 2],
|
| 43 |
+
average="macro", zero_division=0)
|
| 44 |
+
lo, hi = np.percentile(stats, [2.5, 97.5])
|
| 45 |
+
return float(point), float(lo), float(hi)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def paired_permutation_test(scores_a: list[float], scores_b: list[float],
|
| 49 |
+
n_perm: int = 10000, seed: int = 0) -> float:
|
| 50 |
+
"""Two-sided paired permutation test on per-run metric differences.
|
| 51 |
+
|
| 52 |
+
scores_a, scores_b: paired per-(seed,fold) metric values (same order).
|
| 53 |
+
Returns p-value for H0: mean(a-b)=0.
|
| 54 |
+
"""
|
| 55 |
+
rng = np.random.default_rng(seed)
|
| 56 |
+
a, b = np.asarray(scores_a), np.asarray(scores_b)
|
| 57 |
+
diff = a - b
|
| 58 |
+
obs = abs(diff.mean())
|
| 59 |
+
count = 0
|
| 60 |
+
for _ in range(n_perm):
|
| 61 |
+
signs = rng.choice([-1, 1], size=len(diff))
|
| 62 |
+
if abs((diff * signs).mean()) >= obs - 1e-12:
|
| 63 |
+
count += 1
|
| 64 |
+
return (count + 1) / (n_perm + 1)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def oof_metrics(oof: pd.DataFrame) -> dict:
|
| 68 |
+
"""Compute the full metric dict on pooled OOF predictions."""
|
| 69 |
+
prob_cols = [c for c in oof.columns if c.startswith("prob_")]
|
| 70 |
+
prob = oof[sorted(prob_cols)].to_numpy() if prob_cols else None
|
| 71 |
+
return compute_metrics(oof["y_true"].to_numpy(), oof["y_pred"].to_numpy(), prob)
|
src/trifuse/experiments.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Experiment grid: every model config for the main table, ablation, and confound.
|
| 2 |
+
|
| 3 |
+
Defined as TrainConfig factories (not loose YAML) so the grid is typed and the
|
| 4 |
+
runner can iterate deterministically. Epochs are tuned to the small cohort
|
| 5 |
+
(198 subjects) — early stopping on val Macro-F1 usually halts well before the cap.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from trifuse.training.config import TrainConfig
|
| 10 |
+
|
| 11 |
+
TRI = ("axial", "coronal", "sagittal")
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def main_grid() -> list[TrainConfig]:
|
| 15 |
+
return [
|
| 16 |
+
# --- tabular ---
|
| 17 |
+
TrainConfig(name="xgboost", model="xgboost", modality="tabular"),
|
| 18 |
+
TrainConfig(name="tabular_mlp", model="tabular_mlp", modality="tabular",
|
| 19 |
+
epochs=80, batch_size=16, lr=1e-3),
|
| 20 |
+
# --- CNN ---
|
| 21 |
+
TrainConfig(name="resnet50", model="resnet50", modality="slice2d",
|
| 22 |
+
epochs=60, batch_size=16, lr=3e-4, backbone_lr=3e-5,
|
| 23 |
+
freeze_epochs=5),
|
| 24 |
+
TrainConfig(name="densenet2p5d", model="densenet2p5d", modality="slice25d",
|
| 25 |
+
n_slices=9, planes=("axial",), epochs=60, batch_size=8,
|
| 26 |
+
lr=3e-4, backbone_lr=3e-5, freeze_epochs=5),
|
| 27 |
+
TrainConfig(name="resnet3d", model="resnet3d", modality="vol3d",
|
| 28 |
+
vol_size=(128, 128, 128), epochs=100, batch_size=8,
|
| 29 |
+
lr=1e-4),
|
| 30 |
+
# --- transformers ---
|
| 31 |
+
TrainConfig(name="vit_b16", model="vit2d", modality="slice25d",
|
| 32 |
+
n_slices=9, planes=("axial",), epochs=60, batch_size=8,
|
| 33 |
+
lr=3e-4, backbone_lr=1e-5, freeze_epochs=8, unfreeze_last_n=2),
|
| 34 |
+
TrainConfig(name="swin3d", model="swin3d", modality="vol3d",
|
| 35 |
+
vol_size=(96, 112, 112), epochs=80, batch_size=8,
|
| 36 |
+
lr=1e-4),
|
| 37 |
+
# --- recent hybrids (retrained on our folds) ---
|
| 38 |
+
TrainConfig(name="hcct", model="hcct", modality="vol3d",
|
| 39 |
+
vol_size=(96, 112, 112), epochs=80, batch_size=8,
|
| 40 |
+
lr=1e-4),
|
| 41 |
+
TrainConfig(name="vswin_lite", model="vswin_lite", modality="vol3d",
|
| 42 |
+
vol_size=(96, 112, 112), epochs=80, batch_size=8,
|
| 43 |
+
lr=1e-4),
|
| 44 |
+
# --- multimodal baseline ---
|
| 45 |
+
TrainConfig(name="densenet_latefusion", model="densenet_latefusion",
|
| 46 |
+
modality="multimodal", n_slices=9, planes=("axial",),
|
| 47 |
+
epochs=60, batch_size=8, lr=3e-4, backbone_lr=3e-5, freeze_epochs=5),
|
| 48 |
+
# --- proposed ---
|
| 49 |
+
TrainConfig(name="trifuse_ad", model="trifuse", modality="multimodal",
|
| 50 |
+
n_slices=9, planes=TRI, epochs=70, batch_size=6,
|
| 51 |
+
lr=3e-4, backbone_lr=3e-5, freeze_epochs=6, grad_accum=2),
|
| 52 |
+
]
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def ablation_grid() -> list[TrainConfig]:
|
| 56 |
+
"""A1-A5 + full, all sharing TriFuse-AD's training recipe."""
|
| 57 |
+
base = dict(modality="multimodal", n_slices=9, epochs=70, batch_size=6,
|
| 58 |
+
lr=3e-4, backbone_lr=3e-5, freeze_epochs=6, grad_accum=2)
|
| 59 |
+
return [
|
| 60 |
+
TrainConfig(name="abl_A1_axial", model="trifuse", planes=("axial",), **base),
|
| 61 |
+
TrainConfig(name="abl_A2_meanpool", model="trifuse_meanpool", planes=TRI, **base),
|
| 62 |
+
TrainConfig(name="abl_A3_nometa", model="trifuse_nometa", planes=TRI, **base),
|
| 63 |
+
TrainConfig(name="abl_A4_concat", model="trifuse_concat", planes=TRI, **base),
|
| 64 |
+
TrainConfig(name="abl_A5_weightedce", model="trifuse", planes=TRI,
|
| 65 |
+
loss="weighted_ce", **base),
|
| 66 |
+
TrainConfig(name="abl_full", model="trifuse", planes=TRI, **base),
|
| 67 |
+
]
|
src/trifuse/models/__init__.py
ADDED
|
File without changes
|
src/trifuse/models/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (136 Bytes). View file
|
|
|
src/trifuse/models/__pycache__/baselines_tab.cpython-312.pyc
ADDED
|
Binary file (2.7 kB). View file
|
|
|
src/trifuse/models/__pycache__/cnn2d.cpython-312.pyc
ADDED
|
Binary file (5.59 kB). View file
|
|
|
src/trifuse/models/__pycache__/cnn3d.cpython-312.pyc
ADDED
|
Binary file (1.36 kB). View file
|
|
|
src/trifuse/models/__pycache__/fusion.cpython-312.pyc
ADDED
|
Binary file (3.28 kB). View file
|
|
|
src/trifuse/models/__pycache__/hybrids.cpython-312.pyc
ADDED
|
Binary file (9.83 kB). View file
|
|
|
src/trifuse/models/__pycache__/registry.cpython-312.pyc
ADDED
|
Binary file (2.59 kB). View file
|
|
|
src/trifuse/models/__pycache__/transformers.cpython-312.pyc
ADDED
|
Binary file (4.75 kB). View file
|
|
|
src/trifuse/models/__pycache__/trifuse.cpython-312.pyc
ADDED
|
Binary file (7.63 kB). View file
|
|
|
src/trifuse/models/baselines_tab.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tabular baselines on demographic + morphometric features.
|
| 2 |
+
|
| 3 |
+
Allowed features (NO CDR, NO MMSE — those are label-leaking): age, sex, education,
|
| 4 |
+
ses, etiv, nwbv, asf. XGBoost is used both as a main baseline (B0) and as the
|
| 5 |
+
shortcut/confound probe (age-only, demographic-only, full-structured).
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
|
| 13 |
+
FEATURES_FULL = ["age", "sex", "education", "ses", "etiv", "nwbv", "asf"]
|
| 14 |
+
FEATURES_DEMO = ["age", "sex", "education", "ses"]
|
| 15 |
+
FEATURES_AGE = ["age"]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def make_xgb(n_classes: int = 3, seed: int = 0):
|
| 19 |
+
"""Return an XGBoost classifier configured for small-n multiclass."""
|
| 20 |
+
from xgboost import XGBClassifier
|
| 21 |
+
return XGBClassifier(
|
| 22 |
+
n_estimators=300, max_depth=3, learning_rate=0.05,
|
| 23 |
+
subsample=0.8, colsample_bytree=0.8, reg_lambda=1.0,
|
| 24 |
+
objective="multi:softprob", num_class=n_classes,
|
| 25 |
+
eval_metric="mlogloss", tree_method="hist",
|
| 26 |
+
random_state=seed, n_jobs=4,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class TabularMLP(nn.Module):
|
| 31 |
+
"""Neural tabular baseline (B1) and the metadata branch reference."""
|
| 32 |
+
|
| 33 |
+
def __init__(self, n_features: int = 7, n_classes: int = 3, hidden: int = 128,
|
| 34 |
+
dropout: float = 0.3):
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.net = nn.Sequential(
|
| 37 |
+
nn.Linear(n_features, 64), nn.GELU(), nn.Dropout(dropout),
|
| 38 |
+
nn.Linear(64, hidden), nn.GELU(), nn.LayerNorm(hidden),
|
| 39 |
+
nn.Dropout(dropout), nn.Linear(hidden, n_classes),
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
def forward(self, tab: torch.Tensor, *_unused) -> torch.Tensor:
|
| 43 |
+
return self.net(tab)
|
src/trifuse/models/cnn2d.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""2D / 2.5D CNN baselines (timm backbones).
|
| 2 |
+
|
| 3 |
+
- ResNet50Center: single center axial slice (B, 3, H, W).
|
| 4 |
+
- DenseNet2p5D: 9 axial slices encoded by a shared backbone, mean-pooled (2.5D).
|
| 5 |
+
Both accept the same (B, T, 3, H, W) slice tensor as the rest of the zoo; T is
|
| 6 |
+
sliced/agg internally so the training loop is uniform.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import timm
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn as nn
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class ResNet50Center(nn.Module):
|
| 16 |
+
"""Single-slice baseline: uses the center slice of the axial stack."""
|
| 17 |
+
|
| 18 |
+
def __init__(self, n_classes: int = 3, pretrained: bool = True,
|
| 19 |
+
backbone: str = "resnet50", center_index: int | None = None):
|
| 20 |
+
super().__init__()
|
| 21 |
+
self.backbone = timm.create_model(backbone, pretrained=pretrained, num_classes=n_classes, in_chans=3)
|
| 22 |
+
self.center_index = center_index
|
| 23 |
+
|
| 24 |
+
def forward(self, slices: torch.Tensor, tab: torch.Tensor | None = None) -> torch.Tensor:
|
| 25 |
+
# slices: (B, T, 3, H, W); pick center of the (first) plane's stack
|
| 26 |
+
T = slices.shape[1]
|
| 27 |
+
idx = self.center_index if self.center_index is not None else T // 2
|
| 28 |
+
return self.backbone(slices[:, idx])
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class DenseNet2p5D(nn.Module):
|
| 32 |
+
"""2.5D baseline: shared DenseNet over N slices, mean-pool logits."""
|
| 33 |
+
|
| 34 |
+
def __init__(self, n_classes: int = 3, pretrained: bool = True,
|
| 35 |
+
backbone: str = "densenet121", n_slices: int = 9):
|
| 36 |
+
super().__init__()
|
| 37 |
+
self.encoder = timm.create_model(backbone, pretrained=pretrained, num_classes=0, in_chans=3)
|
| 38 |
+
self.head = nn.Linear(self.encoder.num_features, n_classes)
|
| 39 |
+
self.n_slices = n_slices
|
| 40 |
+
|
| 41 |
+
def forward(self, slices: torch.Tensor, tab: torch.Tensor | None = None) -> torch.Tensor:
|
| 42 |
+
# use first n_slices tokens (axial plane) -> mean-pool features
|
| 43 |
+
x = slices[:, : self.n_slices] # (B, S, 3, H, W)
|
| 44 |
+
B, S, C, H, W = x.shape
|
| 45 |
+
feats = self.encoder(x.reshape(B * S, C, H, W)).reshape(B, S, -1)
|
| 46 |
+
return self.head(feats.mean(dim=1))
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class DenseNetLateFusion(nn.Module):
|
| 50 |
+
"""Multimodal baseline B9: DenseNet 2.5D image embedding + metadata MLP, concat."""
|
| 51 |
+
|
| 52 |
+
def __init__(self, n_classes: int = 3, n_tab_features: int = 7,
|
| 53 |
+
pretrained: bool = True, backbone: str = "densenet121", n_slices: int = 9,
|
| 54 |
+
dropout: float = 0.3):
|
| 55 |
+
super().__init__()
|
| 56 |
+
self.encoder = timm.create_model(backbone, pretrained=pretrained, num_classes=0, in_chans=3)
|
| 57 |
+
img_dim = self.encoder.num_features
|
| 58 |
+
self.n_slices = n_slices
|
| 59 |
+
self.tab = nn.Sequential(
|
| 60 |
+
nn.Linear(n_tab_features, 64), nn.GELU(), nn.Dropout(dropout),
|
| 61 |
+
nn.Linear(64, 128), nn.LayerNorm(128),
|
| 62 |
+
)
|
| 63 |
+
self.head = nn.Sequential(
|
| 64 |
+
nn.Linear(img_dim + 128, 256), nn.GELU(), nn.Dropout(dropout),
|
| 65 |
+
nn.Linear(256, n_classes),
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
def forward(self, slices: torch.Tensor, tab: torch.Tensor) -> torch.Tensor:
|
| 69 |
+
x = slices[:, : self.n_slices]
|
| 70 |
+
B, S, C, H, W = x.shape
|
| 71 |
+
img = self.encoder(x.reshape(B * S, C, H, W)).reshape(B, S, -1).mean(dim=1)
|
| 72 |
+
return self.head(torch.cat([img, self.tab(tab)], dim=1))
|
src/trifuse/models/cnn3d.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""3D CNN baseline: whole-brain volume classification via MONAI ResNet.
|
| 2 |
+
|
| 3 |
+
Input volumes are (B, 1, D, H, W). MONAI's resnet18 with spatial_dims=3 is a clean,
|
| 4 |
+
reproducible baseline for the value-of-volume question.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
from monai.networks.nets import resnet18
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class ResNet3D(nn.Module):
|
| 14 |
+
def __init__(self, n_classes: int = 3, in_channels: int = 1):
|
| 15 |
+
super().__init__()
|
| 16 |
+
self.net = resnet18(
|
| 17 |
+
spatial_dims=3, n_input_channels=in_channels, num_classes=n_classes,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
def forward(self, vol: torch.Tensor, tab: torch.Tensor | None = None) -> torch.Tensor:
|
| 21 |
+
return self.net(vol)
|
src/trifuse/models/fusion.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Clinical-guided gated fusion of MRI and tabular embeddings.
|
| 2 |
+
|
| 3 |
+
Instead of plain concatenation [z_mri; z_tab], learn a gate g = sigma(Wg[z_mri;z_tab])
|
| 4 |
+
that scales the tabular contribution before residual-adding it into the MRI stream:
|
| 5 |
+
|
| 6 |
+
z = LayerNorm(z_mri + g * (Wt z_tab))
|
| 7 |
+
|
| 8 |
+
Rationale: when demographics (esp. age) are informative the gate opens; when they are
|
| 9 |
+
unreliable or missing the MRI branch stays dominant, preventing age from swamping the
|
| 10 |
+
imaging signal. This is the mechanism ablation A4 (concat) tests against.
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
import torch.nn as nn
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class GatedFusion(nn.Module):
|
| 19 |
+
def __init__(self, mri_dim: int, tab_dim: int, dropout: float = 0.1):
|
| 20 |
+
super().__init__()
|
| 21 |
+
self.tab_proj = nn.Linear(tab_dim, mri_dim)
|
| 22 |
+
self.gate = nn.Sequential(
|
| 23 |
+
nn.Linear(mri_dim + tab_dim, mri_dim),
|
| 24 |
+
nn.Sigmoid(),
|
| 25 |
+
)
|
| 26 |
+
self.norm = nn.LayerNorm(mri_dim)
|
| 27 |
+
self.drop = nn.Dropout(dropout)
|
| 28 |
+
self.out_dim = mri_dim
|
| 29 |
+
|
| 30 |
+
def forward(self, z_mri: torch.Tensor, z_tab: torch.Tensor) -> torch.Tensor:
|
| 31 |
+
g = self.gate(torch.cat([z_mri, z_tab], dim=-1)) # (B, mri_dim)
|
| 32 |
+
t = self.tab_proj(z_tab) # (B, mri_dim)
|
| 33 |
+
z = self.norm(z_mri + g * t)
|
| 34 |
+
return self.drop(z)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class ConcatFusion(nn.Module):
|
| 38 |
+
"""Ablation A4: plain concatenation baseline (no gate)."""
|
| 39 |
+
|
| 40 |
+
def __init__(self, mri_dim: int, tab_dim: int, dropout: float = 0.1):
|
| 41 |
+
super().__init__()
|
| 42 |
+
self.proj = nn.Sequential(
|
| 43 |
+
nn.Linear(mri_dim + tab_dim, mri_dim),
|
| 44 |
+
nn.GELU(),
|
| 45 |
+
nn.Dropout(dropout),
|
| 46 |
+
)
|
| 47 |
+
self.out_dim = mri_dim
|
| 48 |
+
|
| 49 |
+
def forward(self, z_mri: torch.Tensor, z_tab: torch.Tensor) -> torch.Tensor:
|
| 50 |
+
return self.proj(torch.cat([z_mri, z_tab], dim=-1))
|
src/trifuse/models/hybrids.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Recent CNN-Transformer hybrid baselines, re-implemented compact for OASIS-1.
|
| 2 |
+
|
| 3 |
+
Both are TRAINED ON OUR FOLDS — no published cross-dataset numbers are copied.
|
| 4 |
+
|
| 5 |
+
- HCCTCompact: 3D convolutional stem -> compact conv blocks -> 3D patch tokens ->
|
| 6 |
+
Transformer encoder -> classification head. After Krishnan et al. 3D HCCT (2024).
|
| 7 |
+
- VSwinFormerLite: residual depthwise 3D CNN stem + 3D CBAM -> Swin-Tiny 3D stages ->
|
| 8 |
+
GAP -> head. After the 3D-CNN + Video Swin model (Sci Reports 2025), lite variant.
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn as nn
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# --------------------------- 3D HCCT (compact) ---------------------------
|
| 17 |
+
class ConvBlock3D(nn.Module):
|
| 18 |
+
def __init__(self, cin, cout, stride=1):
|
| 19 |
+
super().__init__()
|
| 20 |
+
self.net = nn.Sequential(
|
| 21 |
+
nn.Conv3d(cin, cout, 3, stride=stride, padding=1, bias=False),
|
| 22 |
+
nn.BatchNorm3d(cout), nn.GELU(),
|
| 23 |
+
nn.Conv3d(cout, cout, 3, padding=1, bias=False),
|
| 24 |
+
nn.BatchNorm3d(cout), nn.GELU(),
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
def forward(self, x):
|
| 28 |
+
return self.net(x)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class HCCTCompact(nn.Module):
|
| 32 |
+
def __init__(self, n_classes: int = 3, in_channels: int = 1, embed_dim: int = 256,
|
| 33 |
+
n_layers: int = 3, n_heads: int = 8, dropout: float = 0.1):
|
| 34 |
+
super().__init__()
|
| 35 |
+
self.stem = nn.Sequential(
|
| 36 |
+
nn.Conv3d(in_channels, 32, 3, stride=2, padding=1, bias=False),
|
| 37 |
+
nn.BatchNorm3d(32), nn.GELU(),
|
| 38 |
+
)
|
| 39 |
+
self.blocks = nn.Sequential(
|
| 40 |
+
ConvBlock3D(32, 64, stride=2),
|
| 41 |
+
ConvBlock3D(64, 128, stride=2),
|
| 42 |
+
ConvBlock3D(128, embed_dim, stride=2),
|
| 43 |
+
)
|
| 44 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
|
| 45 |
+
nn.init.trunc_normal_(self.cls_token, std=0.02)
|
| 46 |
+
self.pos_drop = nn.Dropout(dropout)
|
| 47 |
+
layer = nn.TransformerEncoderLayer(
|
| 48 |
+
d_model=embed_dim, nhead=n_heads, dim_feedforward=embed_dim * 4,
|
| 49 |
+
dropout=dropout, batch_first=True, activation="gelu", norm_first=True,
|
| 50 |
+
)
|
| 51 |
+
self.transformer = nn.TransformerEncoder(layer, num_layers=n_layers)
|
| 52 |
+
self.norm = nn.LayerNorm(embed_dim)
|
| 53 |
+
self.head = nn.Linear(embed_dim, n_classes)
|
| 54 |
+
|
| 55 |
+
def forward(self, vol: torch.Tensor, tab: torch.Tensor | None = None) -> torch.Tensor:
|
| 56 |
+
x = self.blocks(self.stem(vol)) # (B, C, d, h, w)
|
| 57 |
+
B, C = x.shape[:2]
|
| 58 |
+
tokens = x.flatten(2).transpose(1, 2) # (B, N, C)
|
| 59 |
+
cls = self.cls_token.expand(B, -1, -1)
|
| 60 |
+
seq = self.pos_drop(torch.cat([cls, tokens], dim=1))
|
| 61 |
+
seq = self.transformer(seq)
|
| 62 |
+
return self.head(self.norm(seq[:, 0]))
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# --------------------- 3D-CNN-VSwinFormer (lite) ---------------------
|
| 66 |
+
class CBAM3D(nn.Module):
|
| 67 |
+
"""3D convolutional block attention (channel + spatial)."""
|
| 68 |
+
|
| 69 |
+
def __init__(self, channels, reduction=8):
|
| 70 |
+
super().__init__()
|
| 71 |
+
self.mlp = nn.Sequential(
|
| 72 |
+
nn.Linear(channels, channels // reduction), nn.ReLU(inplace=True),
|
| 73 |
+
nn.Linear(channels // reduction, channels),
|
| 74 |
+
)
|
| 75 |
+
self.spatial = nn.Conv3d(2, 1, 7, padding=3, bias=False)
|
| 76 |
+
|
| 77 |
+
def forward(self, x):
|
| 78 |
+
b, c = x.shape[:2]
|
| 79 |
+
avg = self.mlp(x.mean(dim=(2, 3, 4)))
|
| 80 |
+
mx = self.mlp(x.amax(dim=(2, 3, 4)))
|
| 81 |
+
ca = torch.sigmoid(avg + mx).view(b, c, 1, 1, 1)
|
| 82 |
+
x = x * ca
|
| 83 |
+
sa = torch.cat([x.mean(1, keepdim=True), x.amax(1, keepdim=True)], dim=1)
|
| 84 |
+
x = x * torch.sigmoid(self.spatial(sa))
|
| 85 |
+
return x
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class ResDepthwise3D(nn.Module):
|
| 89 |
+
def __init__(self, cin, cout, stride=1):
|
| 90 |
+
super().__init__()
|
| 91 |
+
self.dw = nn.Conv3d(cin, cin, 3, stride=stride, padding=1, groups=cin, bias=False)
|
| 92 |
+
self.pw = nn.Conv3d(cin, cout, 1, bias=False)
|
| 93 |
+
self.bn = nn.BatchNorm3d(cout)
|
| 94 |
+
self.act = nn.GELU()
|
| 95 |
+
self.proj = (nn.Conv3d(cin, cout, 1, stride=stride, bias=False)
|
| 96 |
+
if (cin != cout or stride != 1) else nn.Identity())
|
| 97 |
+
|
| 98 |
+
def forward(self, x):
|
| 99 |
+
out = self.act(self.bn(self.pw(self.dw(x))))
|
| 100 |
+
return out + self.proj(x)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class VSwinFormerLite(nn.Module):
|
| 104 |
+
"""Residual depthwise CNN stem + CBAM, then a MONAI 3D Swin encoder, GAP + head."""
|
| 105 |
+
|
| 106 |
+
def __init__(self, n_classes: int = 3, in_channels: int = 1, img_size=(96, 112, 112)):
|
| 107 |
+
super().__init__()
|
| 108 |
+
self.stem = nn.Sequential(
|
| 109 |
+
nn.Conv3d(in_channels, 32, 3, stride=2, padding=1, bias=False),
|
| 110 |
+
nn.BatchNorm3d(32), nn.GELU(),
|
| 111 |
+
ResDepthwise3D(32, 48),
|
| 112 |
+
ResDepthwise3D(48, 48),
|
| 113 |
+
CBAM3D(48),
|
| 114 |
+
)
|
| 115 |
+
from monai.networks.nets.swin_unetr import SwinTransformer
|
| 116 |
+
from monai.utils import ensure_tuple_rep
|
| 117 |
+
self.swin = SwinTransformer(
|
| 118 |
+
in_chans=48, embed_dim=48,
|
| 119 |
+
window_size=ensure_tuple_rep(7, 3), patch_size=ensure_tuple_rep(2, 3),
|
| 120 |
+
depths=(2, 2, 2, 2), num_heads=(3, 6, 12, 24), spatial_dims=3,
|
| 121 |
+
)
|
| 122 |
+
self.norm = nn.LayerNorm(48 * 16)
|
| 123 |
+
self.head = nn.Linear(48 * 16, n_classes)
|
| 124 |
+
|
| 125 |
+
def forward(self, vol: torch.Tensor, tab: torch.Tensor | None = None) -> torch.Tensor:
|
| 126 |
+
x = self.stem(vol)
|
| 127 |
+
feats = self.swin(x)[-1]
|
| 128 |
+
pooled = feats.flatten(2).mean(-1)
|
| 129 |
+
return self.head(self.norm(pooled))
|
src/trifuse/models/registry.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Model registry: maps a config `model` key to a constructed nn.Module.
|
| 2 |
+
|
| 3 |
+
Every model's forward signature is (primary_input, tab=None) so the trainer can
|
| 4 |
+
call them uniformly. `modality` (from config) decides which input the loader feeds
|
| 5 |
+
as `primary_input`: slice tensor (B,T,3,H,W), volume (B,1,D,H,W), or tabular (B,F).
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from .cnn2d import ResNet50Center, DenseNet2p5D, DenseNetLateFusion
|
| 10 |
+
from .cnn3d import ResNet3D
|
| 11 |
+
from .transformers import ViT2D, SwinT3D
|
| 12 |
+
from .hybrids import HCCTCompact, VSwinFormerLite
|
| 13 |
+
from .trifuse import TriFuseAD
|
| 14 |
+
from .baselines_tab import TabularMLP
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def build_model(cfg, n_tab_features: int = 7, pretrained: bool = True):
|
| 18 |
+
m = cfg.model
|
| 19 |
+
n = 3
|
| 20 |
+
if m == "tabular_mlp":
|
| 21 |
+
return TabularMLP(n_features=n_tab_features, n_classes=n, dropout=cfg.dropout)
|
| 22 |
+
if m == "resnet50":
|
| 23 |
+
return ResNet50Center(n_classes=n, pretrained=pretrained)
|
| 24 |
+
if m == "densenet2p5d":
|
| 25 |
+
return DenseNet2p5D(n_classes=n, pretrained=pretrained, n_slices=cfg.n_slices)
|
| 26 |
+
if m == "resnet3d":
|
| 27 |
+
return ResNet3D(n_classes=n)
|
| 28 |
+
if m == "vit2d":
|
| 29 |
+
return ViT2D(n_classes=n, pretrained=pretrained)
|
| 30 |
+
if m == "swin3d":
|
| 31 |
+
return SwinT3D(n_classes=n, img_size=cfg.vol_size)
|
| 32 |
+
if m == "hcct":
|
| 33 |
+
return HCCTCompact(n_classes=n)
|
| 34 |
+
if m == "vswin_lite":
|
| 35 |
+
return VSwinFormerLite(n_classes=n, img_size=cfg.vol_size)
|
| 36 |
+
if m == "densenet_latefusion":
|
| 37 |
+
return DenseNetLateFusion(n_classes=n, n_tab_features=n_tab_features,
|
| 38 |
+
pretrained=pretrained, n_slices=cfg.n_slices, dropout=cfg.dropout)
|
| 39 |
+
if m.startswith("trifuse"):
|
| 40 |
+
# ablation flags encoded in the model key: trifuse, trifuse_axial, trifuse_meanpool,
|
| 41 |
+
# trifuse_nometa, trifuse_concat
|
| 42 |
+
return TriFuseAD(
|
| 43 |
+
n_classes=n, n_tab_features=n_tab_features,
|
| 44 |
+
planes=tuple(cfg.planes), n_slices=cfg.n_slices, dropout=cfg.dropout,
|
| 45 |
+
use_transformer=("meanpool" not in m),
|
| 46 |
+
use_metadata=("nometa" not in m),
|
| 47 |
+
fusion=("concat" if "concat" in m else "gated"),
|
| 48 |
+
pretrained=pretrained,
|
| 49 |
+
)
|
| 50 |
+
raise ValueError(f"unknown model key: {m}")
|
src/trifuse/models/transformers.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Transformer baselines.
|
| 2 |
+
|
| 3 |
+
- ViT2D: ViT-B/16 (timm, pretrained) over 2.5D multi-slice input. Slices are
|
| 4 |
+
encoded independently by the shared ViT and mean-pooled, then classified.
|
| 5 |
+
Supports 2-stage fine-tuning via freeze_backbone().
|
| 6 |
+
- SwinT3D: MONAI SwinUNETR encoder (Swin-Tiny-scale) over a 3D crop, GAP + head.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import timm
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn as nn
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class ViT2D(nn.Module):
|
| 16 |
+
"""ViT-B/16 over N 2D slices, mean-pooled embeddings -> classifier.
|
| 17 |
+
|
| 18 |
+
Input: (B, N, 3, 224, 224) or (B, 3, 224, 224). Shared backbone across slices.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
def __init__(self, n_classes: int = 3, pretrained: bool = True):
|
| 22 |
+
super().__init__()
|
| 23 |
+
self.backbone = timm.create_model(
|
| 24 |
+
"vit_base_patch16_224", pretrained=pretrained, num_classes=0,
|
| 25 |
+
)
|
| 26 |
+
self.embed_dim = self.backbone.num_features # 768
|
| 27 |
+
self.head = nn.Linear(self.embed_dim, n_classes)
|
| 28 |
+
|
| 29 |
+
def freeze_backbone(self, freeze: bool = True):
|
| 30 |
+
for p in self.backbone.parameters():
|
| 31 |
+
p.requires_grad = not freeze
|
| 32 |
+
|
| 33 |
+
def unfreeze_last_blocks(self, n_blocks: int = 2):
|
| 34 |
+
self.freeze_backbone(True)
|
| 35 |
+
for blk in self.backbone.blocks[-n_blocks:]:
|
| 36 |
+
for p in blk.parameters():
|
| 37 |
+
p.requires_grad = True
|
| 38 |
+
for p in self.backbone.norm.parameters():
|
| 39 |
+
p.requires_grad = True
|
| 40 |
+
|
| 41 |
+
def forward(self, x: torch.Tensor, tab: torch.Tensor | None = None) -> torch.Tensor:
|
| 42 |
+
if x.dim() == 4:
|
| 43 |
+
x = x.unsqueeze(1) # (B,1,3,224,224)
|
| 44 |
+
b, n = x.shape[:2]
|
| 45 |
+
x = x.flatten(0, 1) # (B*N,3,224,224)
|
| 46 |
+
feats = self.backbone(x) # (B*N,768)
|
| 47 |
+
feats = feats.view(b, n, -1).mean(1) # mean-pool slices
|
| 48 |
+
return self.head(feats)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class SwinT3D(nn.Module):
|
| 52 |
+
"""3D Swin transformer encoder (Swin-Tiny scale) via MONAI, GAP + linear head."""
|
| 53 |
+
|
| 54 |
+
def __init__(self, n_classes: int = 3, in_channels: int = 1, img_size=(96, 112, 112)):
|
| 55 |
+
super().__init__()
|
| 56 |
+
from monai.networks.nets.swin_unetr import SwinTransformer
|
| 57 |
+
from monai.utils import ensure_tuple_rep
|
| 58 |
+
|
| 59 |
+
patch = ensure_tuple_rep(2, 3)
|
| 60 |
+
window = ensure_tuple_rep(7, 3)
|
| 61 |
+
self.swin = SwinTransformer(
|
| 62 |
+
in_chans=in_channels,
|
| 63 |
+
embed_dim=48,
|
| 64 |
+
window_size=window,
|
| 65 |
+
patch_size=patch,
|
| 66 |
+
depths=(2, 2, 2, 2),
|
| 67 |
+
num_heads=(3, 6, 12, 24),
|
| 68 |
+
spatial_dims=3,
|
| 69 |
+
)
|
| 70 |
+
self.norm = nn.LayerNorm(48 * 16)
|
| 71 |
+
self.head = nn.Linear(48 * 16, n_classes)
|
| 72 |
+
|
| 73 |
+
def forward(self, vol: torch.Tensor, tab: torch.Tensor | None = None) -> torch.Tensor:
|
| 74 |
+
feats = self.swin(vol)[-1] # deepest stage (B, 8C, d, h, w)
|
| 75 |
+
pooled = feats.flatten(2).mean(-1) # GAP -> (B, 8C)
|
| 76 |
+
return self.head(self.norm(pooled))
|
src/trifuse/models/trifuse.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""TriFuse-AD: tri-planar CNN + slice-plane Transformer + gated metadata fusion.
|
| 2 |
+
|
| 3 |
+
Pipeline:
|
| 4 |
+
27 slices (3 planes x 9) -> shared 2D CNN encoder (timm ConvNeXt-Tiny) -> 27 tokens
|
| 5 |
+
+ slice pos-emb + plane emb + [CLS] -> 2-layer Transformer encoder -> z_mri (CLS)
|
| 6 |
+
metadata (7 feats) -> MLP -> z_tab
|
| 7 |
+
GatedFusion(z_mri, z_tab) -> classifier -> 3 logits
|
| 8 |
+
|
| 9 |
+
Ablation knobs (set via constructor so A1-A5 reuse this class):
|
| 10 |
+
use_transformer=False -> mean-pool tokens instead of Transformer (A2)
|
| 11 |
+
planes=("axial",) -> single-plane / axial-only (A1)
|
| 12 |
+
use_metadata=False -> drop tabular branch entirely (A3)
|
| 13 |
+
fusion="concat" -> ConcatFusion instead of GatedFusion (A4)
|
| 14 |
+
"""
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import timm
|
| 18 |
+
import torch
|
| 19 |
+
import torch.nn as nn
|
| 20 |
+
|
| 21 |
+
from .fusion import GatedFusion, ConcatFusion
|
| 22 |
+
|
| 23 |
+
PLANE_TO_IDX = {"axial": 0, "coronal": 1, "sagittal": 2}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class MetadataMLP(nn.Module):
|
| 27 |
+
def __init__(self, in_dim: int, out_dim: int = 128, dropout: float = 0.3):
|
| 28 |
+
super().__init__()
|
| 29 |
+
self.net = nn.Sequential(
|
| 30 |
+
nn.Linear(in_dim, 64), nn.GELU(), nn.Dropout(dropout),
|
| 31 |
+
nn.Linear(64, out_dim), nn.LayerNorm(out_dim),
|
| 32 |
+
)
|
| 33 |
+
self.out_dim = out_dim
|
| 34 |
+
|
| 35 |
+
def forward(self, x):
|
| 36 |
+
return self.net(x)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class TriFuseAD(nn.Module):
|
| 40 |
+
def __init__(
|
| 41 |
+
self,
|
| 42 |
+
n_classes: int = 3,
|
| 43 |
+
n_tab_features: int = 7,
|
| 44 |
+
planes: tuple[str, ...] = ("axial", "coronal", "sagittal"),
|
| 45 |
+
n_slices: int = 9,
|
| 46 |
+
backbone: str = "convnext_tiny",
|
| 47 |
+
embed_dim: int = 768,
|
| 48 |
+
n_transformer_layers: int = 2,
|
| 49 |
+
n_heads: int = 8,
|
| 50 |
+
dropout: float = 0.3,
|
| 51 |
+
use_transformer: bool = True,
|
| 52 |
+
use_metadata: bool = True,
|
| 53 |
+
fusion: str = "gated",
|
| 54 |
+
pretrained: bool = True,
|
| 55 |
+
):
|
| 56 |
+
super().__init__()
|
| 57 |
+
self.planes = planes
|
| 58 |
+
self.n_slices = n_slices
|
| 59 |
+
self.n_tokens = len(planes) * n_slices
|
| 60 |
+
self.use_transformer = use_transformer
|
| 61 |
+
self.use_metadata = use_metadata
|
| 62 |
+
|
| 63 |
+
# shared CNN encoder (num_classes=0 -> pooled feature vector)
|
| 64 |
+
self.encoder = timm.create_model(
|
| 65 |
+
backbone, pretrained=pretrained, num_classes=0, in_chans=3,
|
| 66 |
+
)
|
| 67 |
+
feat_dim = self.encoder.num_features
|
| 68 |
+
self.proj = nn.Linear(feat_dim, embed_dim) if feat_dim != embed_dim else nn.Identity()
|
| 69 |
+
|
| 70 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
|
| 71 |
+
self.slice_pos = nn.Parameter(torch.zeros(1, n_slices, embed_dim))
|
| 72 |
+
self.plane_emb = nn.Parameter(torch.zeros(1, len(planes), embed_dim))
|
| 73 |
+
nn.init.trunc_normal_(self.cls_token, std=0.02)
|
| 74 |
+
nn.init.trunc_normal_(self.slice_pos, std=0.02)
|
| 75 |
+
nn.init.trunc_normal_(self.plane_emb, std=0.02)
|
| 76 |
+
|
| 77 |
+
if use_transformer:
|
| 78 |
+
layer = nn.TransformerEncoderLayer(
|
| 79 |
+
d_model=embed_dim, nhead=n_heads, dim_feedforward=embed_dim * 4,
|
| 80 |
+
dropout=dropout, batch_first=True, activation="gelu", norm_first=True,
|
| 81 |
+
)
|
| 82 |
+
self.transformer = nn.TransformerEncoder(layer, num_layers=n_transformer_layers)
|
| 83 |
+
self.mri_norm = nn.LayerNorm(embed_dim)
|
| 84 |
+
|
| 85 |
+
fused_dim = embed_dim
|
| 86 |
+
if use_metadata:
|
| 87 |
+
self.tab_mlp = MetadataMLP(n_tab_features, out_dim=128, dropout=dropout)
|
| 88 |
+
fusion_cls = GatedFusion if fusion == "gated" else ConcatFusion
|
| 89 |
+
self.fusion = fusion_cls(embed_dim, self.tab_mlp.out_dim, dropout=dropout)
|
| 90 |
+
fused_dim = self.fusion.out_dim
|
| 91 |
+
|
| 92 |
+
self.head = nn.Sequential(
|
| 93 |
+
nn.Linear(fused_dim, 256), nn.GELU(), nn.Dropout(dropout),
|
| 94 |
+
nn.Linear(256, n_classes),
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
def encode_mri(self, slices: torch.Tensor) -> torch.Tensor:
|
| 98 |
+
"""slices: (B, n_tokens, 3, H, W) -> z_mri (B, embed_dim)."""
|
| 99 |
+
B, T, C, H, W = slices.shape
|
| 100 |
+
feats = self.encoder(slices.reshape(B * T, C, H, W)) # (B*T, feat_dim)
|
| 101 |
+
feats = self.proj(feats).reshape(B, T, -1) # (B, T, embed_dim)
|
| 102 |
+
|
| 103 |
+
# add slice + plane positional embeddings (tokens ordered plane-major)
|
| 104 |
+
pos = []
|
| 105 |
+
for p_idx in range(len(self.planes)):
|
| 106 |
+
pe = self.slice_pos + self.plane_emb[:, p_idx:p_idx + 1, :] # (1, n_slices, D)
|
| 107 |
+
pos.append(pe)
|
| 108 |
+
pos = torch.cat(pos, dim=1) # (1, T, D)
|
| 109 |
+
feats = feats + pos
|
| 110 |
+
|
| 111 |
+
if self.use_transformer:
|
| 112 |
+
cls = self.cls_token.expand(B, -1, -1)
|
| 113 |
+
seq = torch.cat([cls, feats], dim=1) # (B, 1+T, D)
|
| 114 |
+
seq = self.transformer(seq)
|
| 115 |
+
z = seq[:, 0] # CLS
|
| 116 |
+
else:
|
| 117 |
+
z = feats.mean(dim=1) # mean-pool (A2)
|
| 118 |
+
return self.mri_norm(z)
|
| 119 |
+
|
| 120 |
+
def forward(self, slices: torch.Tensor, tab: torch.Tensor | None = None) -> torch.Tensor:
|
| 121 |
+
z_mri = self.encode_mri(slices)
|
| 122 |
+
if self.use_metadata:
|
| 123 |
+
assert tab is not None, "metadata branch enabled but tab is None"
|
| 124 |
+
z_tab = self.tab_mlp(tab)
|
| 125 |
+
z = self.fusion(z_mri, z_tab)
|
| 126 |
+
else:
|
| 127 |
+
z = z_mri
|
| 128 |
+
return self.head(z)
|