Upload 13 files
Browse files- README.md +12 -1
- milk10k_effb2_dermoscopic_metadata/ablation.py +12 -3
- milk10k_effb2_dermoscopic_metadata/core.py +4 -37
- milk10k_effb2_dermoscopic_metadata/data.py +66 -14
- milk10k_effb2_dermoscopic_metadata/inference.py +25 -9
- milk10k_effb2_dermoscopic_metadata/losses.py +111 -0
- milk10k_effb2_dermoscopic_metadata/model.py +10 -2
- milk10k_effb2_dermoscopic_metadata/reporting.py +92 -0
- milk10k_effb2_dermoscopic_metadata/training.py +221 -233
README.md
CHANGED
|
@@ -37,6 +37,15 @@ python train_milk10k_effb2_dermoscopic_metadata.py \
|
|
| 37 |
Use `--encoder-checkpoint` to initialize only the image encoder and
|
| 38 |
`--resume-checkpoint RUN/last.pt` to continue an interrupted run.
|
| 39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
## Inference
|
| 41 |
|
| 42 |
```bash
|
|
@@ -55,4 +64,6 @@ is loaded automatically unless `--no-auto-calibration` is passed.
|
|
| 55 |
|
| 56 |
Training writes `best.pt`, `last.pt`, `history.csv`, `metrics.json`,
|
| 57 |
`per_class_metrics.csv`, `confusion_matrix.csv`, `val_predictions.csv`,
|
| 58 |
-
`
|
|
|
|
|
|
|
|
|
| 37 |
Use `--encoder-checkpoint` to initialize only the image encoder and
|
| 38 |
`--resume-checkpoint RUN/last.pt` to continue an interrupted run.
|
| 39 |
|
| 40 |
+
Losses: `ce`, `focal`, `ldam`, `ce_dice`, and `ce_f1`. For generated datasets,
|
| 41 |
+
use `--synthetic-train-only` so `__sdpair_` lesions cannot enter validation.
|
| 42 |
+
Additional generated data can be appended with `--augmented-data-dir`, filtered
|
| 43 |
+
with `--augmented-classes`, and capped with `--augmented-max-per-class`.
|
| 44 |
+
|
| 45 |
+
Use `--selection-metric f1_macro` (default) or `dice_macro`. LDAM runs also
|
| 46 |
+
write `tail_best.pt`. Pass `--k-folds N` to create deterministic folds in the
|
| 47 |
+
shared split manifest.
|
| 48 |
+
|
| 49 |
## Inference
|
| 50 |
|
| 51 |
```bash
|
|
|
|
| 64 |
|
| 65 |
Training writes `best.pt`, `last.pt`, `history.csv`, `metrics.json`,
|
| 66 |
`per_class_metrics.csv`, `confusion_matrix.csv`, `val_predictions.csv`,
|
| 67 |
+
`splits/`, `run_config.json`, `data_summary.json`, `split_summary.md`,
|
| 68 |
+
prediction/confusion diagnostics, and `run_report.md`. K-fold runs additionally
|
| 69 |
+
write `kfold_summary.csv/json` and `kfold_report.md`.
|
milk10k_effb2_dermoscopic_metadata/ablation.py
CHANGED
|
@@ -27,15 +27,24 @@ def summarize(output_dir: Path):
|
|
| 27 |
payload = {"runs": {}, "delta_with_minus_without": {}}
|
| 28 |
keys = ["f1_macro", "balanced_accuracy", "accuracy", "roc_auc_macro_ovr", "f1_weighted"]
|
| 29 |
for mode, directory in runs.items():
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
payload["runs"][mode] = metrics
|
| 32 |
rows.append({"metadata_mode": mode, **{key: metrics.get(key) for key in keys}})
|
| 33 |
for key in keys:
|
| 34 |
left = payload["runs"]["none"].get(key); right = payload["runs"]["concat"].get(key)
|
| 35 |
payload["delta_with_minus_without"][key] = None if left is None or right is None else right - left
|
| 36 |
class_rows = []
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
for name in none_pc.index:
|
| 40 |
class_rows.append({"class": name, "f1_no_metadata": none_pc.loc[name, "f1"], "f1_with_metadata": with_pc.loc[name, "f1"],
|
| 41 |
"f1_delta": with_pc.loc[name, "f1"] - none_pc.loc[name, "f1"],
|
|
|
|
| 27 |
payload = {"runs": {}, "delta_with_minus_without": {}}
|
| 28 |
keys = ["f1_macro", "balanced_accuracy", "accuracy", "roc_auc_macro_ovr", "f1_weighted"]
|
| 29 |
for mode, directory in runs.items():
|
| 30 |
+
if (directory / "metrics.json").exists():
|
| 31 |
+
metrics = json.loads((directory / "metrics.json").read_text(encoding="utf-8"))
|
| 32 |
+
else:
|
| 33 |
+
kfold = json.loads((directory / "kfold_summary.json").read_text(encoding="utf-8"))
|
| 34 |
+
metrics = kfold["mean"]
|
| 35 |
payload["runs"][mode] = metrics
|
| 36 |
rows.append({"metadata_mode": mode, **{key: metrics.get(key) for key in keys}})
|
| 37 |
for key in keys:
|
| 38 |
left = payload["runs"]["none"].get(key); right = payload["runs"]["concat"].get(key)
|
| 39 |
payload["delta_with_minus_without"][key] = None if left is None or right is None else right - left
|
| 40 |
class_rows = []
|
| 41 |
+
def per_class(directory):
|
| 42 |
+
direct=directory/"per_class_metrics.csv"
|
| 43 |
+
paths=[direct] if direct.exists() else sorted(directory.glob("fold_*/per_class_metrics.csv"))
|
| 44 |
+
frames=[pd.read_csv(path) for path in paths]
|
| 45 |
+
if not frames:raise FileNotFoundError(f"No per-class metrics under {directory}")
|
| 46 |
+
return pd.concat(frames).groupby("class",as_index=True).mean(numeric_only=True)
|
| 47 |
+
none_pc = per_class(runs["none"]); with_pc = per_class(runs["concat"])
|
| 48 |
for name in none_pc.index:
|
| 49 |
class_rows.append({"class": name, "f1_no_metadata": none_pc.loc[name, "f1"], "f1_with_metadata": with_pc.loc[name, "f1"],
|
| 50 |
"f1_delta": with_pc.loc[name, "f1"] - none_pc.loc[name, "f1"],
|
milk10k_effb2_dermoscopic_metadata/core.py
CHANGED
|
@@ -15,7 +15,6 @@ from sklearn.metrics import (
|
|
| 15 |
precision_recall_fscore_support, roc_auc_score,
|
| 16 |
)
|
| 17 |
from sklearn.preprocessing import label_binarize
|
| 18 |
-
from torch import nn
|
| 19 |
|
| 20 |
|
| 21 |
def set_seed(seed: int) -> None:
|
|
@@ -26,39 +25,6 @@ def set_seed(seed: int) -> None:
|
|
| 26 |
torch.cuda.manual_seed_all(seed)
|
| 27 |
|
| 28 |
|
| 29 |
-
class SoftDiceLoss(nn.Module):
|
| 30 |
-
def __init__(self, num_classes: int, smooth: float = 1.0):
|
| 31 |
-
super().__init__()
|
| 32 |
-
self.num_classes = num_classes
|
| 33 |
-
self.smooth = smooth
|
| 34 |
-
|
| 35 |
-
def forward(self, logits, labels):
|
| 36 |
-
probs = torch.softmax(logits, dim=1)
|
| 37 |
-
target = torch.nn.functional.one_hot(labels, self.num_classes).to(probs.dtype)
|
| 38 |
-
intersection = (probs * target).sum(dim=0)
|
| 39 |
-
denominator = probs.sum(dim=0) + target.sum(dim=0)
|
| 40 |
-
return 1.0 - ((2 * intersection + self.smooth) / (denominator + self.smooth)).mean()
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
class CEDiceLoss(nn.Module):
|
| 44 |
-
def __init__(self, num_classes: int, dice_weight: float, class_weights: torch.Tensor | None = None):
|
| 45 |
-
super().__init__()
|
| 46 |
-
self.ce = nn.CrossEntropyLoss(weight=class_weights)
|
| 47 |
-
self.dice = SoftDiceLoss(num_classes)
|
| 48 |
-
self.dice_weight = dice_weight
|
| 49 |
-
|
| 50 |
-
def forward(self, logits, labels):
|
| 51 |
-
return (1.0 - self.dice_weight) * self.ce(logits, labels) + self.dice_weight * self.dice(logits, labels)
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
def build_loss(loss_name: str, num_classes: int, dice_weight: float, class_weights=None):
|
| 55 |
-
if loss_name == "ce":
|
| 56 |
-
return nn.CrossEntropyLoss(weight=class_weights)
|
| 57 |
-
if loss_name == "ce_dice":
|
| 58 |
-
return CEDiceLoss(num_classes, dice_weight, class_weights)
|
| 59 |
-
raise ValueError(f"Unsupported loss: {loss_name}")
|
| 60 |
-
|
| 61 |
-
|
| 62 |
def safe_auc(y_true_bin, y_prob, average):
|
| 63 |
try:
|
| 64 |
return float(roc_auc_score(y_true_bin, y_prob, average=average, multi_class="ovr"))
|
|
@@ -91,6 +57,7 @@ def compute_metrics(y_true: np.ndarray, y_prob: np.ndarray, class_names: list[st
|
|
| 91 |
metrics = {
|
| 92 |
"accuracy": float(accuracy_score(y_true, y_pred)),
|
| 93 |
"balanced_accuracy": float(balanced_accuracy_score(y_true, y_pred)),
|
|
|
|
| 94 |
"top3_accuracy": float(np.mean((np.argsort(y_prob, axis=1)[:, -min(3, len(labels)):] == y_true[:, None]).any(axis=1))),
|
| 95 |
"precision_macro": float(macro[0]), "recall_macro": float(macro[1]), "f1_macro": float(macro[2]),
|
| 96 |
"dice_macro": float(macro[2]),
|
|
@@ -111,9 +78,9 @@ def apply_class_bias(y_prob: np.ndarray, bias: np.ndarray) -> np.ndarray:
|
|
| 111 |
return exp / exp.sum(axis=1, keepdims=True)
|
| 112 |
|
| 113 |
|
| 114 |
-
def optimize_class_bias(y_true, y_prob, class_names, max_bias=1.5, step=0.25, passes=3):
|
| 115 |
bias = np.zeros(len(class_names), dtype=np.float32)
|
| 116 |
-
best = compute_metrics(y_true, y_prob, class_names)[0][
|
| 117 |
candidates = np.arange(-max_bias, max_bias + step / 2, step)
|
| 118 |
for _ in range(passes):
|
| 119 |
improved = False
|
|
@@ -121,7 +88,7 @@ def optimize_class_bias(y_true, y_prob, class_names, max_bias=1.5, step=0.25, pa
|
|
| 121 |
local_best, local_value = best, bias[index]
|
| 122 |
for value in candidates:
|
| 123 |
trial = bias.copy(); trial[index] = value
|
| 124 |
-
score = compute_metrics(y_true, apply_class_bias(y_prob, trial), class_names)[0][
|
| 125 |
if score > local_best:
|
| 126 |
local_best, local_value = score, float(value)
|
| 127 |
if local_best > best:
|
|
|
|
| 15 |
precision_recall_fscore_support, roc_auc_score,
|
| 16 |
)
|
| 17 |
from sklearn.preprocessing import label_binarize
|
|
|
|
| 18 |
|
| 19 |
|
| 20 |
def set_seed(seed: int) -> None:
|
|
|
|
| 25 |
torch.cuda.manual_seed_all(seed)
|
| 26 |
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
def safe_auc(y_true_bin, y_prob, average):
|
| 29 |
try:
|
| 30 |
return float(roc_auc_score(y_true_bin, y_prob, average=average, multi_class="ovr"))
|
|
|
|
| 57 |
metrics = {
|
| 58 |
"accuracy": float(accuracy_score(y_true, y_pred)),
|
| 59 |
"balanced_accuracy": float(balanced_accuracy_score(y_true, y_pred)),
|
| 60 |
+
"top2_accuracy": float(np.mean((np.argsort(y_prob, axis=1)[:, -min(2, len(labels)):] == y_true[:, None]).any(axis=1))),
|
| 61 |
"top3_accuracy": float(np.mean((np.argsort(y_prob, axis=1)[:, -min(3, len(labels)):] == y_true[:, None]).any(axis=1))),
|
| 62 |
"precision_macro": float(macro[0]), "recall_macro": float(macro[1]), "f1_macro": float(macro[2]),
|
| 63 |
"dice_macro": float(macro[2]),
|
|
|
|
| 78 |
return exp / exp.sum(axis=1, keepdims=True)
|
| 79 |
|
| 80 |
|
| 81 |
+
def optimize_class_bias(y_true, y_prob, class_names, max_bias=1.5, step=0.25, passes=3, metric_name="f1_macro"):
|
| 82 |
bias = np.zeros(len(class_names), dtype=np.float32)
|
| 83 |
+
best = compute_metrics(y_true, y_prob, class_names)[0][metric_name]
|
| 84 |
candidates = np.arange(-max_bias, max_bias + step / 2, step)
|
| 85 |
for _ in range(passes):
|
| 86 |
improved = False
|
|
|
|
| 88 |
local_best, local_value = best, bias[index]
|
| 89 |
for value in candidates:
|
| 90 |
trial = bias.copy(); trial[index] = value
|
| 91 |
+
score = compute_metrics(y_true, apply_class_bias(y_prob, trial), class_names)[0][metric_name]
|
| 92 |
if score > local_best:
|
| 93 |
local_best, local_value = score, float(value)
|
| 94 |
if local_best > best:
|
milk10k_effb2_dermoscopic_metadata/data.py
CHANGED
|
@@ -10,7 +10,7 @@ import numpy as np
|
|
| 10 |
import pandas as pd
|
| 11 |
import torch
|
| 12 |
from PIL import Image, ImageFile
|
| 13 |
-
from sklearn.model_selection import train_test_split
|
| 14 |
from torch.utils.data import DataLoader, Dataset, WeightedRandomSampler
|
| 15 |
from torchvision import transforms
|
| 16 |
|
|
@@ -105,13 +105,35 @@ def metadata_vector(row: pd.Series, spec: dict[str, Any]) -> np.ndarray:
|
|
| 105 |
return np.asarray(values, dtype=np.float32)
|
| 106 |
|
| 107 |
|
| 108 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
manifest = manifest.expanduser().resolve()
|
| 110 |
all_ids = set(df["lesion_id"].astype(str))
|
| 111 |
if manifest.exists():
|
| 112 |
payload = json.loads(manifest.read_text(encoding="utf-8"))
|
| 113 |
-
|
| 114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
if train_ids & val_ids:
|
| 116 |
raise ValueError(f"Split manifest has overlapping train/validation IDs: {manifest}")
|
| 117 |
unknown = (train_ids | val_ids) - all_ids
|
|
@@ -119,19 +141,31 @@ def create_or_load_split(df: pd.DataFrame, manifest: Path, val_size: float, seed
|
|
| 119 |
if unknown or missing:
|
| 120 |
raise ValueError(f"Split manifest does not match dataset (unknown={len(unknown)}, missing={len(missing)}).")
|
| 121 |
else:
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
)
|
| 125 |
-
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
manifest.parent.mkdir(parents=True, exist_ok=True)
|
| 128 |
manifest.write_text(
|
| 129 |
json.dumps(
|
| 130 |
{
|
| 131 |
-
"seed": seed,
|
| 132 |
-
"
|
| 133 |
-
"train_lesion_ids": sorted(train_ids),
|
| 134 |
-
"val_lesion_ids": sorted(val_ids),
|
| 135 |
},
|
| 136 |
indent=2,
|
| 137 |
),
|
|
@@ -142,6 +176,22 @@ def create_or_load_split(df: pd.DataFrame, manifest: Path, val_size: float, seed
|
|
| 142 |
return train_df.reset_index(drop=True), val_df.reset_index(drop=True)
|
| 143 |
|
| 144 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
def make_transforms(image_size: int):
|
| 146 |
normalize = transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
|
| 147 |
train_transform = transforms.Compose(
|
|
@@ -166,6 +216,8 @@ class DermoscopicMetadataDataset(Dataset):
|
|
| 166 |
self.df = df.reset_index(drop=True)
|
| 167 |
self.labels = None if label_to_idx is None or "label" not in df else [label_to_idx[x] for x in self.df["label"]]
|
| 168 |
self.metadata = np.stack([metadata_vector(row, metadata_spec) for _, row in self.df.iterrows()])
|
|
|
|
|
|
|
| 169 |
self.transform = transform
|
| 170 |
|
| 171 |
def __len__(self) -> int:
|
|
@@ -193,7 +245,7 @@ def make_loaders(train_df, val_df, label_to_idx, metadata_spec, args):
|
|
| 193 |
counts = np.bincount(labels, minlength=len(label_to_idx))
|
| 194 |
if np.any(counts == 0):
|
| 195 |
raise ValueError("Cannot use weighted sampler with an empty training class.")
|
| 196 |
-
weights = (1.0 / counts.astype(np.float64))[labels]
|
| 197 |
generator = torch.Generator().manual_seed(args.seed)
|
| 198 |
sampler = WeightedRandomSampler(torch.as_tensor(weights, dtype=torch.double), len(labels), True, generator=generator)
|
| 199 |
common = dict(batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=torch.cuda.is_available())
|
|
|
|
| 10 |
import pandas as pd
|
| 11 |
import torch
|
| 12 |
from PIL import Image, ImageFile
|
| 13 |
+
from sklearn.model_selection import StratifiedKFold, train_test_split
|
| 14 |
from torch.utils.data import DataLoader, Dataset, WeightedRandomSampler
|
| 15 |
from torchvision import transforms
|
| 16 |
|
|
|
|
| 105 |
return np.asarray(values, dtype=np.float32)
|
| 106 |
|
| 107 |
|
| 108 |
+
def synthetic_mask(df: pd.DataFrame) -> np.ndarray:
|
| 109 |
+
mask = np.zeros(len(df), dtype=bool)
|
| 110 |
+
if "is_augmented" in df:
|
| 111 |
+
mask |= df["is_augmented"].fillna(False).astype(bool).to_numpy()
|
| 112 |
+
mask |= df["lesion_id"].astype(str).str.contains("__sdpair_", regex=False).to_numpy()
|
| 113 |
+
return mask
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def create_or_load_split(
|
| 117 |
+
df: pd.DataFrame, manifest: Path, val_size: float, seed: int,
|
| 118 |
+
synthetic_train_only: bool = False, fold_index: int = 0, k_folds: int = 1,
|
| 119 |
+
) -> tuple[pd.DataFrame, pd.DataFrame]:
|
| 120 |
manifest = manifest.expanduser().resolve()
|
| 121 |
all_ids = set(df["lesion_id"].astype(str))
|
| 122 |
if manifest.exists():
|
| 123 |
payload = json.loads(manifest.read_text(encoding="utf-8"))
|
| 124 |
+
if "folds" in payload:
|
| 125 |
+
if int(payload.get("k_folds", 1)) != k_folds:
|
| 126 |
+
raise ValueError("Split manifest k_folds does not match --k-folds.")
|
| 127 |
+
if bool(payload.get("synthetic_train_only", False)) != synthetic_train_only:
|
| 128 |
+
raise ValueError("Split manifest synthetic_train_only does not match current CLI; use a separate manifest.")
|
| 129 |
+
try: selected = payload["folds"][fold_index]
|
| 130 |
+
except IndexError as exc: raise ValueError(f"Split manifest has no fold {fold_index}.") from exc
|
| 131 |
+
train_ids = set(map(str, selected["train_lesion_ids"])); val_ids = set(map(str, selected["val_lesion_ids"]))
|
| 132 |
+
else: # v1 manifest compatibility
|
| 133 |
+
if k_folds != 1: raise ValueError("Legacy split manifest cannot be used with k-fold training.")
|
| 134 |
+
train_ids = set(map(str, payload["train_lesion_ids"])); val_ids = set(map(str, payload["val_lesion_ids"]))
|
| 135 |
+
if synthetic_train_only and any("__sdpair_" in item for item in val_ids):
|
| 136 |
+
raise ValueError("Legacy manifest contains synthetic validation IDs; remove it to create a safe v2 manifest.")
|
| 137 |
if train_ids & val_ids:
|
| 138 |
raise ValueError(f"Split manifest has overlapping train/validation IDs: {manifest}")
|
| 139 |
unknown = (train_ids | val_ids) - all_ids
|
|
|
|
| 141 |
if unknown or missing:
|
| 142 |
raise ValueError(f"Split manifest does not match dataset (unknown={len(unknown)}, missing={len(missing)}).")
|
| 143 |
else:
|
| 144 |
+
synthetic = synthetic_mask(df)
|
| 145 |
+
base = df.loc[~synthetic].copy() if synthetic_train_only else df.copy()
|
| 146 |
+
extra_train_ids = set(df.loc[synthetic, "lesion_id"].astype(str)) if synthetic_train_only else set()
|
| 147 |
+
folds = []
|
| 148 |
+
if k_folds == 1:
|
| 149 |
+
train_rows, val_rows = train_test_split(base, test_size=val_size, stratify=base["label"], random_state=seed)
|
| 150 |
+
pairs = [(train_rows, val_rows)]
|
| 151 |
+
else:
|
| 152 |
+
if k_folds < 2: raise ValueError("--k-folds must be 1 or >=2.")
|
| 153 |
+
minimum = int(base["label"].value_counts().min())
|
| 154 |
+
if k_folds > minimum: raise ValueError(f"--k-folds={k_folds} exceeds smallest class count={minimum}.")
|
| 155 |
+
splitter = StratifiedKFold(k_folds, shuffle=True, random_state=seed)
|
| 156 |
+
pairs = [(base.iloc[tr], base.iloc[va]) for tr, va in splitter.split(base, base["label"])]
|
| 157 |
+
for train_rows, val_rows in pairs:
|
| 158 |
+
folds.append({
|
| 159 |
+
"train_lesion_ids": sorted(set(train_rows["lesion_id"].astype(str)) | extra_train_ids),
|
| 160 |
+
"val_lesion_ids": sorted(set(val_rows["lesion_id"].astype(str))),
|
| 161 |
+
})
|
| 162 |
+
train_ids = set(folds[fold_index]["train_lesion_ids"]); val_ids = set(folds[fold_index]["val_lesion_ids"])
|
| 163 |
manifest.parent.mkdir(parents=True, exist_ok=True)
|
| 164 |
manifest.write_text(
|
| 165 |
json.dumps(
|
| 166 |
{
|
| 167 |
+
"schema_version": 2, "seed": seed, "val_size": val_size, "k_folds": k_folds,
|
| 168 |
+
"synthetic_train_only": synthetic_train_only, "folds": folds,
|
|
|
|
|
|
|
| 169 |
},
|
| 170 |
indent=2,
|
| 171 |
),
|
|
|
|
| 176 |
return train_df.reset_index(drop=True), val_df.reset_index(drop=True)
|
| 177 |
|
| 178 |
|
| 179 |
+
def append_augmented_rows(base_df: pd.DataFrame, train_df: pd.DataFrame, args) -> pd.DataFrame:
|
| 180 |
+
if args.augmented_data_dir is None: return train_df
|
| 181 |
+
augmented = load_dermoscopic_dataframe(args.augmented_data_dir)
|
| 182 |
+
augmented = augmented[~augmented["lesion_id"].astype(str).isin(set(base_df["lesion_id"].astype(str)))].copy()
|
| 183 |
+
if args.augmented_classes:
|
| 184 |
+
allowed = {name.upper() for name in args.augmented_classes}
|
| 185 |
+
unknown = allowed - {name.upper() for name in base_df["label"].unique()}
|
| 186 |
+
if unknown: raise ValueError(f"Unknown augmented classes: {sorted(unknown)}")
|
| 187 |
+
augmented = augmented[augmented["label"].str.upper().isin(allowed)]
|
| 188 |
+
if args.augmented_max_per_class < 0: raise ValueError("--augmented-max-per-class must be >=0.")
|
| 189 |
+
if args.augmented_max_per_class:
|
| 190 |
+
augmented = augmented.sample(frac=1, random_state=args.seed).groupby("label", group_keys=False).head(args.augmented_max_per_class)
|
| 191 |
+
augmented["is_augmented"] = True; augmented["ignore_metadata"] = bool(args.zero_augmented_metadata)
|
| 192 |
+
return pd.concat([train_df, augmented], ignore_index=True, sort=False)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
def make_transforms(image_size: int):
|
| 196 |
normalize = transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
|
| 197 |
train_transform = transforms.Compose(
|
|
|
|
| 216 |
self.df = df.reset_index(drop=True)
|
| 217 |
self.labels = None if label_to_idx is None or "label" not in df else [label_to_idx[x] for x in self.df["label"]]
|
| 218 |
self.metadata = np.stack([metadata_vector(row, metadata_spec) for _, row in self.df.iterrows()])
|
| 219 |
+
if "ignore_metadata" in self.df:
|
| 220 |
+
self.metadata[self.df["ignore_metadata"].fillna(False).astype(bool).to_numpy()] = 0
|
| 221 |
self.transform = transform
|
| 222 |
|
| 223 |
def __len__(self) -> int:
|
|
|
|
| 245 |
counts = np.bincount(labels, minlength=len(label_to_idx))
|
| 246 |
if np.any(counts == 0):
|
| 247 |
raise ValueError("Cannot use weighted sampler with an empty training class.")
|
| 248 |
+
weights = (1.0 / np.power(counts.astype(np.float64), args.sampler_power))[labels]
|
| 249 |
generator = torch.Generator().manual_seed(args.seed)
|
| 250 |
sampler = WeightedRandomSampler(torch.as_tensor(weights, dtype=torch.double), len(labels), True, generator=generator)
|
| 251 |
common = dict(batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=torch.cuda.is_available())
|
milk10k_effb2_dermoscopic_metadata/inference.py
CHANGED
|
@@ -21,15 +21,18 @@ def parse_args(argv=None):
|
|
| 21 |
parser = argparse.ArgumentParser(description="Predict with dermoscopic-only metadata checkpoints.")
|
| 22 |
parser.add_argument("--checkpoint", type=Path, nargs="*", default=[])
|
| 23 |
parser.add_argument("--checkpoint-dir", type=Path, default=None)
|
| 24 |
-
parser.add_argument("--
|
| 25 |
-
parser.add_argument("--
|
|
|
|
| 26 |
parser.add_argument("--groundtruth-csv", type=Path, default=None)
|
| 27 |
parser.add_argument("--output", type=Path, required=True)
|
| 28 |
parser.add_argument("--batch-size", type=int, default=32)
|
| 29 |
parser.add_argument("--num-workers", type=int, default=0)
|
| 30 |
parser.add_argument("--image-size", type=int, default=None)
|
| 31 |
parser.add_argument("--tta-flips", action="store_true")
|
|
|
|
| 32 |
parser.add_argument("--no-auto-calibration", action="store_true")
|
|
|
|
| 33 |
return parser.parse_args(argv)
|
| 34 |
|
| 35 |
|
|
@@ -79,6 +82,7 @@ def build_model(checkpoint, device):
|
|
| 79 |
len(checkpoint["class_names"]), input_dim, saved["metadata_mode"], saved.get("backbone", "efficientnet_b2"), False,
|
| 80 |
int(saved.get("branch_dim", 512)), int(saved.get("metadata_dim", 64)), int(saved.get("classifier_hidden_dim", 512)),
|
| 81 |
float(saved.get("dropout", 0.3)), checkpoint.get("backbone_backend_resolved", saved.get("backbone_backend", "timm")).replace("auto", "timm"),
|
|
|
|
| 82 |
).to(device)
|
| 83 |
model.load_state_dict(checkpoint["model_state"]); model.eval()
|
| 84 |
return model
|
|
@@ -100,19 +104,27 @@ def predict(model, loader, device, tta):
|
|
| 100 |
def run(args):
|
| 101 |
paths = checkpoint_paths(args); device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 102 |
checkpoints = [torch.load(path, map_location=device, weights_only=False) for path in paths]
|
| 103 |
-
class_names = checkpoints[0]["class_names"]
|
| 104 |
for checkpoint in checkpoints[1:]:
|
| 105 |
-
if checkpoint["class_names"] != class_names
|
| 106 |
-
raise ValueError("Ensemble checkpoints have incompatible class names
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
df = load_dataframe(args.input_dir, args.metadata_csv, args.groundtruth_csv)
|
| 108 |
size = args.image_size or int(checkpoints[0]["args"].get("image_size", 260))
|
| 109 |
_, transform = make_transforms(size)
|
| 110 |
-
dataset = DermoscopicMetadataDataset(df, None, spec, transform)
|
| 111 |
-
loader = DataLoader(dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, pin_memory=torch.cuda.is_available())
|
| 112 |
ensemble = []
|
| 113 |
for path, checkpoint in zip(paths, checkpoints):
|
|
|
|
|
|
|
| 114 |
probs = predict(build_model(checkpoint, device), loader, device, args.tta_flips)
|
| 115 |
-
calibration_path = path.parent / "calibration.json"
|
| 116 |
if not args.no_auto_calibration and calibration_path.exists():
|
| 117 |
calibration = json.loads(calibration_path.read_text(encoding="utf-8"))
|
| 118 |
if calibration["class_names"] != class_names:
|
|
@@ -120,7 +132,11 @@ def run(args):
|
|
| 120 |
probs = apply_class_bias(probs, np.asarray(calibration["class_bias"], dtype=np.float32))
|
| 121 |
ensemble.append(probs)
|
| 122 |
y_prob = np.mean(ensemble, axis=0)
|
| 123 |
-
output = pd.DataFrame(y_prob, columns=class_names)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
args.output.parent.mkdir(parents=True, exist_ok=True); output.to_csv(args.output, index=False)
|
| 125 |
if "label" in df and df["label"].notna().all():
|
| 126 |
mapping = {name: index for index, name in enumerate(class_names)}
|
|
|
|
| 21 |
parser = argparse.ArgumentParser(description="Predict with dermoscopic-only metadata checkpoints.")
|
| 22 |
parser.add_argument("--checkpoint", type=Path, nargs="*", default=[])
|
| 23 |
parser.add_argument("--checkpoint-dir", type=Path, default=None)
|
| 24 |
+
parser.add_argument("--data-dir", type=Path, default=None)
|
| 25 |
+
parser.add_argument("--input-dir", type=Path, default=None)
|
| 26 |
+
parser.add_argument("--metadata-csv", type=Path, default=None)
|
| 27 |
parser.add_argument("--groundtruth-csv", type=Path, default=None)
|
| 28 |
parser.add_argument("--output", type=Path, required=True)
|
| 29 |
parser.add_argument("--batch-size", type=int, default=32)
|
| 30 |
parser.add_argument("--num-workers", type=int, default=0)
|
| 31 |
parser.add_argument("--image-size", type=int, default=None)
|
| 32 |
parser.add_argument("--tta-flips", action="store_true")
|
| 33 |
+
parser.add_argument("--calibration-file", type=Path, default=None)
|
| 34 |
parser.add_argument("--no-auto-calibration", action="store_true")
|
| 35 |
+
parser.add_argument("--include-debug-columns", action="store_true")
|
| 36 |
return parser.parse_args(argv)
|
| 37 |
|
| 38 |
|
|
|
|
| 82 |
len(checkpoint["class_names"]), input_dim, saved["metadata_mode"], saved.get("backbone", "efficientnet_b2"), False,
|
| 83 |
int(saved.get("branch_dim", 512)), int(saved.get("metadata_dim", 64)), int(saved.get("classifier_hidden_dim", 512)),
|
| 84 |
float(saved.get("dropout", 0.3)), checkpoint.get("backbone_backend_resolved", saved.get("backbone_backend", "timm")).replace("auto", "timm"),
|
| 85 |
+
saved.get("metadata_gate_hidden_dim"),
|
| 86 |
).to(device)
|
| 87 |
model.load_state_dict(checkpoint["model_state"]); model.eval()
|
| 88 |
return model
|
|
|
|
| 104 |
def run(args):
|
| 105 |
paths = checkpoint_paths(args); device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 106 |
checkpoints = [torch.load(path, map_location=device, weights_only=False) for path in paths]
|
| 107 |
+
class_names = checkpoints[0]["class_names"]
|
| 108 |
for checkpoint in checkpoints[1:]:
|
| 109 |
+
if checkpoint["class_names"] != class_names:
|
| 110 |
+
raise ValueError("Ensemble checkpoints have incompatible class names.")
|
| 111 |
+
if args.data_dir is not None:
|
| 112 |
+
data_dir=args.data_dir.expanduser().resolve()
|
| 113 |
+
default_input=data_dir/"MILK10k_Training_Input"
|
| 114 |
+
if not default_input.exists():default_input=data_dir.parent/"MILK10k_Training_Input"
|
| 115 |
+
args.input_dir=args.input_dir or default_input
|
| 116 |
+
args.metadata_csv=args.metadata_csv or data_dir/"MILK10k_Training_Metadata.csv"
|
| 117 |
+
if args.groundtruth_csv is None and (data_dir/"MILK10k_Training_GroundTruth.csv").exists():args.groundtruth_csv=data_dir/"MILK10k_Training_GroundTruth.csv"
|
| 118 |
+
if args.input_dir is None or args.metadata_csv is None:raise ValueError("Pass --data-dir or both --input-dir and --metadata-csv.")
|
| 119 |
df = load_dataframe(args.input_dir, args.metadata_csv, args.groundtruth_csv)
|
| 120 |
size = args.image_size or int(checkpoints[0]["args"].get("image_size", 260))
|
| 121 |
_, transform = make_transforms(size)
|
|
|
|
|
|
|
| 122 |
ensemble = []
|
| 123 |
for path, checkpoint in zip(paths, checkpoints):
|
| 124 |
+
dataset = DermoscopicMetadataDataset(df, None, checkpoint["metadata_spec"], transform)
|
| 125 |
+
loader = DataLoader(dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, pin_memory=torch.cuda.is_available())
|
| 126 |
probs = predict(build_model(checkpoint, device), loader, device, args.tta_flips)
|
| 127 |
+
calibration_path = args.calibration_file.expanduser().resolve() if args.calibration_file else path.parent / "calibration.json"
|
| 128 |
if not args.no_auto_calibration and calibration_path.exists():
|
| 129 |
calibration = json.loads(calibration_path.read_text(encoding="utf-8"))
|
| 130 |
if calibration["class_names"] != class_names:
|
|
|
|
| 132 |
probs = apply_class_bias(probs, np.asarray(calibration["class_bias"], dtype=np.float32))
|
| 133 |
ensemble.append(probs)
|
| 134 |
y_prob = np.mean(ensemble, axis=0)
|
| 135 |
+
output = pd.DataFrame(y_prob, columns=class_names)
|
| 136 |
+
if args.include_debug_columns:
|
| 137 |
+
output.insert(0,"confidence",y_prob.max(1));output.insert(0,"predicted_label",[class_names[i] for i in y_prob.argmax(1)])
|
| 138 |
+
if "isic_id" in df:output.insert(0,"isic_id",df["isic_id"].tolist())
|
| 139 |
+
output.insert(0, "lesion_id", df["lesion_id"].tolist())
|
| 140 |
args.output.parent.mkdir(parents=True, exist_ok=True); output.to_csv(args.output, index=False)
|
| 141 |
if "label" in df and df["label"].notna().all():
|
| 142 |
mapping = {name: index for index, name in enumerate(class_names)}
|
milk10k_effb2_dermoscopic_metadata/losses.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Classification losses for the dermoscopic-only trainer."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
from sklearn.utils.class_weight import compute_class_weight
|
| 10 |
+
from torch import nn
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class FocalLoss(nn.Module):
|
| 14 |
+
def __init__(self, weight=None, gamma=2.0):
|
| 15 |
+
super().__init__(); self.weight = weight; self.gamma = gamma
|
| 16 |
+
|
| 17 |
+
def forward(self, logits, labels):
|
| 18 |
+
ce = F.cross_entropy(logits, labels, reduction="none")
|
| 19 |
+
loss = (1.0 - torch.exp(-ce)) ** self.gamma * ce
|
| 20 |
+
if self.weight is not None: loss = loss * self.weight[labels]
|
| 21 |
+
return loss.mean()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class LDAMLoss(nn.Module):
|
| 25 |
+
def __init__(self, class_counts, beta=.9999, max_margin=.5, deferred_start_epoch=0, alpha_max=10.0):
|
| 26 |
+
super().__init__()
|
| 27 |
+
counts = class_counts.float().clamp_min(1)
|
| 28 |
+
margins = 1.0 / torch.sqrt(torch.sqrt(counts)); margins *= max_margin / margins.max().clamp_min(1e-12)
|
| 29 |
+
alpha = effective_number_alpha(counts, beta).clamp(max=alpha_max); alpha *= counts.numel() / alpha.sum().clamp_min(1e-12)
|
| 30 |
+
self.register_buffer("margins", margins); self.register_buffer("alpha", alpha)
|
| 31 |
+
self.deferred_start_epoch = deferred_start_epoch; self.current_epoch = 0
|
| 32 |
+
|
| 33 |
+
def set_epoch(self, epoch): self.current_epoch = epoch
|
| 34 |
+
|
| 35 |
+
def forward(self, logits, labels):
|
| 36 |
+
adjusted = logits.clone(); rows = torch.arange(labels.size(0), device=labels.device)
|
| 37 |
+
adjusted[rows, labels] -= self.margins.to(logits)[labels]
|
| 38 |
+
loss = F.cross_entropy(adjusted, labels, reduction="none")
|
| 39 |
+
if self.current_epoch >= self.deferred_start_epoch: loss *= self.alpha.to(logits)[labels]
|
| 40 |
+
return loss.mean()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class SoftMacroDiceLoss(nn.Module):
|
| 44 |
+
def forward(self, logits, labels):
|
| 45 |
+
probs = torch.softmax(logits, 1); target = F.one_hot(labels, logits.size(1)).to(probs.dtype)
|
| 46 |
+
score = (2 * (probs * target).sum(0) + 1e-6) / (probs.sum(0) + target.sum(0) + 1e-6)
|
| 47 |
+
return 1 - score.mean()
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class SoftMacroF1Loss(nn.Module):
|
| 51 |
+
def __init__(self, class_weights=None):
|
| 52 |
+
super().__init__()
|
| 53 |
+
if class_weights is not None: self.register_buffer("class_weights", class_weights.float())
|
| 54 |
+
else: self.class_weights = None
|
| 55 |
+
|
| 56 |
+
def forward(self, logits, labels):
|
| 57 |
+
probs = torch.softmax(logits, 1); target = F.one_hot(labels, logits.size(1)).to(probs.dtype)
|
| 58 |
+
tp = (probs * target).sum(0); fp = (probs * (1-target)).sum(0); fn = ((1-probs) * target).sum(0)
|
| 59 |
+
f1 = (2*tp + 1e-6) / (2*tp + fp + fn + 1e-6)
|
| 60 |
+
if self.class_weights is None: return 1 - f1.mean()
|
| 61 |
+
weights = self.class_weights.to(probs); return 1 - (f1 * weights).sum() / weights.sum().clamp_min(1e-6)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class CompositeClassificationLoss(nn.Module):
|
| 65 |
+
def __init__(self, primary, auxiliary, weight):
|
| 66 |
+
super().__init__(); self.primary = primary; self.auxiliary = auxiliary; self.weight = weight
|
| 67 |
+
def forward(self, logits, labels): return self.primary(logits, labels) + self.weight * self.auxiliary(logits, labels)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def effective_number_alpha(counts, beta):
|
| 71 |
+
if beta <= 0: return torch.ones_like(counts)
|
| 72 |
+
if beta >= 1: raise ValueError("--ldam-beta must be less than 1")
|
| 73 |
+
b = torch.tensor(beta, dtype=counts.dtype, device=counts.device)
|
| 74 |
+
return (1-b) / (1-torch.pow(b, counts)).clamp_min(1e-12)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def class_counts(train_df, label_to_idx, device):
|
| 78 |
+
values = np.bincount([label_to_idx[x] for x in train_df.label], minlength=len(label_to_idx))
|
| 79 |
+
if np.any(values == 0): raise ValueError("Train split contains an empty class.")
|
| 80 |
+
return torch.tensor(values, dtype=torch.float32, device=device)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def f1_weights(label_to_idx, args, device):
|
| 84 |
+
weights = torch.ones(len(label_to_idx), device=device)
|
| 85 |
+
normalized = {name.upper(): name for name in label_to_idx}
|
| 86 |
+
for name in args.f1_ignore_classes:
|
| 87 |
+
key = name.upper();
|
| 88 |
+
if key not in normalized: raise ValueError(f"Unknown F1 class: {name}")
|
| 89 |
+
weights[label_to_idx[normalized[key]]] = 0
|
| 90 |
+
for item in args.f1_class_weight:
|
| 91 |
+
if "=" not in item: raise ValueError(f"Expected CLASS=VALUE: {item}")
|
| 92 |
+
name, raw = item.split("=", 1); value = float(raw)
|
| 93 |
+
if value < 0 or name.upper() not in normalized: raise ValueError(f"Invalid F1 class weight: {item}")
|
| 94 |
+
weights[label_to_idx[normalized[name.upper()]]] = value
|
| 95 |
+
if weights.sum() <= 0: raise ValueError("F1 class weights sum to zero.")
|
| 96 |
+
return weights
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def build_loss(train_df: pd.DataFrame, label_to_idx, args, device):
|
| 100 |
+
if args.loss == "ldam":
|
| 101 |
+
return LDAMLoss(class_counts(train_df, label_to_idx, device), args.ldam_beta, args.ldam_max_margin,
|
| 102 |
+
args.ldam_drw_start_epoch, args.ldam_alpha_max)
|
| 103 |
+
weight = None
|
| 104 |
+
if args.class_weight:
|
| 105 |
+
y = np.array([label_to_idx[x] for x in train_df.label])
|
| 106 |
+
weight = torch.tensor(compute_class_weight("balanced", classes=np.arange(len(label_to_idx)), y=y), dtype=torch.float32, device=device)
|
| 107 |
+
ce = nn.CrossEntropyLoss(weight=weight)
|
| 108 |
+
if args.loss == "focal": return FocalLoss(weight, args.focal_gamma)
|
| 109 |
+
if args.loss == "ce_dice": return CompositeClassificationLoss(ce, SoftMacroDiceLoss(), args.dice_weight)
|
| 110 |
+
if args.loss == "ce_f1": return CompositeClassificationLoss(ce, SoftMacroF1Loss(f1_weights(label_to_idx,args,device)), args.f1_weight)
|
| 111 |
+
return ce
|
milk10k_effb2_dermoscopic_metadata/model.py
CHANGED
|
@@ -52,6 +52,7 @@ class DermoscopicMetadataClassifier(nn.Module):
|
|
| 52 |
self, num_classes: int, metadata_input_dim: int, metadata_mode: str = "none", backbone: str = "efficientnet_b2",
|
| 53 |
imagenet_pretrained: bool = True, branch_dim: int = 512, metadata_dim: int = 64,
|
| 54 |
classifier_hidden_dim: int = 512, dropout: float = 0.3, backbone_backend: str = "timm",
|
|
|
|
| 55 |
):
|
| 56 |
super().__init__()
|
| 57 |
if metadata_mode not in METADATA_MODES:
|
|
@@ -68,9 +69,10 @@ class DermoscopicMetadataClassifier(nn.Module):
|
|
| 68 |
else:
|
| 69 |
self.metadata_head = MetadataHead(metadata_input_dim, metadata_dim, dropout)
|
| 70 |
if metadata_mode in ("gated_concat", "gated_only"):
|
|
|
|
| 71 |
self.metadata_gate = nn.Sequential(
|
| 72 |
-
nn.LayerNorm(metadata_input_dim), nn.Linear(metadata_input_dim,
|
| 73 |
-
nn.Linear(
|
| 74 |
)
|
| 75 |
nn.init.zeros_(self.metadata_gate[-2].weight)
|
| 76 |
nn.init.constant_(self.metadata_gate[-2].bias, 2.0)
|
|
@@ -98,3 +100,9 @@ class DermoscopicMetadataClassifier(nn.Module):
|
|
| 98 |
def set_encoder_trainable(model: DermoscopicMetadataClassifier, trainable: bool) -> None:
|
| 99 |
for parameter in model.encoder.parameters():
|
| 100 |
parameter.requires_grad = trainable
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
self, num_classes: int, metadata_input_dim: int, metadata_mode: str = "none", backbone: str = "efficientnet_b2",
|
| 53 |
imagenet_pretrained: bool = True, branch_dim: int = 512, metadata_dim: int = 64,
|
| 54 |
classifier_hidden_dim: int = 512, dropout: float = 0.3, backbone_backend: str = "timm",
|
| 55 |
+
metadata_gate_hidden_dim: int | None = None,
|
| 56 |
):
|
| 57 |
super().__init__()
|
| 58 |
if metadata_mode not in METADATA_MODES:
|
|
|
|
| 69 |
else:
|
| 70 |
self.metadata_head = MetadataHead(metadata_input_dim, metadata_dim, dropout)
|
| 71 |
if metadata_mode in ("gated_concat", "gated_only"):
|
| 72 |
+
gate_hidden = metadata_gate_hidden_dim or metadata_dim
|
| 73 |
self.metadata_gate = nn.Sequential(
|
| 74 |
+
nn.LayerNorm(metadata_input_dim), nn.Linear(metadata_input_dim, gate_hidden), nn.GELU(),
|
| 75 |
+
nn.Linear(gate_hidden, branch_dim), nn.Sigmoid()
|
| 76 |
)
|
| 77 |
nn.init.zeros_(self.metadata_gate[-2].weight)
|
| 78 |
nn.init.constant_(self.metadata_gate[-2].bias, 2.0)
|
|
|
|
| 100 |
def set_encoder_trainable(model: DermoscopicMetadataClassifier, trainable: bool) -> None:
|
| 101 |
for parameter in model.encoder.parameters():
|
| 102 |
parameter.requires_grad = trainable
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def set_metadata_trainable(model: DermoscopicMetadataClassifier, trainable: bool) -> None:
|
| 106 |
+
for module in (model.metadata_head, model.metadata_gate):
|
| 107 |
+
if module is not None:
|
| 108 |
+
for parameter in module.parameters(): parameter.requires_grad = trainable
|
milk10k_effb2_dermoscopic_metadata/reporting.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Structured data, prediction, confusion, environment, and k-fold reports."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json, platform, subprocess, sys
|
| 6 |
+
from datetime import datetime, timezone
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
from .core import json_safe
|
| 11 |
+
from .data import synthetic_mask
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def environment_info():
|
| 15 |
+
import torch
|
| 16 |
+
def git(*args):
|
| 17 |
+
try: return subprocess.run(["git",*args],capture_output=True,text=True,timeout=5).stdout.strip()
|
| 18 |
+
except Exception: return None
|
| 19 |
+
return {"timestamp_utc":datetime.now(timezone.utc).isoformat(),"cwd":str(Path.cwd()),"command":sys.argv,
|
| 20 |
+
"python":sys.version.replace("\n"," "),"platform":platform.platform(),"executable":sys.executable,
|
| 21 |
+
"torch":{"version":torch.__version__,"cuda_available":torch.cuda.is_available(),
|
| 22 |
+
"device":torch.cuda.get_device_name(0) if torch.cuda.is_available() else None},
|
| 23 |
+
"git":{"commit":git("rev-parse","HEAD"),"branch":git("rev-parse","--abbrev-ref","HEAD"),
|
| 24 |
+
"status_short":(git("status","--short") or "").splitlines()}}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def distribution(df, class_names):
|
| 28 |
+
synth = synthetic_mask(df); ignored = df.get("ignore_metadata",pd.Series(False,index=df.index)).fillna(False).astype(bool).to_numpy()
|
| 29 |
+
return {"rows":len(df),"real_rows":int((~synth).sum()),"synthetic_rows":int(synth.sum()),
|
| 30 |
+
"ignore_metadata_rows":int(ignored.sum()),
|
| 31 |
+
"class_counts":df.label.value_counts().reindex(class_names,fill_value=0).astype(int).to_dict(),
|
| 32 |
+
"synthetic_class_counts":df.loc[synth,"label"].value_counts().reindex(class_names,fill_value=0).astype(int).to_dict()}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def save_data_summary(output_dir, full_df, train_df, val_df, class_names):
|
| 36 |
+
payload={"full":distribution(full_df,class_names),"train":distribution(train_df,class_names),"val":distribution(val_df,class_names),
|
| 37 |
+
"synthetic_train_only":bool(synthetic_mask(train_df).sum() and not synthetic_mask(val_df).sum())}
|
| 38 |
+
(output_dir/"data_summary.json").write_text(json.dumps(json_safe(payload),indent=2),encoding="utf-8")
|
| 39 |
+
lines=["# Split Summary",""]
|
| 40 |
+
for split in ("full","train","val"):
|
| 41 |
+
item=payload[split]; lines += [f"## {split.title()}","",f"- rows: {item['rows']}",f"- real: {item['real_rows']}",f"- synthetic: {item['synthetic_rows']}","","| class | count | synthetic |","|---|---:|---:|"]
|
| 42 |
+
lines += [f"| {name} | {count} | {item['synthetic_class_counts'][name]} |" for name,count in item["class_counts"].items()]; lines.append("")
|
| 43 |
+
(output_dir/"split_summary.md").write_text("\n".join(lines),encoding="utf-8")
|
| 44 |
+
return payload
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def prediction_summary(prob, class_names):
|
| 48 |
+
pred=prob.argmax(1); sorted_prob=np.sort(prob,axis=1); confidence=sorted_prob[:,-1]; second=sorted_prob[:,-2]
|
| 49 |
+
entropy=-np.sum(prob*np.log(np.clip(prob,1e-12,1)),axis=1); counts=np.bincount(pred,minlength=len(class_names))
|
| 50 |
+
return {"rows":len(prob),"predicted_class_counts":{n:int(counts[i]) for i,n in enumerate(class_names)},
|
| 51 |
+
"mean_probability":{n:float(prob[:,i].mean()) for i,n in enumerate(class_names)},
|
| 52 |
+
"mean_confidence":float(confidence.mean()),"median_confidence":float(np.median(confidence)),
|
| 53 |
+
"mean_top1_top2_gap":float((confidence-second).mean()),"mean_entropy":float(entropy.mean()),
|
| 54 |
+
"low_confidence_rows":int((confidence<.5).sum())}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def confusion_analysis(cm,class_names):
|
| 58 |
+
pairs=[]
|
| 59 |
+
for i,true in enumerate(class_names):
|
| 60 |
+
total=int(cm[i].sum())
|
| 61 |
+
for j,pred in enumerate(class_names):
|
| 62 |
+
if i!=j and cm[i,j]: pairs.append({"true":true,"predicted":pred,"count":int(cm[i,j]),"rate_of_true":float(cm[i,j]/total) if total else 0})
|
| 63 |
+
return {"top_confusion_pairs":sorted(pairs,key=lambda x:x["count"],reverse=True)[:20]}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def save_diagnostics(output_dir,args,data_summary,metrics,per_class,cm,prob,class_names,fold=None):
|
| 67 |
+
pred=prediction_summary(prob,class_names); conf=confusion_analysis(cm,class_names); warnings=[]
|
| 68 |
+
for row in per_class.to_dict("records"):
|
| 69 |
+
if row["support"]<=5: warnings.append({"severity":"medium","code":"tiny_validation_support","class":row["class"]})
|
| 70 |
+
if row["recall_sensitivity"]==0: warnings.append({"severity":"high","code":"zero_recall","class":row["class"]})
|
| 71 |
+
diag={"fold":fold,"warnings":warnings,"prediction_summary":pred,"confusion_analysis":conf}
|
| 72 |
+
for name,value in (("prediction_summary",pred),("confusion_analysis",conf),("run_diagnostics",diag)):
|
| 73 |
+
(output_dir/f"{name}.json").write_text(json.dumps(json_safe(value),indent=2),encoding="utf-8")
|
| 74 |
+
lines=["# Dermoscopic Run Report","",f"- fold: {fold}",f"- backbone: {args.backbone}",f"- metadata_mode: {args.metadata_mode}",f"- loss: {args.loss}","","## Metrics",""]
|
| 75 |
+
lines += [f"- {key}: {metrics.get(key)}" for key in ("accuracy","balanced_accuracy","f1_macro","dice_macro","roc_auc_macro_ovr","top3_accuracy")]
|
| 76 |
+
lines += ["","## Per class","","```",per_class.to_string(index=False),"```","","## Top confusions",""]
|
| 77 |
+
lines += [f"- {x['true']} -> {x['predicted']}: {x['count']} ({x['rate_of_true']:.1%})" for x in conf["top_confusion_pairs"][:12]]
|
| 78 |
+
lines += ["","## Warnings",""]+[f"- [{x['severity']}] {x['code']}: {x.get('class','')}" for x in warnings]
|
| 79 |
+
(output_dir/"run_report.md").write_text("\n".join(lines),encoding="utf-8")
|
| 80 |
+
return diag
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def save_kfold_summary(metrics_list,output_dir):
|
| 84 |
+
keys=("best_selection_metric","best_val_tail_recall_macro","accuracy","balanced_accuracy","f1_macro","f1_weighted","dice_macro","roc_auc_macro_ovr","top3_accuracy")
|
| 85 |
+
rows=[{"fold":i,**{k:m.get(k) for k in keys}} for i,m in enumerate(metrics_list)]
|
| 86 |
+
frame=pd.DataFrame(rows); frame.to_csv(output_dir/"kfold_summary.csv",index=False)
|
| 87 |
+
payload={"folds":rows,"mean":{},"std":{}}
|
| 88 |
+
for key in keys:
|
| 89 |
+
values=pd.to_numeric(frame[key],errors="coerce").dropna(); payload["mean"][key]=None if values.empty else float(values.mean()); payload["std"][key]=None if values.empty else float(values.std(ddof=0))
|
| 90 |
+
(output_dir/"kfold_summary.json").write_text(json.dumps(json_safe(payload),indent=2),encoding="utf-8")
|
| 91 |
+
(output_dir/"kfold_report.md").write_text("# K-fold Summary\n\n```\n"+frame.to_string(index=False)+"\n```\n",encoding="utf-8")
|
| 92 |
+
return payload
|
milk10k_effb2_dermoscopic_metadata/training.py
CHANGED
|
@@ -1,256 +1,244 @@
|
|
| 1 |
-
"""Training
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
-
import argparse
|
| 6 |
-
import json
|
| 7 |
from pathlib import Path
|
| 8 |
-
|
| 9 |
import numpy as np
|
| 10 |
import pandas as pd
|
| 11 |
import torch
|
| 12 |
-
from sklearn.metrics import balanced_accuracy_score, precision_recall_fscore_support
|
| 13 |
from torch.amp import GradScaler, autocast
|
| 14 |
from tqdm.auto import tqdm
|
| 15 |
|
| 16 |
-
from .core import apply_class_bias,
|
| 17 |
-
from .data import create_or_load_split, fit_metadata_spec, load_dermoscopic_dataframe,
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
parser = argparse.ArgumentParser(description="Train an EfficientNet dermoscopic-only classifier with optional metadata.")
|
| 23 |
-
parser.add_argument("--data-dir", type=Path, required=True)
|
| 24 |
-
parser.add_argument("--input-dir", type=Path, default=None, help="Optional image root; defaults to data-dir or its parent/MILK10k_Training_Input.")
|
| 25 |
-
parser.add_argument("--output-dir", type=Path, required=True)
|
| 26 |
-
parser.add_argument("--split-manifest", type=Path, required=True, help="Shared JSON split; created once and reused exactly.")
|
| 27 |
-
parser.add_argument("--metadata-mode", choices=METADATA_MODES, default="none")
|
| 28 |
-
parser.add_argument("--backbone", default="efficientnet_b2")
|
| 29 |
-
parser.add_argument("--backbone-backend", choices=["auto", "timm", "torchvision"], default="auto")
|
| 30 |
-
parser.add_argument("--encoder-checkpoint", type=Path, default=None)
|
| 31 |
-
parser.add_argument("--resume-checkpoint", type=Path, default=None)
|
| 32 |
-
parser.add_argument("--image-size", type=int, default=260)
|
| 33 |
-
parser.add_argument("--batch-size", type=int, default=16)
|
| 34 |
-
parser.add_argument("--num-workers", type=int, default=0)
|
| 35 |
-
parser.add_argument("--freeze-epochs", type=int, default=5)
|
| 36 |
-
parser.add_argument("--finetune-epochs", type=int, default=20)
|
| 37 |
-
parser.add_argument("--head-lr", type=float, default=1e-4)
|
| 38 |
-
parser.add_argument("--encoder-lr", type=float, default=1e-5)
|
| 39 |
-
parser.add_argument("--weight-decay", type=float, default=1e-4)
|
| 40 |
-
parser.add_argument("--branch-dim", type=int, default=512)
|
| 41 |
-
parser.add_argument("--metadata-dim", type=int, default=64)
|
| 42 |
-
parser.add_argument("--classifier-hidden-dim", type=int, default=512)
|
| 43 |
-
parser.add_argument("--dropout", type=float, default=0.3)
|
| 44 |
-
parser.add_argument("--loss", choices=["ce", "ce_dice"], default="ce")
|
| 45 |
-
parser.add_argument("--dice-weight", type=float, default=0.3)
|
| 46 |
-
parser.add_argument("--class-weight", action="store_true")
|
| 47 |
-
parser.add_argument("--weighted-sampler", action="store_true")
|
| 48 |
-
parser.add_argument("--amp", action="store_true")
|
| 49 |
-
parser.add_argument("--val-size", type=float, default=0.2)
|
| 50 |
-
parser.add_argument("--seed", type=int, default=42)
|
| 51 |
-
parser.add_argument("--patience", type=int, default=6)
|
| 52 |
-
parser.add_argument("--calibrate-bias", action="store_true")
|
| 53 |
-
parser.add_argument("--calibration-max-bias", type=float, default=1.5)
|
| 54 |
-
parser.add_argument("--calibration-step", type=float, default=0.25)
|
| 55 |
-
parser.add_argument("--calibration-passes", type=int, default=3)
|
| 56 |
-
return parser.parse_args(argv)
|
| 57 |
|
|
|
|
| 58 |
|
| 59 |
-
def class_weight_tensor(train_df, class_names, device):
|
| 60 |
-
counts = train_df["label"].value_counts().reindex(class_names, fill_value=0).to_numpy(dtype=np.float64)
|
| 61 |
-
if np.any(counts == 0):
|
| 62 |
-
raise ValueError("Cannot calculate class weights with an empty training class.")
|
| 63 |
-
weights = len(train_df) / (len(class_names) * counts)
|
| 64 |
-
return torch.tensor(weights, dtype=torch.float32, device=device)
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
while changed:
|
| 76 |
-
changed
|
| 77 |
-
for prefix in
|
| 78 |
-
if key.startswith(prefix):
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
if
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
groups
|
| 108 |
-
if
|
| 109 |
-
|
| 110 |
-
return torch.optim.AdamW(groups,
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
def
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
metadata = batch["metadata"].to(device, non_blocking=True)
|
| 122 |
-
labels = batch["label"].to(device, non_blocking=True)
|
| 123 |
-
if training:
|
| 124 |
-
optimizer.zero_grad(set_to_none=True)
|
| 125 |
with torch.set_grad_enabled(training):
|
| 126 |
-
with autocast(device.type,
|
| 127 |
-
logits = model(image, metadata)
|
| 128 |
-
loss = criterion(logits, labels)
|
| 129 |
if training:
|
| 130 |
-
scaler.scale(loss).backward()
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
|
|
|
| 143 |
|
| 144 |
|
| 145 |
@torch.no_grad()
|
| 146 |
-
def predict(model,
|
| 147 |
-
model.eval();
|
| 148 |
-
for batch in tqdm(loader,
|
| 149 |
-
logits
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
train_df
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
backbone_backend = "timm" if backbone_backend == "auto" else backbone_backend
|
| 179 |
-
elif args.encoder_checkpoint:
|
| 180 |
-
backbone_backend = infer_checkpoint_backend(args.encoder_checkpoint, device)
|
| 181 |
-
else:
|
| 182 |
-
backbone_backend = "timm"
|
| 183 |
-
else:
|
| 184 |
-
backbone_backend = args.backbone_backend
|
| 185 |
-
args.backbone_backend = backbone_backend
|
| 186 |
-
|
| 187 |
-
model = DermoscopicMetadataClassifier(
|
| 188 |
-
len(class_names), metadata_input_dim, args.metadata_mode, args.backbone,
|
| 189 |
-
args.encoder_checkpoint is None and args.resume_checkpoint is None,
|
| 190 |
-
args.branch_dim, args.metadata_dim, args.classifier_hidden_dim, args.dropout, backbone_backend,
|
| 191 |
-
).to(device)
|
| 192 |
-
start_epoch, best = 1, float("-inf")
|
| 193 |
if args.resume_checkpoint:
|
| 194 |
-
resume
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
(
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
if
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
if val_stats["
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
print(f"{phase} epoch={
|
| 234 |
-
if
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
model.load_state_dict(best_checkpoint["model_state"])
|
| 239 |
-
y_true,
|
| 240 |
-
metrics
|
| 241 |
-
|
| 242 |
-
(output_dir
|
| 243 |
if args.calibrate_bias:
|
| 244 |
-
bias,
|
| 245 |
-
|
| 246 |
-
(output_dir
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
|
| 251 |
-
def main():
|
| 252 |
-
run(parse_args())
|
| 253 |
|
| 254 |
-
|
| 255 |
-
if
|
| 256 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Training orchestration for single-dermoscopic-image metadata models."""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
+
import argparse, json
|
|
|
|
| 6 |
from pathlib import Path
|
|
|
|
| 7 |
import numpy as np
|
| 8 |
import pandas as pd
|
| 9 |
import torch
|
| 10 |
+
from sklearn.metrics import balanced_accuracy_score, confusion_matrix, precision_recall_fscore_support
|
| 11 |
from torch.amp import GradScaler, autocast
|
| 12 |
from tqdm.auto import tqdm
|
| 13 |
|
| 14 |
+
from .core import apply_class_bias, compute_metrics, json_safe, optimize_class_bias, save_evaluation, set_seed
|
| 15 |
+
from .data import (append_augmented_rows, create_or_load_split, fit_metadata_spec, load_dermoscopic_dataframe,
|
| 16 |
+
make_loaders, metadata_vector, synthetic_mask)
|
| 17 |
+
from .losses import build_loss
|
| 18 |
+
from .model import DermoscopicMetadataClassifier, METADATA_MODES, set_encoder_trainable, set_metadata_trainable
|
| 19 |
+
from .reporting import environment_info, save_data_summary, save_diagnostics, save_kfold_summary
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
+
CHECKPOINT_SCHEMA_VERSION = 2
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
+
def parse_args(argv=None):
|
| 25 |
+
p=argparse.ArgumentParser(description="Train a dermoscopic-only classifier with optional metadata.")
|
| 26 |
+
p.add_argument("--data-dir",type=Path,required=True); p.add_argument("--input-dir",type=Path,default=None)
|
| 27 |
+
p.add_argument("--output-dir",type=Path,required=True); p.add_argument("--split-manifest",type=Path,required=True)
|
| 28 |
+
p.add_argument("--metadata-mode",choices=METADATA_MODES,default="none"); p.add_argument("--backbone",default="efficientnet_b2")
|
| 29 |
+
p.add_argument("--backbone-backend",choices=["auto","timm","torchvision"],default="auto")
|
| 30 |
+
p.add_argument("--encoder-checkpoint",type=Path,default=None); p.add_argument("--resume-checkpoint",type=Path,default=None)
|
| 31 |
+
p.add_argument("--imagenet-pretrained",action="store_true")
|
| 32 |
+
p.add_argument("--image-size",type=int,default=260); p.add_argument("--batch-size",type=int,default=16); p.add_argument("--num-workers",type=int,default=0)
|
| 33 |
+
p.add_argument("--freeze-epochs",type=int,default=5); p.add_argument("--finetune-epochs",type=int,default=20)
|
| 34 |
+
p.add_argument("--head-lr",type=float,default=1e-4); p.add_argument("--encoder-lr",type=float,default=1e-5); p.add_argument("--metadata-lr",type=float,default=None)
|
| 35 |
+
p.add_argument("--weight-decay",type=float,default=1e-4); p.add_argument("--branch-dim",type=int,default=512); p.add_argument("--metadata-dim",type=int,default=64)
|
| 36 |
+
p.add_argument("--metadata-gate-hidden-dim",type=int,default=None); p.add_argument("--freeze-metadata-head",action="store_true")
|
| 37 |
+
p.add_argument("--classifier-hidden-dim",type=int,default=512); p.add_argument("--dropout",type=float,default=.3)
|
| 38 |
+
p.add_argument("--loss",choices=["ce","focal","ldam","ce_dice","ce_f1"],default="ce")
|
| 39 |
+
p.add_argument("--focal-gamma",type=float,default=2.0); p.add_argument("--dice-weight",type=float,default=.3); p.add_argument("--f1-weight",type=float,default=.3)
|
| 40 |
+
p.add_argument("--f1-ignore-classes",nargs="*",default=[]); p.add_argument("--f1-class-weight",action="append",default=[])
|
| 41 |
+
p.add_argument("--ldam-beta",type=float,default=.9999); p.add_argument("--ldam-max-margin",type=float,default=.5)
|
| 42 |
+
p.add_argument("--ldam-drw-start-epoch",type=int,default=0); p.add_argument("--ldam-alpha-max",type=float,default=10.0); p.add_argument("--tail-num-classes",type=int,default=4)
|
| 43 |
+
p.add_argument("--class-weight",action="store_true"); p.add_argument("--weighted-sampler",action="store_true"); p.add_argument("--sampler-power",type=float,default=1.0)
|
| 44 |
+
p.add_argument("--synthetic-train-only",action="store_true"); p.add_argument("--augmented-data-dir",type=Path,default=None)
|
| 45 |
+
p.add_argument("--augmented-max-per-class",type=int,default=0); p.add_argument("--augmented-classes",nargs="*",default=[]); p.add_argument("--zero-augmented-metadata",action="store_true")
|
| 46 |
+
p.add_argument("--k-folds",type=int,default=1); p.add_argument("--val-size",type=float,default=.2); p.add_argument("--seed",type=int,default=42)
|
| 47 |
+
p.add_argument("--amp",action="store_true"); p.add_argument("--patience",type=int,default=6)
|
| 48 |
+
p.add_argument("--selection-metric",choices=["f1_macro","dice_macro"],default="f1_macro")
|
| 49 |
+
p.add_argument("--calibrate-bias",action="store_true"); p.add_argument("--calibration-metric",choices=["f1_macro","dice_macro"],default="dice_macro")
|
| 50 |
+
p.add_argument("--calibration-max-bias",type=float,default=1.5); p.add_argument("--calibration-step",type=float,default=.25); p.add_argument("--calibration-passes",type=int,default=3)
|
| 51 |
+
return p.parse_args(argv)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def extract_state(payload): return payload.get("model_state",payload.get("model_state_dict",payload.get("state_dict",payload)))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def infer_checkpoint_backend(path,device):
|
| 58 |
+
keys=list(extract_state(torch.load(path.expanduser().resolve(),map_location=device,weights_only=False)))
|
| 59 |
+
normalized=[]
|
| 60 |
+
for key in keys:
|
| 61 |
+
changed=True
|
| 62 |
while changed:
|
| 63 |
+
changed=False
|
| 64 |
+
for prefix in ("module.","model.","_orig_mod.","encoder.","dermoscopic_encoder."):
|
| 65 |
+
if key.startswith(prefix): key=key.removeprefix(prefix); changed=True; break
|
| 66 |
+
normalized.append(key)
|
| 67 |
+
timm=sum(k.startswith(("conv_stem.","blocks.","conv_head.","stages.","stem.")) for k in normalized)
|
| 68 |
+
tv=sum(k.startswith(("features.","avgpool.","classifier.")) for k in normalized)
|
| 69 |
+
if timm>tv:return "timm"
|
| 70 |
+
if tv>timm:return "torchvision"
|
| 71 |
+
raise RuntimeError(f"Cannot infer backend from {path}; pass --backbone-backend.")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def load_encoder_checkpoint(path,encoder,device):
|
| 75 |
+
state=extract_state(torch.load(path.expanduser().resolve(),map_location=device,weights_only=False)); target=encoder.state_dict(); matched={}
|
| 76 |
+
for raw,value in state.items():
|
| 77 |
+
key=raw; changed=True
|
| 78 |
+
while changed:
|
| 79 |
+
changed=False
|
| 80 |
+
for prefix in ("module.","_orig_mod.","model.","encoder.","dermoscopic_encoder.","backbone."):
|
| 81 |
+
if key.startswith(prefix): key=key.removeprefix(prefix); changed=True; break
|
| 82 |
+
if key in target and tuple(target[key].shape)==tuple(value.shape): matched[key]=value
|
| 83 |
+
if not matched: raise RuntimeError(f"No compatible encoder weights in {path}")
|
| 84 |
+
target.update(matched); encoder.load_state_dict(target); print(f"Loaded encoder keys={len(matched)}, skipped={len(state)-len(matched)}")
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def make_optimizer(model,args,encoder_trainable):
|
| 88 |
+
encoder=[]; metadata=[]; head=[]
|
| 89 |
+
for name,param in model.named_parameters():
|
| 90 |
+
if not param.requires_grad: continue
|
| 91 |
+
if name.startswith("encoder."): encoder.append(param)
|
| 92 |
+
elif name.startswith(("metadata_head.","metadata_gate.")): metadata.append(param)
|
| 93 |
+
else: head.append(param)
|
| 94 |
+
groups=[{"params":head,"lr":args.head_lr}]
|
| 95 |
+
if metadata: groups.append({"params":metadata,"lr":args.metadata_lr or args.head_lr})
|
| 96 |
+
if encoder_trainable and encoder: groups.append({"params":encoder,"lr":args.encoder_lr})
|
| 97 |
+
return torch.optim.AdamW(groups,weight_decay=args.weight_decay)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def metric_key(name): return "".join(x if x.isalnum() else "_" for x in name)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def run_epoch(model,loader,criterion,device,optimizer=None,scaler=None,use_amp=False,class_names=None,tail_indices=None):
|
| 104 |
+
training=optimizer is not None; model.train(training); total_loss=total=correct=top3=0; truths=[]; preds=[]
|
| 105 |
+
for batch in tqdm(loader,leave=False):
|
| 106 |
+
image=batch["image"].to(device,non_blocking=True); metadata=batch["metadata"].to(device,non_blocking=True); labels=batch["label"].to(device,non_blocking=True)
|
| 107 |
+
if training: optimizer.zero_grad(set_to_none=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
with torch.set_grad_enabled(training):
|
| 109 |
+
with autocast(device.type,enabled=use_amp): logits=model(image,metadata); loss=criterion(logits,labels)
|
|
|
|
|
|
|
| 110 |
if training:
|
| 111 |
+
assert scaler is not None; scaler.scale(loss).backward(); scaler.unscale_(optimizer); torch.nn.utils.clip_grad_norm_(model.parameters(),1.0); scaler.step(optimizer); scaler.update()
|
| 112 |
+
size=labels.size(0); total_loss+=float(loss.detach())*size; total+=size; predicted=logits.argmax(1); correct+=int((predicted==labels).sum())
|
| 113 |
+
top3+=int(logits.topk(min(3,logits.size(1)),1).indices.eq(labels[:,None]).any(1).sum()); truths.append(labels.cpu().numpy()); preds.append(predicted.cpu().numpy())
|
| 114 |
+
y=np.concatenate(truths); pred=np.concatenate(preds); labels=list(range(len(class_names or [])))
|
| 115 |
+
precision,recall,f1,support=precision_recall_fscore_support(y,pred,labels=labels,zero_division=0); cm=confusion_matrix(y,pred,labels=labels)
|
| 116 |
+
stats={"loss":total_loss/max(total,1),"accuracy":correct/max(total,1),"balanced_accuracy":float(balanced_accuracy_score(y,pred)),
|
| 117 |
+
"f1_macro":float(f1.mean()),"dice_macro":float(f1.mean()),"top3_accuracy":top3/max(total,1)}
|
| 118 |
+
for i,name in enumerate(class_names or []):
|
| 119 |
+
key=metric_key(name); stats.update({f"support_{key}":float(support[i]),f"precision_{key}":float(precision[i]),f"recall_{key}":float(recall[i]),f"f1_{key}":float(f1[i]),f"correct_{key}":float(cm[i,i])})
|
| 120 |
+
row_total=int(cm[i].sum())
|
| 121 |
+
for j,pred_name in enumerate(class_names or []):
|
| 122 |
+
if i!=j and cm[i,j]: stats[f"conf_{key}_to_{metric_key(pred_name)}_count"]=float(cm[i,j]); stats[f"conf_{key}_to_{metric_key(pred_name)}_rate"]=float(cm[i,j]/row_total)
|
| 123 |
+
if tail_indices: stats["tail_recall_macro"]=float(recall[tail_indices].mean())
|
| 124 |
+
return stats
|
| 125 |
|
| 126 |
|
| 127 |
@torch.no_grad()
|
| 128 |
+
def predict(model,loader,device):
|
| 129 |
+
model.eval(); truth=[]; probs=[]
|
| 130 |
+
for batch in tqdm(loader,leave=False):
|
| 131 |
+
logits=model(batch["image"].to(device),batch["metadata"].to(device)); truth.append(batch["label"].numpy()); probs.append(torch.softmax(logits,1).cpu().numpy())
|
| 132 |
+
return np.concatenate(truth),np.concatenate(probs)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def checkpoint_payload(model,optimizer,scheduler,scaler,epoch,phase,best,best_tail,patience,class_names,label_to_idx,spec,args):
|
| 136 |
+
return {"schema_version":CHECKPOINT_SCHEMA_VERSION,"epoch":epoch,"phase":phase,"best_val_f1_macro":best if args.selection_metric=="f1_macro" else None,
|
| 137 |
+
"best_selection_metric":best,"selection_metric_name":args.selection_metric,"best_val_tail_recall_macro":best_tail,"patience_count":patience,
|
| 138 |
+
"model_type":model.__class__.__name__,"model_state":model.state_dict(),"optimizer_state":optimizer.state_dict(),"scheduler_state":scheduler.state_dict(),
|
| 139 |
+
"scaler_state":scaler.state_dict(),"class_names":class_names,"label_to_idx":label_to_idx,"metadata_spec":spec,"args":json_safe(vars(args))}
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def tail_config(train_df,class_names,label_to_idx,args):
|
| 143 |
+
if args.loss!="ldam" or args.tail_num_classes<=0:return [],[]
|
| 144 |
+
counts=train_df.label.value_counts().reindex(class_names,fill_value=0); names=sorted(class_names,key=lambda x:(counts[x],x))[:args.tail_num_classes]
|
| 145 |
+
return names,[label_to_idx[x] for x in names]
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def train_split(base_df,train_df,val_df,class_names,label_to_idx,args,device,backend,output_dir,fold=None):
|
| 149 |
+
output_dir.mkdir(parents=True,exist_ok=True); split_dir=output_dir/"splits"; split_dir.mkdir(exist_ok=True)
|
| 150 |
+
train_df=append_augmented_rows(base_df,train_df,args); train_df["is_augmented"]=synthetic_mask(train_df); train_df["ignore_metadata"]=train_df.get("ignore_metadata",False)
|
| 151 |
+
val_df["is_augmented"]=synthetic_mask(val_df); val_df["ignore_metadata"]=False
|
| 152 |
+
train_df.to_csv(split_dir/"train.csv",index=False); val_df.to_csv(split_dir/"val.csv",index=False)
|
| 153 |
+
full_summary=pd.concat([train_df,val_df],ignore_index=True,sort=False); data_summary=save_data_summary(output_dir,full_summary,train_df,val_df,class_names)
|
| 154 |
+
spec=fit_metadata_spec(train_df); metadata_input_dim=len(metadata_vector(train_df.iloc[0],spec)); train_loader,val_loader=make_loaders(train_df,val_df,label_to_idx,spec,args)
|
| 155 |
+
model=DermoscopicMetadataClassifier(len(class_names),metadata_input_dim,args.metadata_mode,args.backbone,
|
| 156 |
+
args.imagenet_pretrained or (args.encoder_checkpoint is None and args.resume_checkpoint is None),args.branch_dim,args.metadata_dim,
|
| 157 |
+
args.classifier_hidden_dim,args.dropout,backend,args.metadata_gate_hidden_dim).to(device)
|
| 158 |
+
if args.freeze_metadata_head:set_metadata_trainable(model,False)
|
| 159 |
+
resume=None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
if args.resume_checkpoint:
|
| 161 |
+
resume=torch.load(args.resume_checkpoint.expanduser().resolve(),map_location=device,weights_only=False); model.load_state_dict(resume["model_state"])
|
| 162 |
+
elif args.encoder_checkpoint:load_encoder_checkpoint(args.encoder_checkpoint,model.encoder,device)
|
| 163 |
+
config={"args":json_safe(vars(args)),"environment":environment_info(),"class_names":class_names,"label_to_idx":label_to_idx,"metadata_spec":spec,
|
| 164 |
+
"metadata_input_dim":metadata_input_dim,"model_type":model.__class__.__name__,"backbone_backend_resolved":backend,"train_size":len(train_df),"val_size":len(val_df),"fold":fold}
|
| 165 |
+
(output_dir/"run_config.json").write_text(json.dumps(config,indent=2),encoding="utf-8")
|
| 166 |
+
criterion=build_loss(train_df,label_to_idx,args,device); tail_names,tail_indices=tail_config(train_df,class_names,label_to_idx,args)
|
| 167 |
+
history=[]; history_path=output_dir/"history.csv"
|
| 168 |
+
if resume is not None and history_path.exists():history=pd.read_csv(history_path).to_dict("records")
|
| 169 |
+
best=float(resume.get("best_selection_metric",resume.get("best_val_f1_macro",float("-inf")))) if resume else float("-inf")
|
| 170 |
+
best_tail=float(resume.get("best_val_tail_recall_macro",float("-inf"))) if resume else float("-inf")
|
| 171 |
+
resume_epoch=int(resume.get("epoch",0)) if resume else 0; resume_phase=resume.get("phase") if resume else None
|
| 172 |
+
phases=(("freeze",args.freeze_epochs,False,1),("finetune",args.finetune_epochs,True,args.freeze_epochs+1))
|
| 173 |
+
for phase,count,encoder_trainable,start in phases:
|
| 174 |
+
if count<=0:continue
|
| 175 |
+
end=start+count-1
|
| 176 |
+
if resume and ((resume_phase=="finetune" and phase=="freeze") or resume_epoch>=end):continue
|
| 177 |
+
set_encoder_trainable(model,encoder_trainable); optimizer=make_optimizer(model,args,encoder_trainable)
|
| 178 |
+
scheduler=torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer,mode="max",factor=.2,patience=2); scaler=GradScaler("cuda",enabled=args.amp and device.type=="cuda")
|
| 179 |
+
patience=int(resume.get("patience_count",0)) if resume and resume_phase==phase else 0
|
| 180 |
+
if resume and resume_phase==phase:
|
| 181 |
+
try:
|
| 182 |
+
optimizer.load_state_dict(resume["optimizer_state"])
|
| 183 |
+
if "scheduler_state" in resume:scheduler.load_state_dict(resume["scheduler_state"])
|
| 184 |
+
if "scaler_state" in resume:scaler.load_state_dict(resume["scaler_state"])
|
| 185 |
+
except (ValueError,KeyError) as exc:print(f"Resume state fallback to recreated optimizer/scaler: {exc}")
|
| 186 |
+
for epoch in range(max(start,resume_epoch+1),end+1):
|
| 187 |
+
if hasattr(criterion,"set_epoch"):criterion.set_epoch(epoch)
|
| 188 |
+
train_stats=run_epoch(model,train_loader,criterion,device,optimizer,scaler,args.amp and device.type=="cuda",class_names,tail_indices)
|
| 189 |
+
val_stats=run_epoch(model,val_loader,criterion,device,None,None,args.amp and device.type=="cuda",class_names,tail_indices); scheduler.step(val_stats[args.selection_metric])
|
| 190 |
+
history.append({"phase":phase,"epoch":epoch,**{f"train_{k}":v for k,v in train_stats.items()},**{f"val_{k}":v for k,v in val_stats.items()}}); pd.DataFrame(history).to_csv(history_path,index=False)
|
| 191 |
+
improved=val_stats[args.selection_metric]>best
|
| 192 |
+
if improved:best=val_stats[args.selection_metric];patience=0
|
| 193 |
+
else:patience+=1
|
| 194 |
+
tail_improved=bool(tail_indices and val_stats["tail_recall_macro"]>best_tail)
|
| 195 |
+
if tail_improved:best_tail=val_stats["tail_recall_macro"]
|
| 196 |
+
payload=checkpoint_payload(model,optimizer,scheduler,scaler,epoch,phase,best,best_tail,patience,class_names,label_to_idx,spec,args)
|
| 197 |
+
if improved:torch.save(payload,output_dir/"best.pt")
|
| 198 |
+
if tail_improved:payload.update({"tail_class_names":tail_names,"tail_class_indices":tail_indices});torch.save(payload,output_dir/"tail_best.pt")
|
| 199 |
+
torch.save(payload,output_dir/"last.pt")
|
| 200 |
+
print(f"{phase} epoch={epoch:03d} train_loss={train_stats['loss']:.4f} val_loss={val_stats['loss']:.4f} val_acc={val_stats['accuracy']:.4f} val_bal={val_stats['balanced_accuracy']:.4f} val_f1={val_stats['f1_macro']:.4f} val_top3={val_stats['top3_accuracy']:.4f}")
|
| 201 |
+
if tail_indices:print(f"tail={tail_names} val_tail_recall={val_stats['tail_recall_macro']:.4f}")
|
| 202 |
+
if args.patience>0 and patience>=args.patience:print(f"Early stopping {phase} at epoch {epoch}");break
|
| 203 |
+
best_path=output_dir/"best.pt"
|
| 204 |
+
if not best_path.exists():raise RuntimeError("No best checkpoint was produced.")
|
| 205 |
+
best_checkpoint=torch.load(best_path,map_location=device,weights_only=False);model.load_state_dict(best_checkpoint["model_state"])
|
| 206 |
+
y_true,y_prob=predict(model,val_loader,device);metrics,per_class,cm=compute_metrics(y_true,y_prob,class_names)
|
| 207 |
+
metrics={"best_selection_metric":best,"selection_metric_name":args.selection_metric,"best_val_f1_macro":best if args.selection_metric=="f1_macro" else None,
|
| 208 |
+
"best_val_tail_recall_macro":None if best_tail==float("-inf") else best_tail,"fold":fold,**metrics}
|
| 209 |
+
save_evaluation(output_dir,y_true,y_prob,val_df,class_names);(output_dir/"metrics.json").write_text(json.dumps(json_safe(metrics),indent=2),encoding="utf-8")
|
| 210 |
if args.calibrate_bias:
|
| 211 |
+
bias,score=optimize_class_bias(y_true,y_prob,class_names,args.calibration_max_bias,args.calibration_step,args.calibration_passes,args.calibration_metric)
|
| 212 |
+
calibrated=apply_class_bias(y_prob,bias); calibrated_metrics=save_evaluation(output_dir,y_true,calibrated,val_df,class_names,"calibrated")
|
| 213 |
+
(output_dir/"calibration.json").write_text(json.dumps({"metric":args.calibration_metric,"optimized_score":score,"class_names":class_names,"class_bias":bias.tolist(),"metrics":calibrated_metrics},indent=2),encoding="utf-8")
|
| 214 |
+
metrics["calibrated"]=calibrated_metrics;(output_dir/"metrics.json").write_text(json.dumps(json_safe(metrics),indent=2),encoding="utf-8")
|
| 215 |
+
save_diagnostics(output_dir,args,data_summary,metrics,per_class,cm,y_prob,class_names,fold)
|
| 216 |
+
return metrics
|
| 217 |
|
|
|
|
|
|
|
| 218 |
|
| 219 |
+
def run(args):
|
| 220 |
+
if args.freeze_epochs+args.finetune_epochs<=0:raise ValueError("At least one epoch is required.")
|
| 221 |
+
if args.k_folds<1:raise ValueError("--k-folds must be >=1.")
|
| 222 |
+
if args.k_folds>1 and args.resume_checkpoint:raise ValueError("Resume a specific fold directly; root k-fold resume is unsupported.")
|
| 223 |
+
set_seed(args.seed);args.output_dir=args.output_dir.expanduser().resolve();args.output_dir.mkdir(parents=True,exist_ok=True)
|
| 224 |
+
df=load_dermoscopic_dataframe(args.data_dir,args.input_dir);df["is_augmented"]=synthetic_mask(df);df["ignore_metadata"]=False
|
| 225 |
+
class_names=sorted(df.label.unique());label_to_idx={x:i for i,x in enumerate(class_names)};device=torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 226 |
+
if args.backbone_backend=="auto":
|
| 227 |
+
if args.resume_checkpoint:
|
| 228 |
+
saved=torch.load(args.resume_checkpoint,map_location="cpu",weights_only=False).get("args",{});backend=saved.get("backbone_backend","timm");backend="timm" if backend=="auto" else backend
|
| 229 |
+
elif args.encoder_checkpoint:backend=infer_checkpoint_backend(args.encoder_checkpoint,device)
|
| 230 |
+
else:backend="timm"
|
| 231 |
+
else:backend=args.backbone_backend
|
| 232 |
+
args.backbone_backend=backend
|
| 233 |
+
results=[]
|
| 234 |
+
for fold in range(args.k_folds):
|
| 235 |
+
train_df,val_df=create_or_load_split(df,args.split_manifest,args.val_size,args.seed,args.synthetic_train_only,fold,args.k_folds)
|
| 236 |
+
if args.synthetic_train_only and synthetic_mask(val_df).any():raise RuntimeError("Synthetic leakage detected in validation split.")
|
| 237 |
+
output=args.output_dir if args.k_folds==1 else args.output_dir/f"fold_{fold:02d}"
|
| 238 |
+
results.append(train_split(df,train_df,val_df,class_names,label_to_idx,args,device,backend,output,None if args.k_folds==1 else fold))
|
| 239 |
+
if args.k_folds>1:save_kfold_summary(results,args.output_dir)
|
| 240 |
+
return results[0] if args.k_folds==1 else results
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def main():run(parse_args())
|
| 244 |
+
if __name__=="__main__":main()
|