Upload 11 files
Browse files- README.md +58 -0
- milk10k_effb2_dermoscopic_metadata/__init__.py +3 -0
- milk10k_effb2_dermoscopic_metadata/ablation.py +69 -0
- milk10k_effb2_dermoscopic_metadata/core.py +153 -0
- milk10k_effb2_dermoscopic_metadata/data.py +203 -0
- milk10k_effb2_dermoscopic_metadata/inference.py +140 -0
- milk10k_effb2_dermoscopic_metadata/model.py +100 -0
- milk10k_effb2_dermoscopic_metadata/training.py +256 -0
- predict_milk10k_effb2_dermoscopic_metadata.py +5 -0
- run_metadata_ablation.py +5 -0
- train_milk10k_effb2_dermoscopic_metadata.py +5 -0
README.md
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MILK10k EfficientNet-B2 dermoscopic metadata
|
| 2 |
+
|
| 3 |
+
Standalone single-image pipeline. It reads only rows whose `image_type` is
|
| 4 |
+
`dermoscopic`; clinical images and clinical metadata are never loaded.
|
| 5 |
+
`--data-dir` contains the metadata and ground-truth CSV files. Images may be
|
| 6 |
+
under that directory or its parent; otherwise pass `--input-dir` explicitly.
|
| 7 |
+
|
| 8 |
+
## Matched metadata ablation
|
| 9 |
+
|
| 10 |
+
Run from this directory. The split manifest is created by the first run and
|
| 11 |
+
reused verbatim by the second run.
|
| 12 |
+
|
| 13 |
+
```bash
|
| 14 |
+
python run_metadata_ablation.py \
|
| 15 |
+
--data-dir ../data_related \
|
| 16 |
+
--output-dir ../results_dermoscopic_metadata_ablation \
|
| 17 |
+
--split-manifest ../results_dermoscopic_metadata_ablation/split.json \
|
| 18 |
+
-- --amp --loss ce_dice --class-weight --freeze-epochs 5 --finetune-epochs 20
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
The comparison is written to `ablation_summary.csv`,
|
| 22 |
+
`ablation_summary.json`, and `ablation_per_class.csv`. Calibration is
|
| 23 |
+
intentionally disabled by the ablation runner so raw validation results are
|
| 24 |
+
comparable.
|
| 25 |
+
|
| 26 |
+
## One training run
|
| 27 |
+
|
| 28 |
+
```bash
|
| 29 |
+
python train_milk10k_effb2_dermoscopic_metadata.py \
|
| 30 |
+
--data-dir ../data_related \
|
| 31 |
+
--output-dir ../dermoscopic_with_metadata \
|
| 32 |
+
--split-manifest ../results_dermoscopic_metadata_ablation/split.json \
|
| 33 |
+
--metadata-mode concat --amp --loss ce_dice
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
`--metadata-mode` accepts `none`, `concat`, `gated_concat`, and `gated_only`.
|
| 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
|
| 43 |
+
python predict_milk10k_effb2_dermoscopic_metadata.py \
|
| 44 |
+
--checkpoint ../dermoscopic_with_metadata/best.pt \
|
| 45 |
+
--input-dir ../MILK10k_Test_Input \
|
| 46 |
+
--metadata-csv /path/to/MILK10k_Test_Metadata.csv \
|
| 47 |
+
--output ../test_dermoscopic_predictions.csv --tta-flips
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
If a labeled set is supplied with `--groundtruth-csv`, inference also writes
|
| 51 |
+
overall, per-class, and confusion-matrix metrics. A sibling `calibration.json`
|
| 52 |
+
is loaded automatically unless `--no-auto-calibration` is passed.
|
| 53 |
+
|
| 54 |
+
## Outputs
|
| 55 |
+
|
| 56 |
+
Training writes `best.pt`, `last.pt`, `history.csv`, `metrics.json`,
|
| 57 |
+
`per_class_metrics.csv`, `confusion_matrix.csv`, `val_predictions.csv`,
|
| 58 |
+
`train_split.csv`, `val_split.csv`, and `run_config.json`.
|
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,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
metrics = json.loads((directory / "metrics.json").read_text(encoding="utf-8"))
|
| 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 |
+
none_pc = pd.read_csv(runs["none"] / "per_class_metrics.csv").set_index("class")
|
| 38 |
+
with_pc = pd.read_csv(runs["concat"] / "per_class_metrics.csv").set_index("class")
|
| 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"],
|
| 42 |
+
"recall_delta": with_pc.loc[name, "recall_sensitivity"] - none_pc.loc[name, "recall_sensitivity"]})
|
| 43 |
+
pd.DataFrame(rows).to_csv(output_dir / "ablation_summary.csv", index=False)
|
| 44 |
+
pd.DataFrame(class_rows).to_csv(output_dir / "ablation_per_class.csv", index=False)
|
| 45 |
+
(output_dir / "ablation_summary.json").write_text(json.dumps(payload, indent=2), encoding="utf-8")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def run(args):
|
| 49 |
+
output_dir = args.output_dir.expanduser().resolve(); output_dir.mkdir(parents=True, exist_ok=True)
|
| 50 |
+
extras = args.training_args[1:] if args.training_args[:1] == ["--"] else args.training_args
|
| 51 |
+
forbidden = {"--data-dir", "--input-dir", "--output-dir", "--split-manifest", "--metadata-mode", "--calibrate-bias"}
|
| 52 |
+
if forbidden.intersection(extras):
|
| 53 |
+
raise ValueError(f"Do not override ablation-controlled arguments: {sorted(forbidden.intersection(extras))}")
|
| 54 |
+
for mode, name in (("none", "no_metadata"), ("concat", "with_metadata")):
|
| 55 |
+
cli = ["--data-dir", str(args.data_dir), "--output-dir", str(output_dir / name), "--split-manifest", str(args.split_manifest), "--metadata-mode", mode]
|
| 56 |
+
if args.input_dir is not None:
|
| 57 |
+
cli.extend(["--input-dir", str(args.input_dir)])
|
| 58 |
+
cli.extend(extras)
|
| 59 |
+
run_training(parse_training_args(cli))
|
| 60 |
+
summarize(output_dir)
|
| 61 |
+
print(f"Ablation summary saved under {output_dir}")
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def main():
|
| 65 |
+
run(parse_args())
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
if __name__ == "__main__":
|
| 69 |
+
main()
|
milk10k_effb2_dermoscopic_metadata/core.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from torch import nn
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def set_seed(seed: int) -> None:
|
| 22 |
+
random.seed(seed)
|
| 23 |
+
np.random.seed(seed)
|
| 24 |
+
torch.manual_seed(seed)
|
| 25 |
+
if torch.cuda.is_available():
|
| 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"))
|
| 65 |
+
except ValueError:
|
| 66 |
+
return None
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def compute_metrics(y_true: np.ndarray, y_prob: np.ndarray, class_names: list[str]):
|
| 70 |
+
y_pred = y_prob.argmax(axis=1)
|
| 71 |
+
labels = list(range(len(class_names)))
|
| 72 |
+
cm = confusion_matrix(y_true, y_pred, labels=labels)
|
| 73 |
+
precision, recall, f1, support = precision_recall_fscore_support(y_true, y_pred, labels=labels, zero_division=0)
|
| 74 |
+
total = int(cm.sum())
|
| 75 |
+
rows = []
|
| 76 |
+
for idx, name in enumerate(class_names):
|
| 77 |
+
tp = int(cm[idx, idx]); fn = int(cm[idx].sum() - tp); fp = int(cm[:, idx].sum() - tp); tn = total - tp - fn - fp
|
| 78 |
+
binary = (y_true == idx).astype(np.int64)
|
| 79 |
+
try:
|
| 80 |
+
auc = float(roc_auc_score(binary, y_prob[:, idx]))
|
| 81 |
+
except ValueError:
|
| 82 |
+
auc = None
|
| 83 |
+
rows.append({
|
| 84 |
+
"class": name, "support": int(support[idx]), "precision": float(precision[idx]),
|
| 85 |
+
"recall_sensitivity": float(recall[idx]), "specificity": tn / (tn + fp) if tn + fp else 0.0,
|
| 86 |
+
"f1": float(f1[idx]), "auc_ovr": auc,
|
| 87 |
+
})
|
| 88 |
+
macro = precision_recall_fscore_support(y_true, y_pred, labels=labels, average="macro", zero_division=0)
|
| 89 |
+
weighted = precision_recall_fscore_support(y_true, y_pred, labels=labels, average="weighted", zero_division=0)
|
| 90 |
+
y_true_bin = label_binarize(y_true, classes=labels)
|
| 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]),
|
| 97 |
+
"precision_weighted": float(weighted[0]), "recall_weighted": float(weighted[1]), "f1_weighted": float(weighted[2]),
|
| 98 |
+
"roc_auc_macro_ovr": safe_auc(y_true_bin, y_prob, "macro"),
|
| 99 |
+
"roc_auc_weighted_ovr": safe_auc(y_true_bin, y_prob, "weighted"),
|
| 100 |
+
"specificity_macro": float(np.mean([row["specificity"] for row in rows])),
|
| 101 |
+
"per_class": rows,
|
| 102 |
+
"classification_report": classification_report(y_true, y_pred, labels=labels, target_names=class_names, zero_division=0, output_dict=True),
|
| 103 |
+
}
|
| 104 |
+
return metrics, pd.DataFrame(rows), cm
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def apply_class_bias(y_prob: np.ndarray, bias: np.ndarray) -> np.ndarray:
|
| 108 |
+
logits = np.log(np.clip(y_prob, 1e-12, 1.0)) + bias[None, :]
|
| 109 |
+
logits -= logits.max(axis=1, keepdims=True)
|
| 110 |
+
exp = np.exp(logits)
|
| 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]["f1_macro"]
|
| 117 |
+
candidates = np.arange(-max_bias, max_bias + step / 2, step)
|
| 118 |
+
for _ in range(passes):
|
| 119 |
+
improved = False
|
| 120 |
+
for index in range(len(class_names)):
|
| 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]["f1_macro"]
|
| 125 |
+
if score > local_best:
|
| 126 |
+
local_best, local_value = score, float(value)
|
| 127 |
+
if local_best > best:
|
| 128 |
+
bias[index], best, improved = local_value, local_best, True
|
| 129 |
+
if not improved:
|
| 130 |
+
break
|
| 131 |
+
return bias, float(best)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def json_safe(value: Any):
|
| 135 |
+
if isinstance(value, Path): return str(value)
|
| 136 |
+
if isinstance(value, np.generic): return value.item()
|
| 137 |
+
if isinstance(value, np.ndarray): return value.tolist()
|
| 138 |
+
if isinstance(value, dict): return {str(k): json_safe(v) for k, v in value.items()}
|
| 139 |
+
if isinstance(value, (list, tuple)): return [json_safe(v) for v in value]
|
| 140 |
+
return value
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def save_evaluation(output_dir: Path, y_true, y_prob, df, class_names, prefix=""):
|
| 144 |
+
metrics, per_class, cm = compute_metrics(y_true, y_prob, class_names)
|
| 145 |
+
stem = f"{prefix}_" if prefix else ""
|
| 146 |
+
(output_dir / f"{stem}metrics.json").write_text(json.dumps(json_safe(metrics), indent=2), encoding="utf-8")
|
| 147 |
+
per_class.to_csv(output_dir / f"{stem}per_class_metrics.csv", index=False)
|
| 148 |
+
pd.DataFrame(cm, index=class_names, columns=class_names).to_csv(output_dir / f"{stem}confusion_matrix.csv")
|
| 149 |
+
predictions = pd.DataFrame(y_prob, columns=class_names)
|
| 150 |
+
predictions.insert(0, "true_label", [class_names[i] for i in y_true])
|
| 151 |
+
predictions.insert(0, "lesion_id", df["lesion_id"].tolist())
|
| 152 |
+
predictions.to_csv(output_dir / f"{stem}val_predictions.csv", index=False)
|
| 153 |
+
return metrics
|
milk10k_effb2_dermoscopic_metadata/data.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 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 create_or_load_split(df: pd.DataFrame, manifest: Path, val_size: float, seed: int) -> tuple[pd.DataFrame, pd.DataFrame]:
|
| 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 |
+
train_ids = set(map(str, payload["train_lesion_ids"]))
|
| 114 |
+
val_ids = set(map(str, payload["val_lesion_ids"]))
|
| 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
|
| 118 |
+
missing = all_ids - (train_ids | val_ids)
|
| 119 |
+
if unknown or missing:
|
| 120 |
+
raise ValueError(f"Split manifest does not match dataset (unknown={len(unknown)}, missing={len(missing)}).")
|
| 121 |
+
else:
|
| 122 |
+
train_rows, val_rows = train_test_split(
|
| 123 |
+
df[["lesion_id", "label"]], test_size=val_size, stratify=df["label"], random_state=seed
|
| 124 |
+
)
|
| 125 |
+
train_ids = set(train_rows["lesion_id"].astype(str))
|
| 126 |
+
val_ids = set(val_rows["lesion_id"].astype(str))
|
| 127 |
+
manifest.parent.mkdir(parents=True, exist_ok=True)
|
| 128 |
+
manifest.write_text(
|
| 129 |
+
json.dumps(
|
| 130 |
+
{
|
| 131 |
+
"seed": seed,
|
| 132 |
+
"val_size": val_size,
|
| 133 |
+
"train_lesion_ids": sorted(train_ids),
|
| 134 |
+
"val_lesion_ids": sorted(val_ids),
|
| 135 |
+
},
|
| 136 |
+
indent=2,
|
| 137 |
+
),
|
| 138 |
+
encoding="utf-8",
|
| 139 |
+
)
|
| 140 |
+
train_df = df[df["lesion_id"].astype(str).isin(train_ids)].copy()
|
| 141 |
+
val_df = df[df["lesion_id"].astype(str).isin(val_ids)].copy()
|
| 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(
|
| 148 |
+
[
|
| 149 |
+
transforms.RandomResizedCrop(image_size, scale=(0.75, 1.0)),
|
| 150 |
+
transforms.RandomHorizontalFlip(),
|
| 151 |
+
transforms.RandomVerticalFlip(),
|
| 152 |
+
transforms.RandomRotation(20),
|
| 153 |
+
transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2),
|
| 154 |
+
transforms.ToTensor(),
|
| 155 |
+
normalize,
|
| 156 |
+
]
|
| 157 |
+
)
|
| 158 |
+
eval_transform = transforms.Compose(
|
| 159 |
+
[transforms.Resize(round(image_size * 1.12)), transforms.CenterCrop(image_size), transforms.ToTensor(), normalize]
|
| 160 |
+
)
|
| 161 |
+
return train_transform, eval_transform
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class DermoscopicMetadataDataset(Dataset):
|
| 165 |
+
def __init__(self, df: pd.DataFrame, label_to_idx: dict[str, int] | None, metadata_spec: dict[str, Any], transform=None):
|
| 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:
|
| 172 |
+
return len(self.df)
|
| 173 |
+
|
| 174 |
+
def __getitem__(self, index: int) -> dict[str, torch.Tensor]:
|
| 175 |
+
row = self.df.iloc[index]
|
| 176 |
+
with Image.open(row["image_path"]) as source:
|
| 177 |
+
image = source.convert("RGB")
|
| 178 |
+
if self.transform:
|
| 179 |
+
image = self.transform(image)
|
| 180 |
+
item = {"image": image, "metadata": torch.from_numpy(self.metadata[index])}
|
| 181 |
+
if self.labels is not None:
|
| 182 |
+
item["label"] = torch.tensor(self.labels[index], dtype=torch.long)
|
| 183 |
+
return item
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def make_loaders(train_df, val_df, label_to_idx, metadata_spec, args):
|
| 187 |
+
train_transform, eval_transform = make_transforms(args.image_size)
|
| 188 |
+
train_ds = DermoscopicMetadataDataset(train_df, label_to_idx, metadata_spec, train_transform)
|
| 189 |
+
val_ds = DermoscopicMetadataDataset(val_df, label_to_idx, metadata_spec, eval_transform)
|
| 190 |
+
sampler = None
|
| 191 |
+
if args.weighted_sampler:
|
| 192 |
+
labels = np.asarray(train_ds.labels)
|
| 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())
|
| 200 |
+
return (
|
| 201 |
+
DataLoader(train_ds, shuffle=sampler is None, sampler=sampler, **common),
|
| 202 |
+
DataLoader(val_ds, shuffle=False, **common),
|
| 203 |
+
)
|
milk10k_effb2_dermoscopic_metadata/inference.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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("--input-dir", type=Path, required=True)
|
| 25 |
+
parser.add_argument("--metadata-csv", type=Path, required=True)
|
| 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 |
+
|
| 36 |
+
def checkpoint_paths(args):
|
| 37 |
+
paths = [path.expanduser().resolve() for path in args.checkpoint]
|
| 38 |
+
if args.checkpoint_dir:
|
| 39 |
+
directory = args.checkpoint_dir.expanduser().resolve()
|
| 40 |
+
folds = sorted(directory.glob("fold_*/best.pt"))
|
| 41 |
+
paths.extend(folds or ([directory / "best.pt"] if (directory / "best.pt").exists() else []))
|
| 42 |
+
if not paths:
|
| 43 |
+
raise ValueError("Pass --checkpoint or --checkpoint-dir containing best.pt.")
|
| 44 |
+
missing = [path for path in paths if not path.exists()]
|
| 45 |
+
if missing:
|
| 46 |
+
raise FileNotFoundError(f"Missing checkpoints: {missing}")
|
| 47 |
+
return paths
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def load_dataframe(input_dir: Path, metadata_csv: Path, groundtruth_csv: Path | None):
|
| 51 |
+
input_dir = input_dir.expanduser().resolve()
|
| 52 |
+
meta = pd.read_csv(metadata_csv.expanduser().resolve())
|
| 53 |
+
required = {"lesion_id", "isic_id", "image_type", *BASE_METADATA_COLUMNS}
|
| 54 |
+
missing = required - set(meta.columns)
|
| 55 |
+
if missing:
|
| 56 |
+
raise ValueError(f"Metadata CSV is missing columns: {sorted(missing)}")
|
| 57 |
+
meta["image_type_norm"] = meta["image_type"].map(normalize_image_type)
|
| 58 |
+
df = meta[meta["image_type_norm"] == "dermoscopic"].copy()
|
| 59 |
+
duplicates = df.groupby("lesion_id").size()
|
| 60 |
+
if (duplicates > 1).any():
|
| 61 |
+
raise ValueError("Expected exactly one dermoscopic row per lesion.")
|
| 62 |
+
df["image_path"] = df.apply(lambda row: input_dir / str(row["lesion_id"]) / f"{row['isic_id']}.jpg", axis=1)
|
| 63 |
+
df = df[df["image_path"].map(Path.exists)].copy(); df["image_path"] = df["image_path"].map(str)
|
| 64 |
+
if groundtruth_csv and groundtruth_csv.exists():
|
| 65 |
+
gt = pd.read_csv(groundtruth_csv)
|
| 66 |
+
columns = [name for name in LABEL_COLUMNS if name in gt.columns]
|
| 67 |
+
gt["label"] = gt[columns].idxmax(axis=1)
|
| 68 |
+
df = df.merge(gt[["lesion_id", "label"]], on="lesion_id", how="left", validate="one_to_one")
|
| 69 |
+
if df.empty:
|
| 70 |
+
raise ValueError("No existing dermoscopic image files were found.")
|
| 71 |
+
return df.reset_index(drop=True)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def build_model(checkpoint, device):
|
| 75 |
+
saved = checkpoint["args"]
|
| 76 |
+
spec = checkpoint["metadata_spec"]
|
| 77 |
+
input_dim = 2 + len(spec["sex_values"]) + len(spec["site_values"]) + len(spec.get("monet_columns", []))
|
| 78 |
+
model = DermoscopicMetadataClassifier(
|
| 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
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@torch.no_grad()
|
| 88 |
+
def predict(model, loader, device, tta):
|
| 89 |
+
output = []
|
| 90 |
+
for batch in tqdm(loader, leave=False):
|
| 91 |
+
image = batch["image"].to(device); metadata = batch["metadata"].to(device)
|
| 92 |
+
views = [image]
|
| 93 |
+
if tta:
|
| 94 |
+
views.extend([torch.flip(image, (-1,)), torch.flip(image, (-2,)), torch.flip(image, (-2, -1))])
|
| 95 |
+
probs = sum(torch.softmax(model(view, metadata), 1) for view in views) / len(views)
|
| 96 |
+
output.append(probs.cpu().numpy())
|
| 97 |
+
return np.concatenate(output)
|
| 98 |
+
|
| 99 |
+
|
| 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"]; spec = checkpoints[0]["metadata_spec"]
|
| 104 |
+
for checkpoint in checkpoints[1:]:
|
| 105 |
+
if checkpoint["class_names"] != class_names or checkpoint["metadata_spec"] != spec:
|
| 106 |
+
raise ValueError("Ensemble checkpoints have incompatible class names or metadata specs.")
|
| 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:
|
| 119 |
+
raise ValueError(f"Calibration class mismatch: {calibration_path}")
|
| 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); output.insert(0, "lesion_id", df["lesion_id"])
|
| 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)}
|
| 127 |
+
y_true = df["label"].map(mapping).to_numpy()
|
| 128 |
+
metrics, per_class, cm = compute_metrics(y_true, y_prob, class_names)
|
| 129 |
+
args.output.with_suffix(".metrics.json").write_text(json.dumps(json_safe(metrics), indent=2), encoding="utf-8")
|
| 130 |
+
per_class.to_csv(args.output.with_suffix(".per_class_metrics.csv"), index=False)
|
| 131 |
+
pd.DataFrame(cm, index=class_names, columns=class_names).to_csv(args.output.with_suffix(".confusion_matrix.csv"))
|
| 132 |
+
print(f"Saved {len(df)} dermoscopic predictions to {args.output}")
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def main():
|
| 136 |
+
run(parse_args())
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
if __name__ == "__main__":
|
| 140 |
+
main()
|
milk10k_effb2_dermoscopic_metadata/model.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
):
|
| 56 |
+
super().__init__()
|
| 57 |
+
if metadata_mode not in METADATA_MODES:
|
| 58 |
+
raise ValueError(f"Unsupported metadata mode: {metadata_mode}")
|
| 59 |
+
self.metadata_mode = metadata_mode
|
| 60 |
+
self.backbone_name = backbone
|
| 61 |
+
self.backbone_backend = backbone_backend
|
| 62 |
+
self.encoder, feature_dim = build_feature_encoder(backbone, backbone_backend, imagenet_pretrained)
|
| 63 |
+
self.image_head = nn.Sequential(nn.LayerNorm(feature_dim), nn.Dropout(dropout), nn.Linear(feature_dim, branch_dim), nn.GELU(), nn.LayerNorm(branch_dim))
|
| 64 |
+
if metadata_mode == "none":
|
| 65 |
+
self.metadata_head = None
|
| 66 |
+
self.metadata_gate = None
|
| 67 |
+
classifier_input = branch_dim
|
| 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, metadata_dim), nn.GELU(),
|
| 73 |
+
nn.Linear(metadata_dim, branch_dim), nn.Sigmoid()
|
| 74 |
+
)
|
| 75 |
+
nn.init.zeros_(self.metadata_gate[-2].weight)
|
| 76 |
+
nn.init.constant_(self.metadata_gate[-2].bias, 2.0)
|
| 77 |
+
else:
|
| 78 |
+
self.metadata_gate = None
|
| 79 |
+
classifier_input = branch_dim if metadata_mode == "gated_only" else branch_dim + metadata_dim
|
| 80 |
+
self.classifier = nn.Sequential(
|
| 81 |
+
nn.LayerNorm(classifier_input), nn.Dropout(dropout), nn.Linear(classifier_input, classifier_hidden_dim),
|
| 82 |
+
nn.GELU(), nn.Dropout(dropout), nn.Linear(classifier_hidden_dim, num_classes)
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
def forward(self, image: torch.Tensor, metadata: torch.Tensor | None = None) -> torch.Tensor:
|
| 86 |
+
features = self.image_head(self.encoder(image))
|
| 87 |
+
if self.metadata_mode == "none":
|
| 88 |
+
fused = features
|
| 89 |
+
else:
|
| 90 |
+
if metadata is None:
|
| 91 |
+
raise ValueError(f"metadata is required for metadata_mode={self.metadata_mode}")
|
| 92 |
+
if self.metadata_gate is not None:
|
| 93 |
+
features = features * self.metadata_gate(metadata)
|
| 94 |
+
fused = features if self.metadata_mode == "gated_only" else torch.cat([features, self.metadata_head(metadata)], dim=1)
|
| 95 |
+
return self.classifier(fused)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def set_encoder_trainable(model: DermoscopicMetadataClassifier, trainable: bool) -> None:
|
| 99 |
+
for parameter in model.encoder.parameters():
|
| 100 |
+
parameter.requires_grad = trainable
|
milk10k_effb2_dermoscopic_metadata/training.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Training CLI for the dermoscopic-only metadata classifier."""
|
| 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, build_loss, json_safe, optimize_class_bias, save_evaluation, set_seed
|
| 17 |
+
from .data import create_or_load_split, fit_metadata_spec, load_dermoscopic_dataframe, make_loaders, metadata_vector
|
| 18 |
+
from .model import DermoscopicMetadataClassifier, METADATA_MODES, set_encoder_trainable
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def parse_args(argv=None):
|
| 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 |
+
def load_encoder_checkpoint(path: Path, encoder, device):
|
| 68 |
+
payload = torch.load(path.expanduser().resolve(), map_location=device, weights_only=False)
|
| 69 |
+
state = payload.get("model_state", payload.get("model_state_dict", payload.get("state_dict", payload)))
|
| 70 |
+
prefixes = ("module.", "_orig_mod.", "model.", "encoder.", "dermoscopic_encoder.", "backbone.")
|
| 71 |
+
target = encoder.state_dict(); matched = {}
|
| 72 |
+
for raw_key, value in state.items():
|
| 73 |
+
variants = {raw_key}; key = raw_key
|
| 74 |
+
changed = True
|
| 75 |
+
while changed:
|
| 76 |
+
changed = False
|
| 77 |
+
for prefix in prefixes:
|
| 78 |
+
if key.startswith(prefix):
|
| 79 |
+
key = key.removeprefix(prefix); variants.add(key); changed = True; break
|
| 80 |
+
for candidate in variants:
|
| 81 |
+
if candidate in target and tuple(target[candidate].shape) == tuple(value.shape):
|
| 82 |
+
matched[candidate] = value; break
|
| 83 |
+
if not matched:
|
| 84 |
+
raise RuntimeError(f"No compatible encoder weights found in {path}")
|
| 85 |
+
target.update(matched); encoder.load_state_dict(target)
|
| 86 |
+
print(f"Loaded {len(matched)} encoder keys from {path}; skipped={len(state) - len(matched)}")
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def infer_checkpoint_backend(path: Path, device) -> str:
|
| 90 |
+
payload = torch.load(path.expanduser().resolve(), map_location=device, weights_only=False)
|
| 91 |
+
state = payload.get("model_state", payload.get("model_state_dict", payload.get("state_dict", payload)))
|
| 92 |
+
keys = []
|
| 93 |
+
for key in state:
|
| 94 |
+
for prefix in ("module.", "model.", "_orig_mod.", "encoder.", "dermoscopic_encoder."):
|
| 95 |
+
key = key.removeprefix(prefix)
|
| 96 |
+
keys.append(key)
|
| 97 |
+
timm_hits = sum(key.startswith(("conv_stem.", "blocks.", "conv_head.", "stages.", "stem.")) for key in keys)
|
| 98 |
+
torchvision_hits = sum(key.startswith(("features.", "avgpool.", "classifier.")) for key in keys)
|
| 99 |
+
if timm_hits > torchvision_hits: return "timm"
|
| 100 |
+
if torchvision_hits > timm_hits: return "torchvision"
|
| 101 |
+
raise RuntimeError(f"Cannot infer backbone backend from {path}; pass --backbone-backend explicitly.")
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def make_optimizer(model, args, encoder_trainable):
|
| 105 |
+
encoder = [p for p in model.encoder.parameters() if p.requires_grad]
|
| 106 |
+
head = [p for name, p in model.named_parameters() if not name.startswith("encoder.") and p.requires_grad]
|
| 107 |
+
groups = [{"params": head, "lr": args.head_lr}]
|
| 108 |
+
if encoder_trainable and encoder:
|
| 109 |
+
groups.append({"params": encoder, "lr": args.encoder_lr})
|
| 110 |
+
return torch.optim.AdamW(groups, weight_decay=args.weight_decay)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def run_epoch(model, loader, criterion, device, optimizer=None, use_amp=False):
|
| 114 |
+
training = optimizer is not None
|
| 115 |
+
model.train(training)
|
| 116 |
+
scaler = GradScaler("cuda", enabled=training and use_amp)
|
| 117 |
+
total_loss = total = correct = 0
|
| 118 |
+
y_true, y_pred = [], []
|
| 119 |
+
for batch in tqdm(loader, leave=False):
|
| 120 |
+
image = batch["image"].to(device, non_blocking=True)
|
| 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, enabled=use_amp):
|
| 127 |
+
logits = model(image, metadata)
|
| 128 |
+
loss = criterion(logits, labels)
|
| 129 |
+
if training:
|
| 130 |
+
scaler.scale(loss).backward()
|
| 131 |
+
scaler.unscale_(optimizer)
|
| 132 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 133 |
+
scaler.step(optimizer)
|
| 134 |
+
scaler.update()
|
| 135 |
+
size = labels.size(0)
|
| 136 |
+
total_loss += float(loss.detach()) * size; total += size
|
| 137 |
+
predicted = logits.argmax(1)
|
| 138 |
+
correct += int((predicted == labels).sum())
|
| 139 |
+
y_true.append(labels.detach().cpu().numpy()); y_pred.append(predicted.detach().cpu().numpy())
|
| 140 |
+
truth = np.concatenate(y_true); pred = np.concatenate(y_pred)
|
| 141 |
+
f1 = precision_recall_fscore_support(truth, pred, average="macro", zero_division=0)[2]
|
| 142 |
+
return {"loss": total_loss / total, "accuracy": correct / total, "balanced_accuracy": float(balanced_accuracy_score(truth, pred)), "f1_macro": float(f1)}
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@torch.no_grad()
|
| 146 |
+
def predict(model, loader, device):
|
| 147 |
+
model.eval(); labels = []; probabilities = []
|
| 148 |
+
for batch in tqdm(loader, leave=False):
|
| 149 |
+
logits = model(batch["image"].to(device), batch["metadata"].to(device))
|
| 150 |
+
labels.append(batch["label"].numpy()); probabilities.append(torch.softmax(logits, 1).cpu().numpy())
|
| 151 |
+
return np.concatenate(labels), np.concatenate(probabilities)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def checkpoint_payload(model, optimizer, epoch, phase, best, class_names, label_to_idx, metadata_spec, args):
|
| 155 |
+
return {
|
| 156 |
+
"epoch": epoch, "phase": phase, "best_val_f1_macro": best, "model_type": model.__class__.__name__,
|
| 157 |
+
"model_state": model.state_dict(), "optimizer_state": optimizer.state_dict(), "class_names": class_names,
|
| 158 |
+
"label_to_idx": label_to_idx, "metadata_spec": metadata_spec, "args": json_safe(vars(args)),
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def run(args):
|
| 163 |
+
if args.freeze_epochs + args.finetune_epochs <= 0:
|
| 164 |
+
raise ValueError("At least one training epoch is required.")
|
| 165 |
+
set_seed(args.seed)
|
| 166 |
+
output_dir = args.output_dir.expanduser().resolve(); output_dir.mkdir(parents=True, exist_ok=True)
|
| 167 |
+
df = load_dermoscopic_dataframe(args.data_dir, args.input_dir)
|
| 168 |
+
train_df, val_df = create_or_load_split(df, args.split_manifest, args.val_size, args.seed)
|
| 169 |
+
class_names = sorted(df["label"].unique()); label_to_idx = {name: i for i, name in enumerate(class_names)}
|
| 170 |
+
metadata_spec = fit_metadata_spec(train_df)
|
| 171 |
+
metadata_input_dim = len(metadata_vector(train_df.iloc[0], metadata_spec))
|
| 172 |
+
train_loader, val_loader = make_loaders(train_df, val_df, label_to_idx, metadata_spec, args)
|
| 173 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 174 |
+
if args.backbone_backend == "auto":
|
| 175 |
+
if args.resume_checkpoint:
|
| 176 |
+
resume_header = torch.load(args.resume_checkpoint.expanduser().resolve(), map_location="cpu", weights_only=False)
|
| 177 |
+
backbone_backend = resume_header.get("args", {}).get("backbone_backend", "timm")
|
| 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 = torch.load(args.resume_checkpoint.expanduser().resolve(), map_location=device, weights_only=False)
|
| 195 |
+
model.load_state_dict(resume["model_state"])
|
| 196 |
+
start_epoch = int(resume.get("epoch", 0)) + 1; best = float(resume.get("best_val_f1_macro", best))
|
| 197 |
+
elif args.encoder_checkpoint:
|
| 198 |
+
load_encoder_checkpoint(args.encoder_checkpoint, model.encoder, device)
|
| 199 |
+
|
| 200 |
+
train_df.to_csv(output_dir / "train_split.csv", index=False); val_df.to_csv(output_dir / "val_split.csv", index=False)
|
| 201 |
+
config = {"args": json_safe(vars(args)), "class_names": class_names, "label_to_idx": label_to_idx, "metadata_spec": metadata_spec,
|
| 202 |
+
"metadata_input_dim": metadata_input_dim, "backbone_backend_resolved": backbone_backend,
|
| 203 |
+
"train_size": len(train_df), "val_size": len(val_df)}
|
| 204 |
+
(output_dir / "run_config.json").write_text(json.dumps(config, indent=2), encoding="utf-8")
|
| 205 |
+
|
| 206 |
+
weights = class_weight_tensor(train_df, class_names, device) if args.class_weight else None
|
| 207 |
+
criterion = build_loss(args.loss, len(class_names), args.dice_weight, weights)
|
| 208 |
+
history = []
|
| 209 |
+
history_path = output_dir / "history.csv"
|
| 210 |
+
if history_path.exists() and args.resume_checkpoint:
|
| 211 |
+
history = pd.read_csv(history_path).to_dict("records")
|
| 212 |
+
global_epoch = 0
|
| 213 |
+
for phase, count, encoder_trainable in (("freeze", args.freeze_epochs, False), ("finetune", args.finetune_epochs, True)):
|
| 214 |
+
set_encoder_trainable(model, encoder_trainable)
|
| 215 |
+
optimizer = make_optimizer(model, args, encoder_trainable)
|
| 216 |
+
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode="max", factor=0.2, patience=2)
|
| 217 |
+
patience = 0
|
| 218 |
+
for _ in range(count):
|
| 219 |
+
global_epoch += 1
|
| 220 |
+
if global_epoch < start_epoch:
|
| 221 |
+
continue
|
| 222 |
+
train_stats = run_epoch(model, train_loader, criterion, device, optimizer, args.amp and device.type == "cuda")
|
| 223 |
+
val_stats = run_epoch(model, val_loader, criterion, device, None, args.amp and device.type == "cuda")
|
| 224 |
+
scheduler.step(val_stats["f1_macro"])
|
| 225 |
+
row = {"phase": phase, "epoch": global_epoch, **{f"train_{k}": v for k, v in train_stats.items()}, **{f"val_{k}": v for k, v in val_stats.items()}}
|
| 226 |
+
history.append(row); pd.DataFrame(history).to_csv(history_path, index=False)
|
| 227 |
+
torch.save(checkpoint_payload(model, optimizer, global_epoch, phase, best, class_names, label_to_idx, metadata_spec, args), output_dir / "last.pt")
|
| 228 |
+
if val_stats["f1_macro"] > best:
|
| 229 |
+
best = val_stats["f1_macro"]; patience = 0
|
| 230 |
+
torch.save(checkpoint_payload(model, optimizer, global_epoch, phase, best, class_names, label_to_idx, metadata_spec, args), output_dir / "best.pt")
|
| 231 |
+
else:
|
| 232 |
+
patience += 1
|
| 233 |
+
print(f"{phase} epoch={global_epoch:03d} train_f1={train_stats['f1_macro']:.4f} val_f1={val_stats['f1_macro']:.4f}")
|
| 234 |
+
if args.patience > 0 and patience >= args.patience:
|
| 235 |
+
print(f"Early stopping {phase} after {patience} epochs without improvement."); break
|
| 236 |
+
|
| 237 |
+
best_checkpoint = torch.load(output_dir / "best.pt", map_location=device, weights_only=False)
|
| 238 |
+
model.load_state_dict(best_checkpoint["model_state"])
|
| 239 |
+
y_true, y_prob = predict(model, val_loader, device)
|
| 240 |
+
metrics = save_evaluation(output_dir, y_true, y_prob, val_df, class_names)
|
| 241 |
+
metrics["best_val_f1_macro"] = best
|
| 242 |
+
(output_dir / "metrics.json").write_text(json.dumps(json_safe(metrics), indent=2), encoding="utf-8")
|
| 243 |
+
if args.calibrate_bias:
|
| 244 |
+
bias, score = optimize_class_bias(y_true, y_prob, class_names, args.calibration_max_bias, args.calibration_step, args.calibration_passes)
|
| 245 |
+
calibration = {"class_names": class_names, "class_bias": bias.tolist(), "raw_f1_macro": metrics["f1_macro"], "calibrated_f1_macro": score}
|
| 246 |
+
(output_dir / "calibration.json").write_text(json.dumps(calibration, indent=2), encoding="utf-8")
|
| 247 |
+
save_evaluation(output_dir, y_true, apply_class_bias(y_prob, bias), val_df, class_names, prefix="calibrated")
|
| 248 |
+
print(f"Finished: output={output_dir}, val_f1_macro={metrics['f1_macro']:.4f}")
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def main():
|
| 252 |
+
run(parse_args())
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
if __name__ == "__main__":
|
| 256 |
+
main()
|
predict_milk10k_effb2_dermoscopic_metadata.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from milk10k_effb2_dermoscopic_metadata.inference import main
|
| 3 |
+
|
| 4 |
+
if __name__ == "__main__":
|
| 5 |
+
main()
|
run_metadata_ablation.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from milk10k_effb2_dermoscopic_metadata.ablation import main
|
| 3 |
+
|
| 4 |
+
if __name__ == "__main__":
|
| 5 |
+
main()
|
train_milk10k_effb2_dermoscopic_metadata.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from milk10k_effb2_dermoscopic_metadata.training import main
|
| 3 |
+
|
| 4 |
+
if __name__ == "__main__":
|
| 5 |
+
main()
|