Upload 9 files
Browse files- milk10k_effb2_dermoscopic_metadata/__init__.py +3 -0
- milk10k_effb2_dermoscopic_metadata/ablation.py +78 -0
- milk10k_effb2_dermoscopic_metadata/core.py +120 -0
- milk10k_effb2_dermoscopic_metadata/data.py +255 -0
- milk10k_effb2_dermoscopic_metadata/inference.py +156 -0
- milk10k_effb2_dermoscopic_metadata/losses.py +111 -0
- milk10k_effb2_dermoscopic_metadata/model.py +108 -0
- milk10k_effb2_dermoscopic_metadata/reporting.py +92 -0
- milk10k_effb2_dermoscopic_metadata/training.py +244 -0
milk10k_effb2_dermoscopic_metadata/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""MILK10k single-dermoscopic-image classifier with optional metadata."""
|
| 2 |
+
|
| 3 |
+
__version__ = "0.1.0"
|
milk10k_effb2_dermoscopic_metadata/ablation.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run and summarize matched no-metadata vs metadata training."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import pandas as pd
|
| 10 |
+
|
| 11 |
+
from .training import parse_args as parse_training_args, run as run_training
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def parse_args(argv=None):
|
| 15 |
+
parser = argparse.ArgumentParser(description="Run matched dermoscopic metadata ablation.")
|
| 16 |
+
parser.add_argument("--data-dir", type=Path, required=True)
|
| 17 |
+
parser.add_argument("--input-dir", type=Path, default=None)
|
| 18 |
+
parser.add_argument("--output-dir", type=Path, required=True)
|
| 19 |
+
parser.add_argument("--split-manifest", type=Path, required=True)
|
| 20 |
+
parser.add_argument("training_args", nargs=argparse.REMAINDER, help="Extra training arguments after --, e.g. -- --amp --loss ce_dice")
|
| 21 |
+
return parser.parse_args(argv)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def summarize(output_dir: Path):
|
| 25 |
+
runs = {"none": output_dir / "no_metadata", "concat": output_dir / "with_metadata"}
|
| 26 |
+
rows = []
|
| 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"],
|
| 51 |
+
"recall_delta": with_pc.loc[name, "recall_sensitivity"] - none_pc.loc[name, "recall_sensitivity"]})
|
| 52 |
+
pd.DataFrame(rows).to_csv(output_dir / "ablation_summary.csv", index=False)
|
| 53 |
+
pd.DataFrame(class_rows).to_csv(output_dir / "ablation_per_class.csv", index=False)
|
| 54 |
+
(output_dir / "ablation_summary.json").write_text(json.dumps(payload, indent=2), encoding="utf-8")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def run(args):
|
| 58 |
+
output_dir = args.output_dir.expanduser().resolve(); output_dir.mkdir(parents=True, exist_ok=True)
|
| 59 |
+
extras = args.training_args[1:] if args.training_args[:1] == ["--"] else args.training_args
|
| 60 |
+
forbidden = {"--data-dir", "--input-dir", "--output-dir", "--split-manifest", "--metadata-mode", "--calibrate-bias"}
|
| 61 |
+
if forbidden.intersection(extras):
|
| 62 |
+
raise ValueError(f"Do not override ablation-controlled arguments: {sorted(forbidden.intersection(extras))}")
|
| 63 |
+
for mode, name in (("none", "no_metadata"), ("concat", "with_metadata")):
|
| 64 |
+
cli = ["--data-dir", str(args.data_dir), "--output-dir", str(output_dir / name), "--split-manifest", str(args.split_manifest), "--metadata-mode", mode]
|
| 65 |
+
if args.input_dir is not None:
|
| 66 |
+
cli.extend(["--input-dir", str(args.input_dir)])
|
| 67 |
+
cli.extend(extras)
|
| 68 |
+
run_training(parse_training_args(cli))
|
| 69 |
+
summarize(output_dir)
|
| 70 |
+
print(f"Ablation summary saved under {output_dir}")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def main():
|
| 74 |
+
run(parse_args())
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
if __name__ == "__main__":
|
| 78 |
+
main()
|
milk10k_effb2_dermoscopic_metadata/core.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Losses, prediction metrics, calibration, and serialization helpers."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import random
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import pandas as pd
|
| 12 |
+
import torch
|
| 13 |
+
from sklearn.metrics import (
|
| 14 |
+
accuracy_score, balanced_accuracy_score, classification_report, confusion_matrix,
|
| 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:
|
| 21 |
+
random.seed(seed)
|
| 22 |
+
np.random.seed(seed)
|
| 23 |
+
torch.manual_seed(seed)
|
| 24 |
+
if torch.cuda.is_available():
|
| 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"))
|
| 31 |
+
except ValueError:
|
| 32 |
+
return None
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def compute_metrics(y_true: np.ndarray, y_prob: np.ndarray, class_names: list[str]):
|
| 36 |
+
y_pred = y_prob.argmax(axis=1)
|
| 37 |
+
labels = list(range(len(class_names)))
|
| 38 |
+
cm = confusion_matrix(y_true, y_pred, labels=labels)
|
| 39 |
+
precision, recall, f1, support = precision_recall_fscore_support(y_true, y_pred, labels=labels, zero_division=0)
|
| 40 |
+
total = int(cm.sum())
|
| 41 |
+
rows = []
|
| 42 |
+
for idx, name in enumerate(class_names):
|
| 43 |
+
tp = int(cm[idx, idx]); fn = int(cm[idx].sum() - tp); fp = int(cm[:, idx].sum() - tp); tn = total - tp - fn - fp
|
| 44 |
+
binary = (y_true == idx).astype(np.int64)
|
| 45 |
+
try:
|
| 46 |
+
auc = float(roc_auc_score(binary, y_prob[:, idx]))
|
| 47 |
+
except ValueError:
|
| 48 |
+
auc = None
|
| 49 |
+
rows.append({
|
| 50 |
+
"class": name, "support": int(support[idx]), "precision": float(precision[idx]),
|
| 51 |
+
"recall_sensitivity": float(recall[idx]), "specificity": tn / (tn + fp) if tn + fp else 0.0,
|
| 52 |
+
"f1": float(f1[idx]), "auc_ovr": auc,
|
| 53 |
+
})
|
| 54 |
+
macro = precision_recall_fscore_support(y_true, y_pred, labels=labels, average="macro", zero_division=0)
|
| 55 |
+
weighted = precision_recall_fscore_support(y_true, y_pred, labels=labels, average="weighted", zero_division=0)
|
| 56 |
+
y_true_bin = label_binarize(y_true, classes=labels)
|
| 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]),
|
| 64 |
+
"precision_weighted": float(weighted[0]), "recall_weighted": float(weighted[1]), "f1_weighted": float(weighted[2]),
|
| 65 |
+
"roc_auc_macro_ovr": safe_auc(y_true_bin, y_prob, "macro"),
|
| 66 |
+
"roc_auc_weighted_ovr": safe_auc(y_true_bin, y_prob, "weighted"),
|
| 67 |
+
"specificity_macro": float(np.mean([row["specificity"] for row in rows])),
|
| 68 |
+
"per_class": rows,
|
| 69 |
+
"classification_report": classification_report(y_true, y_pred, labels=labels, target_names=class_names, zero_division=0, output_dict=True),
|
| 70 |
+
}
|
| 71 |
+
return metrics, pd.DataFrame(rows), cm
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def apply_class_bias(y_prob: np.ndarray, bias: np.ndarray) -> np.ndarray:
|
| 75 |
+
logits = np.log(np.clip(y_prob, 1e-12, 1.0)) + bias[None, :]
|
| 76 |
+
logits -= logits.max(axis=1, keepdims=True)
|
| 77 |
+
exp = np.exp(logits)
|
| 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
|
| 87 |
+
for index in range(len(class_names)):
|
| 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:
|
| 95 |
+
bias[index], best, improved = local_value, local_best, True
|
| 96 |
+
if not improved:
|
| 97 |
+
break
|
| 98 |
+
return bias, float(best)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def json_safe(value: Any):
|
| 102 |
+
if isinstance(value, Path): return str(value)
|
| 103 |
+
if isinstance(value, np.generic): return value.item()
|
| 104 |
+
if isinstance(value, np.ndarray): return value.tolist()
|
| 105 |
+
if isinstance(value, dict): return {str(k): json_safe(v) for k, v in value.items()}
|
| 106 |
+
if isinstance(value, (list, tuple)): return [json_safe(v) for v in value]
|
| 107 |
+
return value
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def save_evaluation(output_dir: Path, y_true, y_prob, df, class_names, prefix=""):
|
| 111 |
+
metrics, per_class, cm = compute_metrics(y_true, y_prob, class_names)
|
| 112 |
+
stem = f"{prefix}_" if prefix else ""
|
| 113 |
+
(output_dir / f"{stem}metrics.json").write_text(json.dumps(json_safe(metrics), indent=2), encoding="utf-8")
|
| 114 |
+
per_class.to_csv(output_dir / f"{stem}per_class_metrics.csv", index=False)
|
| 115 |
+
pd.DataFrame(cm, index=class_names, columns=class_names).to_csv(output_dir / f"{stem}confusion_matrix.csv")
|
| 116 |
+
predictions = pd.DataFrame(y_prob, columns=class_names)
|
| 117 |
+
predictions.insert(0, "true_label", [class_names[i] for i in y_true])
|
| 118 |
+
predictions.insert(0, "lesion_id", df["lesion_id"].tolist())
|
| 119 |
+
predictions.to_csv(output_dir / f"{stem}val_predictions.csv", index=False)
|
| 120 |
+
return metrics
|
milk10k_effb2_dermoscopic_metadata/data.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dermoscopic-only dataframe, metadata, split, transform, and loader helpers."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 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 |
+
|
| 17 |
+
ImageFile.LOAD_TRUNCATED_IMAGES = True
|
| 18 |
+
|
| 19 |
+
LABEL_COLUMNS = ["AKIEC", "BCC", "BEN_OTH", "BKL", "DF", "INF", "MAL_OTH", "MEL", "NV", "SCCKA", "VASC"]
|
| 20 |
+
BASE_METADATA_COLUMNS = ("age_approx", "sex", "skin_tone_class", "site")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def normalize_image_type(value: str) -> str:
|
| 24 |
+
return str(value).strip().lower().replace(" ", "_").replace(":", "").replace("-", "_")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def resolve_training_paths(data_dir: Path, input_dir: Path | None = None) -> tuple[Path, Path, Path]:
|
| 28 |
+
data_dir = data_dir.expanduser().resolve()
|
| 29 |
+
if input_dir is None:
|
| 30 |
+
local_input = data_dir / "MILK10k_Training_Input"
|
| 31 |
+
sibling_input = data_dir.parent / "MILK10k_Training_Input"
|
| 32 |
+
input_dir = local_input if local_input.exists() else sibling_input
|
| 33 |
+
else:
|
| 34 |
+
input_dir = input_dir.expanduser().resolve()
|
| 35 |
+
metadata_csv = data_dir / "MILK10k_Training_Metadata.csv"
|
| 36 |
+
groundtruth_csv = data_dir / "MILK10k_Training_GroundTruth.csv"
|
| 37 |
+
missing = [path for path in (input_dir, metadata_csv, groundtruth_csv) if not path.exists()]
|
| 38 |
+
if missing:
|
| 39 |
+
raise FileNotFoundError("Missing MILK10k training input: " + ", ".join(map(str, missing)))
|
| 40 |
+
return input_dir, metadata_csv, groundtruth_csv
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def resolve_monet_columns(meta: pd.DataFrame) -> list[str]:
|
| 44 |
+
return sorted(column for column in meta.columns if column.startswith("MONET_"))
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def load_dermoscopic_dataframe(data_dir: Path, input_dir: Path | None = None) -> pd.DataFrame:
|
| 48 |
+
input_dir, metadata_csv, groundtruth_csv = resolve_training_paths(data_dir, input_dir)
|
| 49 |
+
meta = pd.read_csv(metadata_csv)
|
| 50 |
+
gt = pd.read_csv(groundtruth_csv)
|
| 51 |
+
required = {"lesion_id", "isic_id", "image_type", *BASE_METADATA_COLUMNS}
|
| 52 |
+
missing = required.difference(meta.columns)
|
| 53 |
+
if missing:
|
| 54 |
+
raise ValueError(f"Metadata CSV is missing columns: {sorted(missing)}")
|
| 55 |
+
label_columns = [column for column in LABEL_COLUMNS if column in gt.columns]
|
| 56 |
+
if not label_columns:
|
| 57 |
+
raise ValueError("Ground-truth CSV contains no recognized class columns.")
|
| 58 |
+
|
| 59 |
+
meta["image_type_norm"] = meta["image_type"].map(normalize_image_type)
|
| 60 |
+
dermoscopic = meta[meta["image_type_norm"] == "dermoscopic"].copy()
|
| 61 |
+
duplicate_counts = dermoscopic.groupby("lesion_id").size()
|
| 62 |
+
duplicates = duplicate_counts[duplicate_counts > 1]
|
| 63 |
+
if not duplicates.empty:
|
| 64 |
+
sample = duplicates.head(5).to_dict()
|
| 65 |
+
raise ValueError(f"Expected one dermoscopic image per lesion; duplicates found: {sample}")
|
| 66 |
+
dermoscopic["image_path"] = dermoscopic.apply(
|
| 67 |
+
lambda row: input_dir / str(row["lesion_id"]) / f"{row['isic_id']}.jpg", axis=1
|
| 68 |
+
)
|
| 69 |
+
dermoscopic = dermoscopic[dermoscopic["image_path"].map(Path.exists)].copy()
|
| 70 |
+
dermoscopic["image_path"] = dermoscopic["image_path"].map(str)
|
| 71 |
+
|
| 72 |
+
gt = gt.copy()
|
| 73 |
+
gt["label"] = gt[label_columns].idxmax(axis=1)
|
| 74 |
+
df = gt[["lesion_id", "label"]].merge(dermoscopic, on="lesion_id", how="inner", validate="one_to_one")
|
| 75 |
+
if df.empty:
|
| 76 |
+
raise ValueError(f"No labeled dermoscopic images found under {input_dir}")
|
| 77 |
+
return df.reset_index(drop=True)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def fit_metadata_spec(train_df: pd.DataFrame) -> dict[str, Any]:
|
| 81 |
+
def categories(column: str) -> list[str]:
|
| 82 |
+
values = train_df[column].fillna("unknown").astype(str).str.strip().replace("", "unknown")
|
| 83 |
+
return sorted(set(values.tolist()) | {"unknown"})
|
| 84 |
+
|
| 85 |
+
return {
|
| 86 |
+
"sex_values": categories("sex"),
|
| 87 |
+
"site_values": categories("site"),
|
| 88 |
+
"monet_columns": resolve_monet_columns(train_df),
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def metadata_vector(row: pd.Series, spec: dict[str, Any]) -> np.ndarray:
|
| 93 |
+
age = pd.to_numeric(row.get("age_approx"), errors="coerce")
|
| 94 |
+
skin = pd.to_numeric(row.get("skin_tone_class"), errors="coerce")
|
| 95 |
+
sex = str(row.get("sex", "unknown")).strip() if pd.notna(row.get("sex")) else "unknown"
|
| 96 |
+
site = str(row.get("site", "unknown")).strip() if pd.notna(row.get("site")) else "unknown"
|
| 97 |
+
sex = sex or "unknown"
|
| 98 |
+
site = site or "unknown"
|
| 99 |
+
values = [0.0 if pd.isna(age) else float(age) / 100.0, 0.0 if pd.isna(skin) else float(skin) / 6.0]
|
| 100 |
+
values.extend(float(sex == item) for item in spec["sex_values"])
|
| 101 |
+
values.extend(float(site == item) for item in spec["site_values"])
|
| 102 |
+
for column in spec.get("monet_columns", []):
|
| 103 |
+
value = pd.to_numeric(row.get(column), errors="coerce")
|
| 104 |
+
values.append(0.0 if pd.isna(value) else float(value))
|
| 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
|
| 140 |
+
missing = all_ids - (train_ids | val_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 |
+
),
|
| 172 |
+
encoding="utf-8",
|
| 173 |
+
)
|
| 174 |
+
train_df = df[df["lesion_id"].astype(str).isin(train_ids)].copy()
|
| 175 |
+
val_df = df[df["lesion_id"].astype(str).isin(val_ids)].copy()
|
| 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(
|
| 198 |
+
[
|
| 199 |
+
transforms.RandomResizedCrop(image_size, scale=(0.75, 1.0)),
|
| 200 |
+
transforms.RandomHorizontalFlip(),
|
| 201 |
+
transforms.RandomVerticalFlip(),
|
| 202 |
+
transforms.RandomRotation(20),
|
| 203 |
+
transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2),
|
| 204 |
+
transforms.ToTensor(),
|
| 205 |
+
normalize,
|
| 206 |
+
]
|
| 207 |
+
)
|
| 208 |
+
eval_transform = transforms.Compose(
|
| 209 |
+
[transforms.Resize(round(image_size * 1.12)), transforms.CenterCrop(image_size), transforms.ToTensor(), normalize]
|
| 210 |
+
)
|
| 211 |
+
return train_transform, eval_transform
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
class DermoscopicMetadataDataset(Dataset):
|
| 215 |
+
def __init__(self, df: pd.DataFrame, label_to_idx: dict[str, int] | None, metadata_spec: dict[str, Any], transform=None):
|
| 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:
|
| 224 |
+
return len(self.df)
|
| 225 |
+
|
| 226 |
+
def __getitem__(self, index: int) -> dict[str, torch.Tensor]:
|
| 227 |
+
row = self.df.iloc[index]
|
| 228 |
+
with Image.open(row["image_path"]) as source:
|
| 229 |
+
image = source.convert("RGB")
|
| 230 |
+
if self.transform:
|
| 231 |
+
image = self.transform(image)
|
| 232 |
+
item = {"image": image, "metadata": torch.from_numpy(self.metadata[index])}
|
| 233 |
+
if self.labels is not None:
|
| 234 |
+
item["label"] = torch.tensor(self.labels[index], dtype=torch.long)
|
| 235 |
+
return item
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def make_loaders(train_df, val_df, label_to_idx, metadata_spec, args):
|
| 239 |
+
train_transform, eval_transform = make_transforms(args.image_size)
|
| 240 |
+
train_ds = DermoscopicMetadataDataset(train_df, label_to_idx, metadata_spec, train_transform)
|
| 241 |
+
val_ds = DermoscopicMetadataDataset(val_df, label_to_idx, metadata_spec, eval_transform)
|
| 242 |
+
sampler = None
|
| 243 |
+
if args.weighted_sampler:
|
| 244 |
+
labels = np.asarray(train_ds.labels)
|
| 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())
|
| 252 |
+
return (
|
| 253 |
+
DataLoader(train_ds, shuffle=sampler is None, sampler=sampler, **common),
|
| 254 |
+
DataLoader(val_ds, shuffle=False, **common),
|
| 255 |
+
)
|
milk10k_effb2_dermoscopic_metadata/inference.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Inference for dermoscopic-only metadata checkpoints."""
|
| 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 torch.utils.data import DataLoader
|
| 13 |
+
from tqdm.auto import tqdm
|
| 14 |
+
|
| 15 |
+
from .core import apply_class_bias, compute_metrics, json_safe
|
| 16 |
+
from .data import BASE_METADATA_COLUMNS, DermoscopicMetadataDataset, LABEL_COLUMNS, make_transforms, normalize_image_type, resolve_monet_columns
|
| 17 |
+
from .model import DermoscopicMetadataClassifier
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
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("--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 |
+
|
| 39 |
+
def checkpoint_paths(args):
|
| 40 |
+
paths = [path.expanduser().resolve() for path in args.checkpoint]
|
| 41 |
+
if args.checkpoint_dir:
|
| 42 |
+
directory = args.checkpoint_dir.expanduser().resolve()
|
| 43 |
+
folds = sorted(directory.glob("fold_*/best.pt"))
|
| 44 |
+
paths.extend(folds or ([directory / "best.pt"] if (directory / "best.pt").exists() else []))
|
| 45 |
+
if not paths:
|
| 46 |
+
raise ValueError("Pass --checkpoint or --checkpoint-dir containing best.pt.")
|
| 47 |
+
missing = [path for path in paths if not path.exists()]
|
| 48 |
+
if missing:
|
| 49 |
+
raise FileNotFoundError(f"Missing checkpoints: {missing}")
|
| 50 |
+
return paths
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def load_dataframe(input_dir: Path, metadata_csv: Path, groundtruth_csv: Path | None):
|
| 54 |
+
input_dir = input_dir.expanduser().resolve()
|
| 55 |
+
meta = pd.read_csv(metadata_csv.expanduser().resolve())
|
| 56 |
+
required = {"lesion_id", "isic_id", "image_type", *BASE_METADATA_COLUMNS}
|
| 57 |
+
missing = required - set(meta.columns)
|
| 58 |
+
if missing:
|
| 59 |
+
raise ValueError(f"Metadata CSV is missing columns: {sorted(missing)}")
|
| 60 |
+
meta["image_type_norm"] = meta["image_type"].map(normalize_image_type)
|
| 61 |
+
df = meta[meta["image_type_norm"] == "dermoscopic"].copy()
|
| 62 |
+
duplicates = df.groupby("lesion_id").size()
|
| 63 |
+
if (duplicates > 1).any():
|
| 64 |
+
raise ValueError("Expected exactly one dermoscopic row per lesion.")
|
| 65 |
+
df["image_path"] = df.apply(lambda row: input_dir / str(row["lesion_id"]) / f"{row['isic_id']}.jpg", axis=1)
|
| 66 |
+
df = df[df["image_path"].map(Path.exists)].copy(); df["image_path"] = df["image_path"].map(str)
|
| 67 |
+
if groundtruth_csv and groundtruth_csv.exists():
|
| 68 |
+
gt = pd.read_csv(groundtruth_csv)
|
| 69 |
+
columns = [name for name in LABEL_COLUMNS if name in gt.columns]
|
| 70 |
+
gt["label"] = gt[columns].idxmax(axis=1)
|
| 71 |
+
df = df.merge(gt[["lesion_id", "label"]], on="lesion_id", how="left", validate="one_to_one")
|
| 72 |
+
if df.empty:
|
| 73 |
+
raise ValueError("No existing dermoscopic image files were found.")
|
| 74 |
+
return df.reset_index(drop=True)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def build_model(checkpoint, device):
|
| 78 |
+
saved = checkpoint["args"]
|
| 79 |
+
spec = checkpoint["metadata_spec"]
|
| 80 |
+
input_dim = 2 + len(spec["sex_values"]) + len(spec["site_values"]) + len(spec.get("monet_columns", []))
|
| 81 |
+
model = DermoscopicMetadataClassifier(
|
| 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
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@torch.no_grad()
|
| 92 |
+
def predict(model, loader, device, tta):
|
| 93 |
+
output = []
|
| 94 |
+
for batch in tqdm(loader, leave=False):
|
| 95 |
+
image = batch["image"].to(device); metadata = batch["metadata"].to(device)
|
| 96 |
+
views = [image]
|
| 97 |
+
if tta:
|
| 98 |
+
views.extend([torch.flip(image, (-1,)), torch.flip(image, (-2,)), torch.flip(image, (-2, -1))])
|
| 99 |
+
probs = sum(torch.softmax(model(view, metadata), 1) for view in views) / len(views)
|
| 100 |
+
output.append(probs.cpu().numpy())
|
| 101 |
+
return np.concatenate(output)
|
| 102 |
+
|
| 103 |
+
|
| 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:
|
| 131 |
+
raise ValueError(f"Calibration class mismatch: {calibration_path}")
|
| 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)}
|
| 143 |
+
y_true = df["label"].map(mapping).to_numpy()
|
| 144 |
+
metrics, per_class, cm = compute_metrics(y_true, y_prob, class_names)
|
| 145 |
+
args.output.with_suffix(".metrics.json").write_text(json.dumps(json_safe(metrics), indent=2), encoding="utf-8")
|
| 146 |
+
per_class.to_csv(args.output.with_suffix(".per_class_metrics.csv"), index=False)
|
| 147 |
+
pd.DataFrame(cm, index=class_names, columns=class_names).to_csv(args.output.with_suffix(".confusion_matrix.csv"))
|
| 148 |
+
print(f"Saved {len(df)} dermoscopic predictions to {args.output}")
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def main():
|
| 152 |
+
run(parse_args())
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
if __name__ == "__main__":
|
| 156 |
+
main()
|
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
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Single-image classifier and optional metadata fusion."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import timm
|
| 6 |
+
import torch
|
| 7 |
+
from torch import nn
|
| 8 |
+
|
| 9 |
+
METADATA_MODES = ("none", "concat", "gated_concat", "gated_only")
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def build_feature_encoder(backbone: str, backend: str, pretrained: bool):
|
| 13 |
+
if backend == "timm":
|
| 14 |
+
encoder = timm.create_model(backbone, pretrained=pretrained, num_classes=0, global_pool="avg")
|
| 15 |
+
return encoder, int(encoder.num_features)
|
| 16 |
+
if backend != "torchvision":
|
| 17 |
+
raise ValueError(f"Unsupported backbone backend: {backend}")
|
| 18 |
+
from torchvision import models
|
| 19 |
+
builders = {
|
| 20 |
+
"efficientnet_b1": (models.efficientnet_b1, models.EfficientNet_B1_Weights),
|
| 21 |
+
"efficientnet_b2": (models.efficientnet_b2, models.EfficientNet_B2_Weights),
|
| 22 |
+
"resnet50": (models.resnet50, models.ResNet50_Weights),
|
| 23 |
+
"convnext_base": (models.convnext_base, models.ConvNeXt_Base_Weights),
|
| 24 |
+
}
|
| 25 |
+
if backbone not in builders:
|
| 26 |
+
raise ValueError(f"torchvision backend does not support backbone={backbone!r}")
|
| 27 |
+
builder, weights_enum = builders[backbone]
|
| 28 |
+
encoder = builder(weights=weights_enum.DEFAULT if pretrained else None)
|
| 29 |
+
if backbone.startswith("efficientnet") or backbone.startswith("convnext"):
|
| 30 |
+
feature_dim = int(encoder.classifier[-1].in_features)
|
| 31 |
+
encoder.classifier = nn.Identity()
|
| 32 |
+
else:
|
| 33 |
+
feature_dim = int(encoder.fc.in_features)
|
| 34 |
+
encoder.fc = nn.Identity()
|
| 35 |
+
return encoder, feature_dim
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class MetadataHead(nn.Module):
|
| 39 |
+
def __init__(self, input_dim: int, output_dim: int, dropout: float):
|
| 40 |
+
super().__init__()
|
| 41 |
+
self.net = nn.Sequential(
|
| 42 |
+
nn.LayerNorm(input_dim), nn.Linear(input_dim, max(32, output_dim * 2)), nn.GELU(),
|
| 43 |
+
nn.Dropout(dropout), nn.Linear(max(32, output_dim * 2), output_dim), nn.GELU(), nn.LayerNorm(output_dim)
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
def forward(self, value):
|
| 47 |
+
return self.net(value)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class DermoscopicMetadataClassifier(nn.Module):
|
| 51 |
+
def __init__(
|
| 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:
|
| 59 |
+
raise ValueError(f"Unsupported metadata mode: {metadata_mode}")
|
| 60 |
+
self.metadata_mode = metadata_mode
|
| 61 |
+
self.backbone_name = backbone
|
| 62 |
+
self.backbone_backend = backbone_backend
|
| 63 |
+
self.encoder, feature_dim = build_feature_encoder(backbone, backbone_backend, imagenet_pretrained)
|
| 64 |
+
self.image_head = nn.Sequential(nn.LayerNorm(feature_dim), nn.Dropout(dropout), nn.Linear(feature_dim, branch_dim), nn.GELU(), nn.LayerNorm(branch_dim))
|
| 65 |
+
if metadata_mode == "none":
|
| 66 |
+
self.metadata_head = None
|
| 67 |
+
self.metadata_gate = None
|
| 68 |
+
classifier_input = branch_dim
|
| 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)
|
| 79 |
+
else:
|
| 80 |
+
self.metadata_gate = None
|
| 81 |
+
classifier_input = branch_dim if metadata_mode == "gated_only" else branch_dim + metadata_dim
|
| 82 |
+
self.classifier = nn.Sequential(
|
| 83 |
+
nn.LayerNorm(classifier_input), nn.Dropout(dropout), nn.Linear(classifier_input, classifier_hidden_dim),
|
| 84 |
+
nn.GELU(), nn.Dropout(dropout), nn.Linear(classifier_hidden_dim, num_classes)
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
def forward(self, image: torch.Tensor, metadata: torch.Tensor | None = None) -> torch.Tensor:
|
| 88 |
+
features = self.image_head(self.encoder(image))
|
| 89 |
+
if self.metadata_mode == "none":
|
| 90 |
+
fused = features
|
| 91 |
+
else:
|
| 92 |
+
if metadata is None:
|
| 93 |
+
raise ValueError(f"metadata is required for metadata_mode={self.metadata_mode}")
|
| 94 |
+
if self.metadata_gate is not None:
|
| 95 |
+
features = features * self.metadata_gate(metadata)
|
| 96 |
+
fused = features if self.metadata_mode == "gated_only" else torch.cat([features, self.metadata_head(metadata)], dim=1)
|
| 97 |
+
return self.classifier(fused)
|
| 98 |
+
|
| 99 |
+
|
| 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
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|