Upload 16 files
Browse files- milk10k_effb2_metadata/__init__.py +2 -0
- milk10k_effb2_metadata/__pycache__/__init__.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/checkpoints.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/cli.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/data.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/losses.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/metrics.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/models.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/training.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/checkpoints.py +92 -0
- milk10k_effb2_metadata/cli.py +58 -0
- milk10k_effb2_metadata/data.py +262 -0
- milk10k_effb2_metadata/losses.py +111 -0
- milk10k_effb2_metadata/metrics.py +144 -0
- milk10k_effb2_metadata/models.py +122 -0
- milk10k_effb2_metadata/training.py +502 -0
milk10k_effb2_metadata/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""EfficientNet-B2 dual-branch MILK10k metadata trainer."""
|
| 2 |
+
|
milk10k_effb2_metadata/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (201 Bytes). View file
|
|
|
milk10k_effb2_metadata/__pycache__/checkpoints.cpython-314.pyc
ADDED
|
Binary file (7.04 kB). View file
|
|
|
milk10k_effb2_metadata/__pycache__/cli.cpython-314.pyc
ADDED
|
Binary file (4.28 kB). View file
|
|
|
milk10k_effb2_metadata/__pycache__/data.cpython-314.pyc
ADDED
|
Binary file (19.9 kB). View file
|
|
|
milk10k_effb2_metadata/__pycache__/losses.cpython-314.pyc
ADDED
|
Binary file (9.1 kB). View file
|
|
|
milk10k_effb2_metadata/__pycache__/metrics.cpython-314.pyc
ADDED
|
Binary file (9.11 kB). View file
|
|
|
milk10k_effb2_metadata/__pycache__/models.cpython-314.pyc
ADDED
|
Binary file (7.91 kB). View file
|
|
|
milk10k_effb2_metadata/__pycache__/training.cpython-314.pyc
ADDED
|
Binary file (24.2 kB). View file
|
|
|
milk10k_effb2_metadata/checkpoints.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Checkpoint loading utilities for mixed timm/torchvision EfficientNet-B2 branches."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from torch import nn
|
| 11 |
+
|
| 12 |
+
CHECKPOINT_STATE_KEYS = ("model_state", "model_state_dict", "state_dict")
|
| 13 |
+
PREFIXES_TO_STRIP = ("module.", "model.", "_orig_mod.")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def extract_state_dict(checkpoint: Any) -> dict[str, torch.Tensor]:
|
| 17 |
+
if isinstance(checkpoint, dict):
|
| 18 |
+
for key in CHECKPOINT_STATE_KEYS:
|
| 19 |
+
value = checkpoint.get(key)
|
| 20 |
+
if isinstance(value, dict):
|
| 21 |
+
return value
|
| 22 |
+
if isinstance(checkpoint, dict) and all(torch.is_tensor(value) for value in checkpoint.values()):
|
| 23 |
+
return checkpoint
|
| 24 |
+
raise ValueError("Checkpoint does not contain a supported state dict.")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def load_raw_checkpoint(path: Path, device: torch.device, branch_name: str) -> Any:
|
| 28 |
+
if not path.exists():
|
| 29 |
+
raise FileNotFoundError(f"{branch_name} checkpoint not found: {path}")
|
| 30 |
+
try:
|
| 31 |
+
return torch.load(path, map_location=device, weights_only=False)
|
| 32 |
+
except TypeError:
|
| 33 |
+
return torch.load(path, map_location=device)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def normalize_key(key: str) -> str:
|
| 37 |
+
changed = True
|
| 38 |
+
while changed:
|
| 39 |
+
changed = False
|
| 40 |
+
for prefix in PREFIXES_TO_STRIP:
|
| 41 |
+
if key.startswith(prefix):
|
| 42 |
+
key = key.removeprefix(prefix)
|
| 43 |
+
changed = True
|
| 44 |
+
return key
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def infer_checkpoint_backend(path: Path, device: torch.device, branch_name: str) -> str:
|
| 48 |
+
checkpoint = load_raw_checkpoint(path, device, branch_name)
|
| 49 |
+
state = extract_state_dict(checkpoint)
|
| 50 |
+
keys = {normalize_key(key) for key in state}
|
| 51 |
+
timm_prefixes = ("conv_stem.", "bn1.", "blocks.", "conv_head.", "bn2.")
|
| 52 |
+
torchvision_prefixes = ("features.", "avgpool.", "classifier.")
|
| 53 |
+
timm_hits = sum(key.startswith(timm_prefixes) for key in keys)
|
| 54 |
+
torchvision_hits = sum(key.startswith(torchvision_prefixes) for key in keys)
|
| 55 |
+
if timm_hits > torchvision_hits:
|
| 56 |
+
return "timm"
|
| 57 |
+
if torchvision_hits > timm_hits:
|
| 58 |
+
return "torchvision"
|
| 59 |
+
raise RuntimeError(
|
| 60 |
+
f"{branch_name}: cannot infer checkpoint backend from {path}. "
|
| 61 |
+
"Pass --backbone-backend timm or --backbone-backend torchvision explicitly."
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def resolve_backbone_backends(args: argparse.Namespace, device: torch.device) -> tuple[str, str]:
|
| 66 |
+
if args.backbone_backend != "auto":
|
| 67 |
+
return args.backbone_backend, args.backbone_backend
|
| 68 |
+
|
| 69 |
+
clinical_backend = infer_checkpoint_backend(args.clinical_checkpoint, device, "clinical")
|
| 70 |
+
dermoscopic_backend = infer_checkpoint_backend(args.dermoscopic_checkpoint, device, "dermoscopic")
|
| 71 |
+
print(f"Auto-detected backbone backends: clinical={clinical_backend}, dermoscopic={dermoscopic_backend}")
|
| 72 |
+
return clinical_backend, dermoscopic_backend
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def load_encoder_checkpoint(path: Path, encoder: nn.Module, branch_name: str, device: torch.device) -> None:
|
| 76 |
+
checkpoint = load_raw_checkpoint(path, device, branch_name)
|
| 77 |
+
raw_state = extract_state_dict(checkpoint)
|
| 78 |
+
source_state = {normalize_key(key): value for key, value in raw_state.items()}
|
| 79 |
+
target_state = encoder.state_dict()
|
| 80 |
+
matched = {
|
| 81 |
+
key: value
|
| 82 |
+
for key, value in source_state.items()
|
| 83 |
+
if key in target_state and tuple(value.shape) == tuple(target_state[key].shape)
|
| 84 |
+
}
|
| 85 |
+
skipped = len(source_state) - len(matched)
|
| 86 |
+
if not matched:
|
| 87 |
+
raise RuntimeError(f"{branch_name}: no matching encoder weights loaded from {path}")
|
| 88 |
+
|
| 89 |
+
target_state.update(matched)
|
| 90 |
+
encoder.load_state_dict(target_state)
|
| 91 |
+
print(f"{branch_name}: loaded {len(matched)} keys from {path}; skipped {skipped} keys")
|
| 92 |
+
|
milk10k_effb2_metadata/cli.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CLI for the EfficientNet-B2 dual metadata trainer."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def parse_args() -> argparse.Namespace:
|
| 10 |
+
parser = argparse.ArgumentParser(description="Train MILK10k dual EfficientNet-B2 with metadata fusion.")
|
| 11 |
+
parser.add_argument("--data-dir", type=Path, default=None)
|
| 12 |
+
parser.add_argument("--clinical-checkpoint", type=Path, required=True)
|
| 13 |
+
parser.add_argument("--dermoscopic-checkpoint", type=Path, required=True)
|
| 14 |
+
parser.add_argument("--output-dir", type=Path, default=Path("milk10k_dual_effb2_metadata_runs"))
|
| 15 |
+
parser.add_argument("--freeze-epochs", type=int, default=8)
|
| 16 |
+
parser.add_argument("--finetune-epochs", type=int, default=20)
|
| 17 |
+
parser.add_argument("--batch-size", type=int, default=8)
|
| 18 |
+
parser.add_argument("--image-size", type=int, default=260)
|
| 19 |
+
parser.add_argument(
|
| 20 |
+
"--num-workers",
|
| 21 |
+
type=int,
|
| 22 |
+
default=0,
|
| 23 |
+
help="DataLoader workers. Keep 0 in small Docker/Marimo containers to avoid /dev/shm exhaustion.",
|
| 24 |
+
)
|
| 25 |
+
parser.add_argument("--head-lr", type=float, default=1e-4)
|
| 26 |
+
parser.add_argument("--encoder-lr", type=float, default=1e-5)
|
| 27 |
+
parser.add_argument("--weight-decay", type=float, default=1e-4)
|
| 28 |
+
parser.add_argument("--val-size", type=float, default=0.20)
|
| 29 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 30 |
+
parser.add_argument("--branch-dim", type=int, default=512)
|
| 31 |
+
parser.add_argument("--metadata-dim", type=int, default=64)
|
| 32 |
+
parser.add_argument("--classifier-hidden-dim", type=int, default=512)
|
| 33 |
+
parser.add_argument("--dropout", type=float, default=0.3)
|
| 34 |
+
parser.add_argument("--class-weight", action="store_true")
|
| 35 |
+
parser.add_argument("--weighted-sampler", action="store_true")
|
| 36 |
+
parser.add_argument("--sampler-power", type=float, default=1.0)
|
| 37 |
+
parser.add_argument("--loss", choices=["ce", "focal", "milk_lt"], default="ce")
|
| 38 |
+
parser.add_argument("--focal-gamma", type=float, default=2.0)
|
| 39 |
+
parser.add_argument("--lt-beta", type=float, default=0.9999)
|
| 40 |
+
parser.add_argument("--lt-max-margin", type=float, default=0.5)
|
| 41 |
+
parser.add_argument("--lt-logit-tau", type=float, default=1.0)
|
| 42 |
+
parser.add_argument("--lt-draw-start-epoch", "--lt-drw-start-epoch", dest="lt_draw_start_epoch", type=int, default=0)
|
| 43 |
+
parser.add_argument("--lt-alpha-max", type=float, default=10.0)
|
| 44 |
+
parser.add_argument("--k-folds", type=int, default=1)
|
| 45 |
+
parser.add_argument("--amp", action="store_true")
|
| 46 |
+
parser.add_argument(
|
| 47 |
+
"--backbone-backend",
|
| 48 |
+
choices=["auto", "timm", "torchvision"],
|
| 49 |
+
default="auto",
|
| 50 |
+
help="Backbone implementation used by checkpoints. auto detects timm vs torchvision from checkpoint keys.",
|
| 51 |
+
)
|
| 52 |
+
parser.add_argument(
|
| 53 |
+
"--imagenet-pretrained",
|
| 54 |
+
action="store_true",
|
| 55 |
+
help="Initialize EfficientNet-B2 with ImageNet weights before loading branch checkpoints.",
|
| 56 |
+
)
|
| 57 |
+
parser.add_argument("--patience", type=int, default=6)
|
| 58 |
+
return parser.parse_args()
|
milk10k_effb2_metadata/data.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dataframe, metadata, split, and dataloader helpers."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 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 |
+
from datasets import LABEL_COLUMNS, normalize_image_type
|
| 18 |
+
|
| 19 |
+
ImageFile.LOAD_TRUNCATED_IMAGES = True
|
| 20 |
+
|
| 21 |
+
METADATA_COLUMNS = ("age_approx", "sex", "skin_tone_class", "site")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class PairedMilk10kMetadataDataset(Dataset):
|
| 25 |
+
def __init__(
|
| 26 |
+
self,
|
| 27 |
+
df: pd.DataFrame,
|
| 28 |
+
label_to_idx: dict[str, int],
|
| 29 |
+
metadata_spec: dict[str, Any],
|
| 30 |
+
transform=None,
|
| 31 |
+
) -> None:
|
| 32 |
+
self.df = df.reset_index(drop=True)
|
| 33 |
+
self.labels = [label_to_idx[label] for label in self.df["label"].tolist()]
|
| 34 |
+
self.metadata = np.stack([metadata_vector(row, metadata_spec) for _, row in self.df.iterrows()])
|
| 35 |
+
self.transform = transform
|
| 36 |
+
|
| 37 |
+
def __len__(self) -> int:
|
| 38 |
+
return len(self.df)
|
| 39 |
+
|
| 40 |
+
def _load_image(self, path: str) -> torch.Tensor:
|
| 41 |
+
with Image.open(path) as img:
|
| 42 |
+
image = img.convert("RGB")
|
| 43 |
+
if self.transform is not None:
|
| 44 |
+
image = self.transform(image)
|
| 45 |
+
return image
|
| 46 |
+
|
| 47 |
+
def __getitem__(self, idx: int) -> dict[str, torch.Tensor]:
|
| 48 |
+
row = self.df.iloc[idx]
|
| 49 |
+
return {
|
| 50 |
+
"clinical": self._load_image(row["clinical_path"]),
|
| 51 |
+
"dermoscopic": self._load_image(row["dermoscopic_path"]),
|
| 52 |
+
"metadata": torch.from_numpy(self.metadata[idx]),
|
| 53 |
+
"label": torch.tensor(self.labels[idx], dtype=torch.long),
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def load_paired_dataframe(data_dir: Path) -> pd.DataFrame:
|
| 58 |
+
input_dir = data_dir / "MILK10k_Training_Input"
|
| 59 |
+
gt = pd.read_csv(data_dir / "MILK10k_Training_GroundTruth.csv")
|
| 60 |
+
meta = pd.read_csv(data_dir / "MILK10k_Training_Metadata.csv")
|
| 61 |
+
monet_columns = resolve_monet_columns(meta)
|
| 62 |
+
|
| 63 |
+
gt["label"] = gt[LABEL_COLUMNS].idxmax(axis=1)
|
| 64 |
+
meta["image_type_norm"] = meta["image_type"].map(normalize_image_type)
|
| 65 |
+
meta["path"] = meta.apply(lambda r: input_dir / r["lesion_id"] / f"{r['isic_id']}.jpg", axis=1)
|
| 66 |
+
meta = meta[meta["path"].map(lambda p: p.exists())].copy()
|
| 67 |
+
meta["path"] = meta["path"].map(str)
|
| 68 |
+
|
| 69 |
+
keep = ["lesion_id", "path", *METADATA_COLUMNS, *monet_columns]
|
| 70 |
+
clinical = meta[meta["image_type_norm"] == "clinical_close_up"][keep].drop_duplicates("lesion_id")
|
| 71 |
+
dermoscopic = meta[meta["image_type_norm"] == "dermoscopic"][keep].drop_duplicates("lesion_id")
|
| 72 |
+
paired = (
|
| 73 |
+
gt[["lesion_id", "label"]]
|
| 74 |
+
.merge(clinical.add_prefix("clinical_"), left_on="lesion_id", right_on="clinical_lesion_id")
|
| 75 |
+
.merge(dermoscopic.add_prefix("dermoscopic_"), left_on="lesion_id", right_on="dermoscopic_lesion_id")
|
| 76 |
+
.drop(columns=["clinical_lesion_id", "dermoscopic_lesion_id"])
|
| 77 |
+
)
|
| 78 |
+
if paired.empty:
|
| 79 |
+
raise ValueError(f"No paired clinical/dermoscopic lesions found under {input_dir}")
|
| 80 |
+
return paired
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def resolve_monet_columns(meta: pd.DataFrame) -> list[str]:
|
| 84 |
+
try:
|
| 85 |
+
from milk10k_dual_encoder.config import MONET_COLUMNS
|
| 86 |
+
|
| 87 |
+
configured = [column for column in MONET_COLUMNS if column in meta.columns]
|
| 88 |
+
if configured:
|
| 89 |
+
return configured
|
| 90 |
+
except Exception:
|
| 91 |
+
pass
|
| 92 |
+
return sorted(column for column in meta.columns if column.startswith("MONET_"))
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def lesion_split(df: pd.DataFrame, val_size: float, seed: int) -> tuple[pd.DataFrame, pd.DataFrame]:
|
| 96 |
+
lesion_df = df[["lesion_id", "label"]].drop_duplicates("lesion_id")
|
| 97 |
+
train_lesions, val_lesions = train_test_split(
|
| 98 |
+
lesion_df,
|
| 99 |
+
test_size=val_size,
|
| 100 |
+
stratify=lesion_df["label"],
|
| 101 |
+
random_state=seed,
|
| 102 |
+
)
|
| 103 |
+
return split_by_lesion_ids(df, train_lesions["lesion_id"], val_lesions["lesion_id"])
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def kfold_splits(df: pd.DataFrame, k_folds: int, seed: int) -> list[tuple[pd.DataFrame, pd.DataFrame]]:
|
| 107 |
+
if k_folds < 2:
|
| 108 |
+
raise ValueError("--k-folds must be 1 for single split or at least 2 for k-fold training.")
|
| 109 |
+
|
| 110 |
+
lesion_df = df[["lesion_id", "label"]].drop_duplicates("lesion_id").reset_index(drop=True)
|
| 111 |
+
min_class_count = int(lesion_df["label"].value_counts().min())
|
| 112 |
+
if k_folds > min_class_count:
|
| 113 |
+
raise ValueError(
|
| 114 |
+
f"--k-folds={k_folds} is larger than the smallest class count ({min_class_count}). "
|
| 115 |
+
"Use fewer folds or merge/remove ultra-rare classes."
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
splitter = StratifiedKFold(n_splits=k_folds, shuffle=True, random_state=seed)
|
| 119 |
+
splits = []
|
| 120 |
+
for train_idx, val_idx in splitter.split(lesion_df["lesion_id"], lesion_df["label"]):
|
| 121 |
+
train_lesions = lesion_df.iloc[train_idx]["lesion_id"]
|
| 122 |
+
val_lesions = lesion_df.iloc[val_idx]["lesion_id"]
|
| 123 |
+
splits.append(split_by_lesion_ids(df, train_lesions, val_lesions))
|
| 124 |
+
return splits
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def split_by_lesion_ids(
|
| 128 |
+
df: pd.DataFrame,
|
| 129 |
+
train_lesions: pd.Series,
|
| 130 |
+
val_lesions: pd.Series,
|
| 131 |
+
) -> tuple[pd.DataFrame, pd.DataFrame]:
|
| 132 |
+
return (
|
| 133 |
+
df[df["lesion_id"].isin(train_lesions)].copy(),
|
| 134 |
+
df[df["lesion_id"].isin(val_lesions)].copy(),
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def fit_metadata_spec(train_df: pd.DataFrame) -> dict[str, Any]:
|
| 139 |
+
sex_values = sorted({"unknown"} | collect_string_values(train_df, "sex"))
|
| 140 |
+
site_values = sorted({"unknown"} | collect_string_values(train_df, "site"))
|
| 141 |
+
return {
|
| 142 |
+
"sex_values": sex_values,
|
| 143 |
+
"site_values": site_values,
|
| 144 |
+
"monet_columns": infer_paired_monet_columns(train_df),
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def collect_string_values(df: pd.DataFrame, field: str) -> set[str]:
|
| 149 |
+
values: set[str] = set()
|
| 150 |
+
for prefix in ("clinical", "dermoscopic"):
|
| 151 |
+
series = df[f"{prefix}_{field}"].fillna("unknown").astype(str).str.strip()
|
| 152 |
+
values.update(value if value else "unknown" for value in series.tolist())
|
| 153 |
+
return values
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def infer_paired_monet_columns(df: pd.DataFrame) -> list[str]:
|
| 157 |
+
clinical_prefix = "clinical_MONET_"
|
| 158 |
+
return sorted(
|
| 159 |
+
column.removeprefix("clinical_")
|
| 160 |
+
for column in df.columns
|
| 161 |
+
if column.startswith(clinical_prefix) and f"dermoscopic_{column.removeprefix('clinical_')}" in df.columns
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def metadata_vector(row: pd.Series, spec: dict[str, Any]) -> np.ndarray:
|
| 166 |
+
age = first_numeric(row, "age_approx")
|
| 167 |
+
skin_tone = first_numeric(row, "skin_tone_class")
|
| 168 |
+
sex = first_string(row, "sex")
|
| 169 |
+
site = first_string(row, "site")
|
| 170 |
+
|
| 171 |
+
values: list[float] = [
|
| 172 |
+
0.0 if age is None else float(age) / 100.0,
|
| 173 |
+
0.0 if skin_tone is None else float(skin_tone) / 6.0,
|
| 174 |
+
]
|
| 175 |
+
values.extend(1.0 if sex == item else 0.0 for item in spec["sex_values"])
|
| 176 |
+
values.extend(1.0 if site == item else 0.0 for item in spec["site_values"])
|
| 177 |
+
|
| 178 |
+
for prefix in ("clinical", "dermoscopic"):
|
| 179 |
+
for column in spec.get("monet_columns", []):
|
| 180 |
+
value = pd.to_numeric(row.get(f"{prefix}_{column}"), errors="coerce")
|
| 181 |
+
values.append(0.0 if pd.isna(value) else float(value))
|
| 182 |
+
|
| 183 |
+
return np.asarray(values, dtype=np.float32)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def first_numeric(row: pd.Series, field: str) -> float | None:
|
| 187 |
+
for prefix in ("clinical", "dermoscopic"):
|
| 188 |
+
value = pd.to_numeric(row.get(f"{prefix}_{field}"), errors="coerce")
|
| 189 |
+
if not pd.isna(value):
|
| 190 |
+
return float(value)
|
| 191 |
+
return None
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def first_string(row: pd.Series, field: str) -> str:
|
| 195 |
+
for prefix in ("clinical", "dermoscopic"):
|
| 196 |
+
value = row.get(f"{prefix}_{field}")
|
| 197 |
+
if pd.notna(value):
|
| 198 |
+
value = str(value).strip()
|
| 199 |
+
if value:
|
| 200 |
+
return value
|
| 201 |
+
return "unknown"
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def make_transforms(image_size: int):
|
| 205 |
+
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
| 206 |
+
train_transform = transforms.Compose(
|
| 207 |
+
[
|
| 208 |
+
transforms.Resize((image_size, image_size)),
|
| 209 |
+
transforms.RandomHorizontalFlip(),
|
| 210 |
+
transforms.RandomVerticalFlip(),
|
| 211 |
+
transforms.RandomRotation(20),
|
| 212 |
+
transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2),
|
| 213 |
+
transforms.ToTensor(),
|
| 214 |
+
normalize,
|
| 215 |
+
]
|
| 216 |
+
)
|
| 217 |
+
eval_transform = transforms.Compose(
|
| 218 |
+
[
|
| 219 |
+
transforms.Resize((image_size, image_size)),
|
| 220 |
+
transforms.ToTensor(),
|
| 221 |
+
normalize,
|
| 222 |
+
]
|
| 223 |
+
)
|
| 224 |
+
return train_transform, eval_transform
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def make_loaders(
|
| 228 |
+
train_df: pd.DataFrame,
|
| 229 |
+
val_df: pd.DataFrame,
|
| 230 |
+
label_to_idx: dict[str, int],
|
| 231 |
+
metadata_spec: dict[str, Any],
|
| 232 |
+
args: argparse.Namespace,
|
| 233 |
+
) -> tuple[DataLoader, DataLoader]:
|
| 234 |
+
train_transform, eval_transform = make_transforms(args.image_size)
|
| 235 |
+
train_ds = PairedMilk10kMetadataDataset(train_df, label_to_idx, metadata_spec, train_transform)
|
| 236 |
+
val_ds = PairedMilk10kMetadataDataset(val_df, label_to_idx, metadata_spec, eval_transform)
|
| 237 |
+
common = dict(
|
| 238 |
+
batch_size=args.batch_size,
|
| 239 |
+
num_workers=args.num_workers,
|
| 240 |
+
pin_memory=torch.cuda.is_available(),
|
| 241 |
+
drop_last=False,
|
| 242 |
+
)
|
| 243 |
+
sampler = build_weighted_sampler(train_ds, args) if args.weighted_sampler else None
|
| 244 |
+
train_loader = DataLoader(train_ds, shuffle=sampler is None, sampler=sampler, **common)
|
| 245 |
+
val_loader = DataLoader(val_ds, shuffle=False, **common)
|
| 246 |
+
return train_loader, val_loader
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def build_weighted_sampler(
|
| 250 |
+
dataset: PairedMilk10kMetadataDataset,
|
| 251 |
+
args: argparse.Namespace,
|
| 252 |
+
) -> WeightedRandomSampler:
|
| 253 |
+
labels = np.asarray(dataset.labels)
|
| 254 |
+
counts = np.bincount(labels)
|
| 255 |
+
if np.any(counts == 0):
|
| 256 |
+
raise ValueError("Cannot build weighted sampler because at least one class has zero training samples.")
|
| 257 |
+
class_weights = 1.0 / np.power(counts.astype(np.float64), args.sampler_power)
|
| 258 |
+
sample_weights = torch.as_tensor(class_weights[labels], dtype=torch.double)
|
| 259 |
+
generator = torch.Generator()
|
| 260 |
+
generator.manual_seed(args.seed)
|
| 261 |
+
return WeightedRandomSampler(sample_weights, num_samples=len(dataset), replacement=True, generator=generator)
|
| 262 |
+
|
milk10k_effb2_metadata/losses.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Classification losses for the EffB2 metadata trainer."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
from sklearn.utils.class_weight import compute_class_weight
|
| 12 |
+
from torch import nn
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class FocalLoss(nn.Module):
|
| 16 |
+
def __init__(self, weight: torch.Tensor | None = None, gamma: float = 2.0) -> None:
|
| 17 |
+
super().__init__()
|
| 18 |
+
self.weight = weight
|
| 19 |
+
self.gamma = gamma
|
| 20 |
+
|
| 21 |
+
def forward(self, logits: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
|
| 22 |
+
ce = F.cross_entropy(logits, labels, reduction="none")
|
| 23 |
+
pt = torch.exp(-ce)
|
| 24 |
+
loss = (1.0 - pt) ** self.gamma * ce
|
| 25 |
+
if self.weight is not None:
|
| 26 |
+
loss = loss * self.weight[labels]
|
| 27 |
+
return loss.mean()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class MILKLongTailLoss(nn.Module):
|
| 31 |
+
"""LDAM + balanced-softmax/logit adjustment + deferred effective-number alpha."""
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self,
|
| 35 |
+
class_counts: torch.Tensor,
|
| 36 |
+
beta: float = 0.9999,
|
| 37 |
+
max_margin: float = 0.5,
|
| 38 |
+
logit_tau: float = 1.0,
|
| 39 |
+
deferred_start_epoch: int = 0,
|
| 40 |
+
alpha_max: float = 10.0,
|
| 41 |
+
) -> None:
|
| 42 |
+
super().__init__()
|
| 43 |
+
counts = class_counts.float().clamp_min(1.0)
|
| 44 |
+
margins = 1.0 / torch.sqrt(torch.sqrt(counts))
|
| 45 |
+
margins = margins * (max_margin / margins.max().clamp_min(1e-12))
|
| 46 |
+
priors = counts / counts.sum()
|
| 47 |
+
alpha = effective_number_alpha(counts, beta)
|
| 48 |
+
alpha = alpha.clamp(max=alpha_max)
|
| 49 |
+
alpha = alpha * (counts.numel() / alpha.sum().clamp_min(1e-12))
|
| 50 |
+
|
| 51 |
+
self.register_buffer("margins", margins)
|
| 52 |
+
self.register_buffer("log_priors", priors.log())
|
| 53 |
+
self.register_buffer("alpha", alpha)
|
| 54 |
+
self.logit_tau = logit_tau
|
| 55 |
+
self.deferred_start_epoch = deferred_start_epoch
|
| 56 |
+
self.current_epoch = 0
|
| 57 |
+
|
| 58 |
+
def set_epoch(self, epoch: int) -> None:
|
| 59 |
+
self.current_epoch = epoch
|
| 60 |
+
|
| 61 |
+
def forward(self, logits: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
|
| 62 |
+
adjusted_logits = logits.clone()
|
| 63 |
+
rows = torch.arange(labels.size(0), device=labels.device)
|
| 64 |
+
adjusted_logits[rows, labels] = adjusted_logits[rows, labels] - self.margins[labels]
|
| 65 |
+
adjusted_logits = adjusted_logits + self.logit_tau * self.log_priors
|
| 66 |
+
loss = F.cross_entropy(adjusted_logits, labels, reduction="none")
|
| 67 |
+
if self.current_epoch >= self.deferred_start_epoch:
|
| 68 |
+
loss = loss * self.alpha[labels]
|
| 69 |
+
return loss.mean()
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def effective_number_alpha(counts: torch.Tensor, beta: float) -> torch.Tensor:
|
| 73 |
+
if beta <= 0.0:
|
| 74 |
+
return torch.ones_like(counts)
|
| 75 |
+
if beta >= 1.0:
|
| 76 |
+
raise ValueError("--lt-beta must be less than 1.0")
|
| 77 |
+
beta_tensor = torch.tensor(beta, dtype=counts.dtype, device=counts.device)
|
| 78 |
+
effective_num = 1.0 - torch.pow(beta_tensor, counts)
|
| 79 |
+
alpha = (1.0 - beta_tensor) / effective_num.clamp_min(1e-12)
|
| 80 |
+
return alpha
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def class_count_tensor(train_df: pd.DataFrame, label_to_idx: dict[str, int], device: torch.device) -> torch.Tensor:
|
| 84 |
+
y = np.array([label_to_idx[label] for label in train_df["label"]])
|
| 85 |
+
counts = np.bincount(y, minlength=len(label_to_idx))
|
| 86 |
+
if np.any(counts == 0):
|
| 87 |
+
missing = [label for label, idx in label_to_idx.items() if counts[idx] == 0]
|
| 88 |
+
raise ValueError(f"Cannot build loss because train split has zero samples for classes: {missing}")
|
| 89 |
+
return torch.tensor(counts, dtype=torch.float32, device=device)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def build_loss(train_df: pd.DataFrame, label_to_idx: dict[str, int], args: argparse.Namespace, device: torch.device) -> nn.Module:
|
| 93 |
+
if args.loss == "milk_lt":
|
| 94 |
+
counts = class_count_tensor(train_df, label_to_idx, device)
|
| 95 |
+
return MILKLongTailLoss(
|
| 96 |
+
class_counts=counts,
|
| 97 |
+
beta=args.lt_beta,
|
| 98 |
+
max_margin=args.lt_max_margin,
|
| 99 |
+
logit_tau=args.lt_logit_tau,
|
| 100 |
+
deferred_start_epoch=args.lt_draw_start_epoch,
|
| 101 |
+
alpha_max=args.lt_alpha_max,
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
weight = None
|
| 105 |
+
if args.class_weight:
|
| 106 |
+
y = np.array([label_to_idx[label] for label in train_df["label"]])
|
| 107 |
+
weights = compute_class_weight(class_weight="balanced", classes=np.arange(len(label_to_idx)), y=y)
|
| 108 |
+
weight = torch.tensor(weights, dtype=torch.float32, device=device)
|
| 109 |
+
if args.loss == "focal":
|
| 110 |
+
return FocalLoss(weight=weight, gamma=args.focal_gamma)
|
| 111 |
+
return nn.CrossEntropyLoss(weight=weight)
|
milk10k_effb2_metadata/metrics.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Prediction and classification metric helpers."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import torch
|
| 11 |
+
from sklearn.metrics import (
|
| 12 |
+
accuracy_score,
|
| 13 |
+
balanced_accuracy_score,
|
| 14 |
+
classification_report,
|
| 15 |
+
confusion_matrix,
|
| 16 |
+
precision_recall_fscore_support,
|
| 17 |
+
roc_auc_score,
|
| 18 |
+
)
|
| 19 |
+
from sklearn.preprocessing import label_binarize
|
| 20 |
+
from torch.utils.data import DataLoader
|
| 21 |
+
from tqdm.auto import tqdm
|
| 22 |
+
|
| 23 |
+
from milk10k_effb2_metadata.models import DualEffB2MetadataClassifier
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def move_batch(batch: dict[str, torch.Tensor], device: torch.device) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 27 |
+
clinical = batch["clinical"].to(device, non_blocking=True)
|
| 28 |
+
dermoscopic = batch["dermoscopic"].to(device, non_blocking=True)
|
| 29 |
+
metadata = batch["metadata"].to(device, non_blocking=True)
|
| 30 |
+
labels = batch["label"].to(device, non_blocking=True)
|
| 31 |
+
return clinical, dermoscopic, metadata, labels
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@torch.no_grad()
|
| 35 |
+
def predict(model: DualEffB2MetadataClassifier, loader: DataLoader, device: torch.device) -> tuple[np.ndarray, np.ndarray]:
|
| 36 |
+
model.eval()
|
| 37 |
+
labels_all = []
|
| 38 |
+
probs_all = []
|
| 39 |
+
for batch in tqdm(loader, leave=False):
|
| 40 |
+
clinical, dermoscopic, metadata, labels = move_batch(batch, device)
|
| 41 |
+
logits = model(clinical, dermoscopic, metadata)
|
| 42 |
+
labels_all.append(labels.cpu().numpy())
|
| 43 |
+
probs_all.append(torch.softmax(logits, dim=1).cpu().numpy())
|
| 44 |
+
return np.concatenate(labels_all), np.concatenate(probs_all)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def compute_metrics(y_true: np.ndarray, y_prob: np.ndarray, class_names: list[str]) -> tuple[dict[str, Any], pd.DataFrame, np.ndarray]:
|
| 48 |
+
y_pred = y_prob.argmax(axis=1)
|
| 49 |
+
labels = list(range(len(class_names)))
|
| 50 |
+
y_true_bin = label_binarize(y_true, classes=labels)
|
| 51 |
+
cm = confusion_matrix(y_true, y_pred, labels=labels)
|
| 52 |
+
|
| 53 |
+
precision_macro, recall_macro, f1_macro, _ = precision_recall_fscore_support(
|
| 54 |
+
y_true, y_pred, labels=labels, average="macro", zero_division=0
|
| 55 |
+
)
|
| 56 |
+
precision_weighted, recall_weighted, f1_weighted, _ = precision_recall_fscore_support(
|
| 57 |
+
y_true, y_pred, labels=labels, average="weighted", zero_division=0
|
| 58 |
+
)
|
| 59 |
+
precision_per_class, recall_per_class, f1_per_class, support_per_class = precision_recall_fscore_support(
|
| 60 |
+
y_true, y_pred, labels=labels, average=None, zero_division=0
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
total = cm.sum()
|
| 64 |
+
per_class_rows = []
|
| 65 |
+
for idx, class_name in enumerate(class_names):
|
| 66 |
+
tp = int(cm[idx, idx])
|
| 67 |
+
fn = int(cm[idx, :].sum() - tp)
|
| 68 |
+
fp = int(cm[:, idx].sum() - tp)
|
| 69 |
+
tn = int(total - tp - fn - fp)
|
| 70 |
+
try:
|
| 71 |
+
auc_ovr = float(roc_auc_score(y_true_bin[:, idx], y_prob[:, idx]))
|
| 72 |
+
except ValueError:
|
| 73 |
+
auc_ovr = None
|
| 74 |
+
per_class_rows.append(
|
| 75 |
+
{
|
| 76 |
+
"class": class_name,
|
| 77 |
+
"support": int(support_per_class[idx]),
|
| 78 |
+
"precision": float(precision_per_class[idx]),
|
| 79 |
+
"recall_sensitivity": float(recall_per_class[idx]),
|
| 80 |
+
"specificity": tn / (tn + fp) if (tn + fp) else 0.0,
|
| 81 |
+
"f1": float(f1_per_class[idx]),
|
| 82 |
+
"auc_ovr": auc_ovr,
|
| 83 |
+
}
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
metrics = {
|
| 87 |
+
"accuracy": float(accuracy_score(y_true, y_pred)),
|
| 88 |
+
"balanced_accuracy": float(balanced_accuracy_score(y_true, y_pred)),
|
| 89 |
+
"top2_accuracy": float(np.mean((np.argsort(y_prob, axis=1)[:, -min(2, len(class_names)) :] == y_true[:, None]).any(axis=1))),
|
| 90 |
+
"top3_accuracy": float(np.mean((np.argsort(y_prob, axis=1)[:, -min(3, len(class_names)) :] == y_true[:, None]).any(axis=1))),
|
| 91 |
+
"precision_macro": float(precision_macro),
|
| 92 |
+
"recall_macro": float(recall_macro),
|
| 93 |
+
"f1_macro": float(f1_macro),
|
| 94 |
+
"precision_weighted": float(precision_weighted),
|
| 95 |
+
"recall_weighted": float(recall_weighted),
|
| 96 |
+
"f1_weighted": float(f1_weighted),
|
| 97 |
+
"roc_auc_macro_ovr": safe_roc_auc(y_true_bin, y_prob, "macro"),
|
| 98 |
+
"roc_auc_weighted_ovr": safe_roc_auc(y_true_bin, y_prob, "weighted"),
|
| 99 |
+
"roc_auc_micro_ovr": safe_roc_auc(y_true_bin, y_prob, "micro"),
|
| 100 |
+
"specificity_macro": float(np.mean([row["specificity"] for row in per_class_rows])),
|
| 101 |
+
"per_class": per_class_rows,
|
| 102 |
+
"classification_report": classification_report(
|
| 103 |
+
y_true,
|
| 104 |
+
y_pred,
|
| 105 |
+
labels=labels,
|
| 106 |
+
target_names=class_names,
|
| 107 |
+
zero_division=0,
|
| 108 |
+
output_dict=True,
|
| 109 |
+
),
|
| 110 |
+
"class_names": class_names,
|
| 111 |
+
}
|
| 112 |
+
return metrics, pd.DataFrame(per_class_rows), cm
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def safe_roc_auc(y_true_bin: np.ndarray, y_prob: np.ndarray, average: str | None) -> float | None:
|
| 116 |
+
try:
|
| 117 |
+
return float(roc_auc_score(y_true_bin, y_prob, average=average, multi_class="ovr"))
|
| 118 |
+
except ValueError:
|
| 119 |
+
return None
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def save_predictions(
|
| 123 |
+
val_df: pd.DataFrame,
|
| 124 |
+
y_true: np.ndarray,
|
| 125 |
+
y_prob: np.ndarray,
|
| 126 |
+
class_names: list[str],
|
| 127 |
+
output_dir: Path,
|
| 128 |
+
) -> None:
|
| 129 |
+
y_pred = y_prob.argmax(axis=1)
|
| 130 |
+
prediction_df = pd.DataFrame(
|
| 131 |
+
{
|
| 132 |
+
"lesion_id": val_df["lesion_id"].tolist(),
|
| 133 |
+
"clinical_path": val_df["clinical_path"].tolist(),
|
| 134 |
+
"dermoscopic_path": val_df["dermoscopic_path"].tolist(),
|
| 135 |
+
"y_true": y_true,
|
| 136 |
+
"y_pred": y_pred,
|
| 137 |
+
"label_true": [class_names[idx] for idx in y_true],
|
| 138 |
+
"label_pred": [class_names[idx] for idx in y_pred],
|
| 139 |
+
"confidence": y_prob.max(axis=1),
|
| 140 |
+
}
|
| 141 |
+
)
|
| 142 |
+
probability_df = pd.DataFrame(y_prob, columns=[f"prob_{name}" for name in class_names])
|
| 143 |
+
pd.concat([prediction_df, probability_df], axis=1).to_csv(output_dir / "val_predictions.csv", index=False)
|
| 144 |
+
|
milk10k_effb2_metadata/models.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Model components for the dual EfficientNet-B2 metadata classifier."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import timm
|
| 6 |
+
import torch
|
| 7 |
+
from torch import nn
|
| 8 |
+
from torchvision.models import EfficientNet_B2_Weights, efficientnet_b2
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class ProjectionHead(nn.Module):
|
| 12 |
+
def __init__(self, in_dim: int, out_dim: int, dropout: float) -> None:
|
| 13 |
+
super().__init__()
|
| 14 |
+
self.net = nn.Sequential(
|
| 15 |
+
nn.LayerNorm(in_dim),
|
| 16 |
+
nn.Dropout(dropout),
|
| 17 |
+
nn.Linear(in_dim, out_dim),
|
| 18 |
+
nn.GELU(),
|
| 19 |
+
nn.LayerNorm(out_dim),
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 23 |
+
return self.net(x)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class MetadataHead(nn.Module):
|
| 27 |
+
def __init__(self, in_dim: int, out_dim: int, dropout: float) -> None:
|
| 28 |
+
super().__init__()
|
| 29 |
+
hidden_dim = max(out_dim * 2, 32)
|
| 30 |
+
self.net = nn.Sequential(
|
| 31 |
+
nn.LayerNorm(in_dim),
|
| 32 |
+
nn.Linear(in_dim, hidden_dim),
|
| 33 |
+
nn.GELU(),
|
| 34 |
+
nn.Dropout(dropout),
|
| 35 |
+
nn.Linear(hidden_dim, out_dim),
|
| 36 |
+
nn.GELU(),
|
| 37 |
+
nn.LayerNorm(out_dim),
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
def forward(self, metadata: torch.Tensor) -> torch.Tensor:
|
| 41 |
+
return self.net(metadata)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class DualEffB2MetadataClassifier(nn.Module):
|
| 45 |
+
def __init__(
|
| 46 |
+
self,
|
| 47 |
+
num_classes: int,
|
| 48 |
+
metadata_input_dim: int,
|
| 49 |
+
branch_dim: int,
|
| 50 |
+
metadata_dim: int,
|
| 51 |
+
classifier_hidden_dim: int,
|
| 52 |
+
dropout: float,
|
| 53 |
+
imagenet_pretrained: bool,
|
| 54 |
+
clinical_backbone_backend: str,
|
| 55 |
+
dermoscopic_backbone_backend: str,
|
| 56 |
+
) -> None:
|
| 57 |
+
super().__init__()
|
| 58 |
+
self.clinical_backbone_backend = clinical_backbone_backend
|
| 59 |
+
self.dermoscopic_backbone_backend = dermoscopic_backbone_backend
|
| 60 |
+
self.clinical_encoder, clinical_feature_dim = build_effb2_feature_encoder(
|
| 61 |
+
clinical_backbone_backend,
|
| 62 |
+
imagenet_pretrained,
|
| 63 |
+
)
|
| 64 |
+
self.dermoscopic_encoder, dermoscopic_feature_dim = build_effb2_feature_encoder(
|
| 65 |
+
dermoscopic_backbone_backend,
|
| 66 |
+
imagenet_pretrained,
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
self.clinical_head = ProjectionHead(clinical_feature_dim, branch_dim, dropout)
|
| 70 |
+
self.dermoscopic_head = ProjectionHead(dermoscopic_feature_dim, branch_dim, dropout)
|
| 71 |
+
self.metadata_head = MetadataHead(metadata_input_dim, metadata_dim, dropout)
|
| 72 |
+
fused_dim = branch_dim * 2 + metadata_dim
|
| 73 |
+
self.classifier = nn.Sequential(
|
| 74 |
+
nn.LayerNorm(fused_dim),
|
| 75 |
+
nn.Dropout(dropout),
|
| 76 |
+
nn.Linear(fused_dim, classifier_hidden_dim),
|
| 77 |
+
nn.GELU(),
|
| 78 |
+
nn.Dropout(dropout),
|
| 79 |
+
nn.Linear(classifier_hidden_dim, num_classes),
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
def forward(
|
| 83 |
+
self,
|
| 84 |
+
clinical: torch.Tensor,
|
| 85 |
+
dermoscopic: torch.Tensor,
|
| 86 |
+
metadata: torch.Tensor,
|
| 87 |
+
) -> torch.Tensor:
|
| 88 |
+
clinical_features = self.clinical_encoder(clinical)
|
| 89 |
+
dermoscopic_features = self.dermoscopic_encoder(dermoscopic)
|
| 90 |
+
clinical_repr = self.clinical_head(clinical_features)
|
| 91 |
+
dermoscopic_repr = self.dermoscopic_head(dermoscopic_features)
|
| 92 |
+
metadata_repr = self.metadata_head(metadata)
|
| 93 |
+
fused = torch.cat([clinical_repr, dermoscopic_repr, metadata_repr], dim=1)
|
| 94 |
+
return self.classifier(fused)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def build_effb2_feature_encoder(backbone_backend: str, imagenet_pretrained: bool) -> tuple[nn.Module, int]:
|
| 98 |
+
if backbone_backend == "timm":
|
| 99 |
+
model = timm.create_model(
|
| 100 |
+
"efficientnet_b2",
|
| 101 |
+
pretrained=imagenet_pretrained,
|
| 102 |
+
num_classes=0,
|
| 103 |
+
global_pool="avg",
|
| 104 |
+
)
|
| 105 |
+
return model, int(model.num_features)
|
| 106 |
+
|
| 107 |
+
if backbone_backend == "torchvision":
|
| 108 |
+
weights = EfficientNet_B2_Weights.IMAGENET1K_V1 if imagenet_pretrained else None
|
| 109 |
+
model = efficientnet_b2(weights=weights)
|
| 110 |
+
feature_dim = int(model.classifier[1].in_features)
|
| 111 |
+
model.classifier = nn.Identity()
|
| 112 |
+
return model, feature_dim
|
| 113 |
+
|
| 114 |
+
raise ValueError(f"Unsupported backbone backend: {backbone_backend}")
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def set_encoder_trainable(model: DualEffB2MetadataClassifier, trainable: bool) -> None:
|
| 118 |
+
for param in model.clinical_encoder.parameters():
|
| 119 |
+
param.requires_grad = trainable
|
| 120 |
+
for param in model.dermoscopic_encoder.parameters():
|
| 121 |
+
param.requires_grad = trainable
|
| 122 |
+
|
milk10k_effb2_metadata/training.py
ADDED
|
@@ -0,0 +1,502 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Training orchestration for the EffB2 dual metadata classifier."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 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 balanced_accuracy_score, precision_recall_fscore_support
|
| 14 |
+
from torch import nn
|
| 15 |
+
from torch.amp import GradScaler, autocast
|
| 16 |
+
from torch.utils.data import DataLoader
|
| 17 |
+
from tqdm.auto import tqdm
|
| 18 |
+
|
| 19 |
+
from datasets import resolve_data_dir, set_seed
|
| 20 |
+
from milk10k_effb2_metadata.checkpoints import load_encoder_checkpoint, resolve_backbone_backends
|
| 21 |
+
from milk10k_effb2_metadata.data import (
|
| 22 |
+
fit_metadata_spec,
|
| 23 |
+
kfold_splits,
|
| 24 |
+
lesion_split,
|
| 25 |
+
load_paired_dataframe,
|
| 26 |
+
make_loaders,
|
| 27 |
+
metadata_vector,
|
| 28 |
+
)
|
| 29 |
+
from milk10k_effb2_metadata.losses import build_loss
|
| 30 |
+
from milk10k_effb2_metadata.metrics import compute_metrics, move_batch, predict, save_predictions
|
| 31 |
+
from milk10k_effb2_metadata.models import DualEffB2MetadataClassifier, set_encoder_trainable
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def build_optimizer(model: DualEffB2MetadataClassifier, args: argparse.Namespace, encoders_trainable: bool) -> torch.optim.Optimizer:
|
| 35 |
+
head_params = []
|
| 36 |
+
encoder_params = []
|
| 37 |
+
for name, param in model.named_parameters():
|
| 38 |
+
if not param.requires_grad:
|
| 39 |
+
continue
|
| 40 |
+
if name.startswith(("clinical_encoder.", "dermoscopic_encoder.")):
|
| 41 |
+
encoder_params.append(param)
|
| 42 |
+
else:
|
| 43 |
+
head_params.append(param)
|
| 44 |
+
|
| 45 |
+
groups = [{"params": head_params, "lr": args.head_lr}]
|
| 46 |
+
if encoders_trainable and encoder_params:
|
| 47 |
+
groups.append({"params": encoder_params, "lr": args.encoder_lr})
|
| 48 |
+
return torch.optim.AdamW(groups, weight_decay=args.weight_decay)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def run_epoch(
|
| 52 |
+
model: DualEffB2MetadataClassifier,
|
| 53 |
+
loader: DataLoader,
|
| 54 |
+
criterion: nn.Module,
|
| 55 |
+
device: torch.device,
|
| 56 |
+
optimizer: torch.optim.Optimizer | None = None,
|
| 57 |
+
scaler: GradScaler | None = None,
|
| 58 |
+
use_amp: bool = False,
|
| 59 |
+
) -> dict[str, float]:
|
| 60 |
+
training = optimizer is not None
|
| 61 |
+
model.train(training)
|
| 62 |
+
total_loss = 0.0
|
| 63 |
+
correct = 0
|
| 64 |
+
top3_correct = 0
|
| 65 |
+
total = 0
|
| 66 |
+
preds_all = []
|
| 67 |
+
labels_all = []
|
| 68 |
+
|
| 69 |
+
for batch in tqdm(loader, leave=False):
|
| 70 |
+
clinical, dermoscopic, metadata, labels = move_batch(batch, device)
|
| 71 |
+
if training:
|
| 72 |
+
optimizer.zero_grad(set_to_none=True)
|
| 73 |
+
|
| 74 |
+
with torch.set_grad_enabled(training):
|
| 75 |
+
with autocast("cuda", enabled=use_amp):
|
| 76 |
+
logits = model(clinical, dermoscopic, metadata)
|
| 77 |
+
loss = criterion(logits, labels)
|
| 78 |
+
if training:
|
| 79 |
+
if scaler is not None and use_amp:
|
| 80 |
+
scaler.scale(loss).backward()
|
| 81 |
+
scaler.unscale_(optimizer)
|
| 82 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
|
| 83 |
+
scaler.step(optimizer)
|
| 84 |
+
scaler.update()
|
| 85 |
+
else:
|
| 86 |
+
loss.backward()
|
| 87 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
|
| 88 |
+
optimizer.step()
|
| 89 |
+
|
| 90 |
+
batch_size = labels.size(0)
|
| 91 |
+
total_loss += float(loss.detach().item()) * batch_size
|
| 92 |
+
correct += (logits.argmax(dim=1) == labels).sum().item()
|
| 93 |
+
topk = min(3, logits.size(1))
|
| 94 |
+
top3_correct += logits.topk(topk, dim=1).indices.eq(labels[:, None]).any(dim=1).sum().item()
|
| 95 |
+
total += batch_size
|
| 96 |
+
preds_all.append(logits.argmax(dim=1).detach().cpu().numpy())
|
| 97 |
+
labels_all.append(labels.detach().cpu().numpy())
|
| 98 |
+
|
| 99 |
+
y_pred = np.concatenate(preds_all) if preds_all else np.array([])
|
| 100 |
+
y_true = np.concatenate(labels_all) if labels_all else np.array([])
|
| 101 |
+
|
| 102 |
+
return {
|
| 103 |
+
"loss": total_loss / max(total, 1),
|
| 104 |
+
"accuracy": correct / max(total, 1),
|
| 105 |
+
"balanced_accuracy": float(balanced_accuracy_score(y_true, y_pred)) if total else 0.0,
|
| 106 |
+
"f1_macro": float(precision_recall_fscore_support(y_true, y_pred, average="macro", zero_division=0)[2]) if total else 0.0,
|
| 107 |
+
"top3_accuracy": top3_correct / max(total, 1),
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def save_checkpoint(
|
| 112 |
+
path: Path,
|
| 113 |
+
model: DualEffB2MetadataClassifier,
|
| 114 |
+
optimizer: torch.optim.Optimizer,
|
| 115 |
+
epoch: int,
|
| 116 |
+
phase: str,
|
| 117 |
+
best_val_loss: float,
|
| 118 |
+
class_names: list[str],
|
| 119 |
+
label_to_idx: dict[str, int],
|
| 120 |
+
metadata_spec: dict[str, Any],
|
| 121 |
+
args: argparse.Namespace,
|
| 122 |
+
) -> None:
|
| 123 |
+
torch.save(
|
| 124 |
+
{
|
| 125 |
+
"epoch": epoch,
|
| 126 |
+
"phase": phase,
|
| 127 |
+
"model_state": model.state_dict(),
|
| 128 |
+
"optimizer_state": optimizer.state_dict(),
|
| 129 |
+
"best_val_loss": best_val_loss,
|
| 130 |
+
"class_names": class_names,
|
| 131 |
+
"label_to_idx": label_to_idx,
|
| 132 |
+
"metadata_spec": metadata_spec,
|
| 133 |
+
"args": json_safe(vars(args)),
|
| 134 |
+
},
|
| 135 |
+
path,
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def train_phase(
|
| 140 |
+
phase: str,
|
| 141 |
+
num_epochs: int,
|
| 142 |
+
start_epoch: int,
|
| 143 |
+
model: DualEffB2MetadataClassifier,
|
| 144 |
+
train_loader: DataLoader,
|
| 145 |
+
val_loader: DataLoader,
|
| 146 |
+
criterion: nn.Module,
|
| 147 |
+
device: torch.device,
|
| 148 |
+
args: argparse.Namespace,
|
| 149 |
+
class_names: list[str],
|
| 150 |
+
label_to_idx: dict[str, int],
|
| 151 |
+
metadata_spec: dict[str, Any],
|
| 152 |
+
output_dir: Path,
|
| 153 |
+
history: list[dict[str, Any]],
|
| 154 |
+
best_val_loss: float,
|
| 155 |
+
) -> tuple[int, float]:
|
| 156 |
+
if num_epochs <= 0:
|
| 157 |
+
return start_epoch, best_val_loss
|
| 158 |
+
|
| 159 |
+
encoders_trainable = phase == "finetune"
|
| 160 |
+
set_encoder_trainable(model, encoders_trainable)
|
| 161 |
+
optimizer = build_optimizer(model, args, encoders_trainable)
|
| 162 |
+
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode="min", factor=0.2, patience=2)
|
| 163 |
+
scaler = GradScaler("cuda", enabled=args.amp and device.type == "cuda")
|
| 164 |
+
use_amp = args.amp and device.type == "cuda"
|
| 165 |
+
patience_count = 0
|
| 166 |
+
|
| 167 |
+
print(f"\nPhase: {phase}, epochs={num_epochs}, encoders_trainable={encoders_trainable}")
|
| 168 |
+
for local_epoch in range(1, num_epochs + 1):
|
| 169 |
+
epoch = start_epoch + local_epoch - 1
|
| 170 |
+
if hasattr(criterion, "set_epoch"):
|
| 171 |
+
criterion.set_epoch(epoch)
|
| 172 |
+
train_stats = run_epoch(model, train_loader, criterion, device, optimizer, scaler, use_amp)
|
| 173 |
+
val_stats = run_epoch(model, val_loader, criterion, device)
|
| 174 |
+
scheduler.step(val_stats["loss"])
|
| 175 |
+
row = {
|
| 176 |
+
"phase": phase,
|
| 177 |
+
"epoch": epoch,
|
| 178 |
+
**{f"train_{key}": value for key, value in train_stats.items()},
|
| 179 |
+
**{f"val_{key}": value for key, value in val_stats.items()},
|
| 180 |
+
}
|
| 181 |
+
history.append(row)
|
| 182 |
+
pd.DataFrame(history).to_csv(output_dir / "history.csv", index=False)
|
| 183 |
+
print(
|
| 184 |
+
f"{phase} epoch {epoch:03d}: "
|
| 185 |
+
f"train_loss={train_stats['loss']:.4f} val_loss={val_stats['loss']:.4f} "
|
| 186 |
+
f"train_bal_acc={train_stats['balanced_accuracy']:.4f} train_f1={train_stats['f1_macro']:.4f} "
|
| 187 |
+
f"val_acc={val_stats['accuracy']:.4f} val_bal_acc={val_stats['balanced_accuracy']:.4f} "
|
| 188 |
+
f"val_f1={val_stats['f1_macro']:.4f} val_top3={val_stats['top3_accuracy']:.4f}"
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
if val_stats["loss"] < best_val_loss:
|
| 192 |
+
best_val_loss = val_stats["loss"]
|
| 193 |
+
patience_count = 0
|
| 194 |
+
save_checkpoint(
|
| 195 |
+
output_dir / "best.pt",
|
| 196 |
+
model,
|
| 197 |
+
optimizer,
|
| 198 |
+
epoch,
|
| 199 |
+
phase,
|
| 200 |
+
best_val_loss,
|
| 201 |
+
class_names,
|
| 202 |
+
label_to_idx,
|
| 203 |
+
metadata_spec,
|
| 204 |
+
args,
|
| 205 |
+
)
|
| 206 |
+
else:
|
| 207 |
+
patience_count += 1
|
| 208 |
+
if patience_count >= args.patience:
|
| 209 |
+
print(f"Early stopping {phase} at epoch {epoch}")
|
| 210 |
+
break
|
| 211 |
+
|
| 212 |
+
return start_epoch + num_epochs, best_val_loss
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def build_model(
|
| 216 |
+
class_names: list[str],
|
| 217 |
+
metadata_dim: int,
|
| 218 |
+
args: argparse.Namespace,
|
| 219 |
+
device: torch.device,
|
| 220 |
+
clinical_backbone_backend: str,
|
| 221 |
+
dermoscopic_backbone_backend: str,
|
| 222 |
+
) -> DualEffB2MetadataClassifier:
|
| 223 |
+
model = DualEffB2MetadataClassifier(
|
| 224 |
+
num_classes=len(class_names),
|
| 225 |
+
metadata_input_dim=metadata_dim,
|
| 226 |
+
branch_dim=args.branch_dim,
|
| 227 |
+
metadata_dim=args.metadata_dim,
|
| 228 |
+
classifier_hidden_dim=args.classifier_hidden_dim,
|
| 229 |
+
dropout=args.dropout,
|
| 230 |
+
imagenet_pretrained=args.imagenet_pretrained,
|
| 231 |
+
clinical_backbone_backend=clinical_backbone_backend,
|
| 232 |
+
dermoscopic_backbone_backend=dermoscopic_backbone_backend,
|
| 233 |
+
).to(device)
|
| 234 |
+
load_encoder_checkpoint(args.clinical_checkpoint, model.clinical_encoder, "clinical", device)
|
| 235 |
+
load_encoder_checkpoint(args.dermoscopic_checkpoint, model.dermoscopic_encoder, "dermoscopic", device)
|
| 236 |
+
return model
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def save_run_config(
|
| 240 |
+
output_dir: Path,
|
| 241 |
+
args: argparse.Namespace,
|
| 242 |
+
class_names: list[str],
|
| 243 |
+
metadata_spec: dict[str, Any],
|
| 244 |
+
train_df: pd.DataFrame,
|
| 245 |
+
val_df: pd.DataFrame,
|
| 246 |
+
clinical_backbone_backend: str,
|
| 247 |
+
dermoscopic_backbone_backend: str,
|
| 248 |
+
fold: int | None = None,
|
| 249 |
+
) -> None:
|
| 250 |
+
payload = {
|
| 251 |
+
"args": json_safe(vars(args)),
|
| 252 |
+
"class_names": class_names,
|
| 253 |
+
"metadata_spec": json_safe(metadata_spec),
|
| 254 |
+
"train_size": len(train_df),
|
| 255 |
+
"val_size": len(val_df),
|
| 256 |
+
"fold": fold,
|
| 257 |
+
"fusion": "concat(clinical_head, dermoscopic_head, metadata_head)",
|
| 258 |
+
"clinical_backbone": f"{clinical_backbone_backend} efficientnet_b2",
|
| 259 |
+
"dermoscopic_backbone": f"{dermoscopic_backbone_backend} efficientnet_b2",
|
| 260 |
+
}
|
| 261 |
+
with open(output_dir / "run_config.json", "w", encoding="utf-8") as f:
|
| 262 |
+
json.dump(payload, f, indent=2)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def run_training_split(
|
| 266 |
+
df: pd.DataFrame,
|
| 267 |
+
train_df: pd.DataFrame,
|
| 268 |
+
val_df: pd.DataFrame,
|
| 269 |
+
class_names: list[str],
|
| 270 |
+
label_to_idx: dict[str, int],
|
| 271 |
+
args: argparse.Namespace,
|
| 272 |
+
device: torch.device,
|
| 273 |
+
clinical_backbone_backend: str,
|
| 274 |
+
dermoscopic_backbone_backend: str,
|
| 275 |
+
output_dir: Path,
|
| 276 |
+
fold: int | None = None,
|
| 277 |
+
) -> dict[str, Any]:
|
| 278 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 279 |
+
split_dir = output_dir / "splits"
|
| 280 |
+
split_dir.mkdir(exist_ok=True)
|
| 281 |
+
train_df.to_csv(split_dir / "train.csv", index=False)
|
| 282 |
+
val_df.to_csv(split_dir / "val.csv", index=False)
|
| 283 |
+
|
| 284 |
+
metadata_spec = fit_metadata_spec(train_df)
|
| 285 |
+
metadata_dim = len(metadata_vector(train_df.iloc[0], metadata_spec))
|
| 286 |
+
save_run_config(
|
| 287 |
+
output_dir,
|
| 288 |
+
args,
|
| 289 |
+
class_names,
|
| 290 |
+
metadata_spec,
|
| 291 |
+
train_df,
|
| 292 |
+
val_df,
|
| 293 |
+
clinical_backbone_backend,
|
| 294 |
+
dermoscopic_backbone_backend,
|
| 295 |
+
fold,
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
model = build_model(
|
| 299 |
+
class_names,
|
| 300 |
+
metadata_dim,
|
| 301 |
+
args,
|
| 302 |
+
device,
|
| 303 |
+
clinical_backbone_backend,
|
| 304 |
+
dermoscopic_backbone_backend,
|
| 305 |
+
)
|
| 306 |
+
train_loader, val_loader = make_loaders(train_df, val_df, label_to_idx, metadata_spec, args)
|
| 307 |
+
criterion = build_loss(train_df, label_to_idx, args, device)
|
| 308 |
+
|
| 309 |
+
print(f"Output dir: {output_dir}")
|
| 310 |
+
print(f"Device: {device}")
|
| 311 |
+
print(f"Classes: {class_names}")
|
| 312 |
+
print(f"Paired lesions: train={len(train_df)}, val={len(val_df)}, total={len(df)}")
|
| 313 |
+
print(f"Metadata input dim: {metadata_dim}")
|
| 314 |
+
print(f"MONET columns: {len(metadata_spec.get('monet_columns', []))}")
|
| 315 |
+
print(f"Loss: {args.loss}, class_weight={args.class_weight}, weighted_sampler={args.weighted_sampler}")
|
| 316 |
+
if args.loss == "milk_lt" and args.class_weight:
|
| 317 |
+
print("Note: --class-weight is ignored for --loss milk_lt because milk_lt uses effective-number alpha.")
|
| 318 |
+
|
| 319 |
+
history: list[dict[str, Any]] = []
|
| 320 |
+
epoch, best_val_loss = train_phase(
|
| 321 |
+
"freeze",
|
| 322 |
+
args.freeze_epochs,
|
| 323 |
+
1,
|
| 324 |
+
model,
|
| 325 |
+
train_loader,
|
| 326 |
+
val_loader,
|
| 327 |
+
criterion,
|
| 328 |
+
device,
|
| 329 |
+
args,
|
| 330 |
+
class_names,
|
| 331 |
+
label_to_idx,
|
| 332 |
+
metadata_spec,
|
| 333 |
+
output_dir,
|
| 334 |
+
history,
|
| 335 |
+
float("inf"),
|
| 336 |
+
)
|
| 337 |
+
epoch, best_val_loss = train_phase(
|
| 338 |
+
"finetune",
|
| 339 |
+
args.finetune_epochs,
|
| 340 |
+
epoch,
|
| 341 |
+
model,
|
| 342 |
+
train_loader,
|
| 343 |
+
val_loader,
|
| 344 |
+
criterion,
|
| 345 |
+
device,
|
| 346 |
+
args,
|
| 347 |
+
class_names,
|
| 348 |
+
label_to_idx,
|
| 349 |
+
metadata_spec,
|
| 350 |
+
output_dir,
|
| 351 |
+
history,
|
| 352 |
+
best_val_loss,
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
best_path = output_dir / "best.pt"
|
| 356 |
+
if best_path.exists():
|
| 357 |
+
checkpoint = torch.load(best_path, map_location=device, weights_only=False)
|
| 358 |
+
model.load_state_dict(checkpoint["model_state"])
|
| 359 |
+
y_true, y_prob = predict(model, val_loader, device)
|
| 360 |
+
metrics, per_class_df, cm = compute_metrics(y_true, y_prob, class_names)
|
| 361 |
+
metrics = {"best_val_loss": float(best_val_loss), **metrics}
|
| 362 |
+
with open(output_dir / "metrics.json", "w", encoding="utf-8") as f:
|
| 363 |
+
json.dump(json_safe(metrics), f, indent=2)
|
| 364 |
+
pd.DataFrame(cm, index=class_names, columns=class_names).to_csv(output_dir / "confusion_matrix.csv")
|
| 365 |
+
per_class_df.to_csv(output_dir / "per_class_metrics.csv", index=False)
|
| 366 |
+
save_predictions(val_df, y_true, y_prob, class_names, output_dir)
|
| 367 |
+
print(
|
| 368 |
+
f"Done: best_val_loss={best_val_loss:.4f}, "
|
| 369 |
+
f"val_acc={metrics['accuracy']:.4f}, balanced_acc={metrics['balanced_accuracy']:.4f}, "
|
| 370 |
+
f"f1_macro={metrics['f1_macro']:.4f}, top3={metrics['top3_accuracy']:.4f}, "
|
| 371 |
+
f"auc_macro={metrics['roc_auc_macro_ovr']}"
|
| 372 |
+
)
|
| 373 |
+
return metrics
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def train_single_run(
|
| 377 |
+
df: pd.DataFrame,
|
| 378 |
+
class_names: list[str],
|
| 379 |
+
label_to_idx: dict[str, int],
|
| 380 |
+
args: argparse.Namespace,
|
| 381 |
+
device: torch.device,
|
| 382 |
+
clinical_backbone_backend: str,
|
| 383 |
+
dermoscopic_backbone_backend: str,
|
| 384 |
+
) -> dict[str, Any]:
|
| 385 |
+
train_df, val_df = lesion_split(df, args.val_size, args.seed)
|
| 386 |
+
return run_training_split(
|
| 387 |
+
df,
|
| 388 |
+
train_df,
|
| 389 |
+
val_df,
|
| 390 |
+
class_names,
|
| 391 |
+
label_to_idx,
|
| 392 |
+
args,
|
| 393 |
+
device,
|
| 394 |
+
clinical_backbone_backend,
|
| 395 |
+
dermoscopic_backbone_backend,
|
| 396 |
+
args.output_dir,
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def train_kfold(
|
| 401 |
+
df: pd.DataFrame,
|
| 402 |
+
class_names: list[str],
|
| 403 |
+
label_to_idx: dict[str, int],
|
| 404 |
+
args: argparse.Namespace,
|
| 405 |
+
device: torch.device,
|
| 406 |
+
clinical_backbone_backend: str,
|
| 407 |
+
dermoscopic_backbone_backend: str,
|
| 408 |
+
) -> list[dict[str, Any]]:
|
| 409 |
+
fold_metrics = []
|
| 410 |
+
for fold_idx, (train_df, val_df) in enumerate(kfold_splits(df, args.k_folds, args.seed)):
|
| 411 |
+
print(f"\nK-fold {fold_idx + 1}/{args.k_folds}")
|
| 412 |
+
metrics = run_training_split(
|
| 413 |
+
df,
|
| 414 |
+
train_df,
|
| 415 |
+
val_df,
|
| 416 |
+
class_names,
|
| 417 |
+
label_to_idx,
|
| 418 |
+
args,
|
| 419 |
+
device,
|
| 420 |
+
clinical_backbone_backend,
|
| 421 |
+
dermoscopic_backbone_backend,
|
| 422 |
+
args.output_dir / f"fold_{fold_idx:02d}",
|
| 423 |
+
fold_idx,
|
| 424 |
+
)
|
| 425 |
+
fold_metrics.append({"fold": fold_idx, **metrics})
|
| 426 |
+
save_kfold_summary(fold_metrics, args.output_dir)
|
| 427 |
+
return fold_metrics
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def save_kfold_summary(fold_metrics: list[dict[str, Any]], output_dir: Path) -> None:
|
| 431 |
+
summary_keys = [
|
| 432 |
+
"best_val_loss",
|
| 433 |
+
"accuracy",
|
| 434 |
+
"balanced_accuracy",
|
| 435 |
+
"f1_macro",
|
| 436 |
+
"roc_auc_macro_ovr",
|
| 437 |
+
"top3_accuracy",
|
| 438 |
+
]
|
| 439 |
+
rows = []
|
| 440 |
+
for metrics in fold_metrics:
|
| 441 |
+
rows.append({key: metrics.get(key) for key in ["fold", *summary_keys]})
|
| 442 |
+
summary_df = pd.DataFrame(rows)
|
| 443 |
+
summary_df.to_csv(output_dir / "kfold_summary.csv", index=False)
|
| 444 |
+
|
| 445 |
+
aggregate: dict[str, Any] = {"folds": json_safe(rows), "mean": {}, "std": {}}
|
| 446 |
+
for key in summary_keys:
|
| 447 |
+
values = pd.to_numeric(summary_df[key], errors="coerce").dropna()
|
| 448 |
+
aggregate["mean"][key] = None if values.empty else float(values.mean())
|
| 449 |
+
aggregate["std"][key] = None if values.empty else float(values.std(ddof=0))
|
| 450 |
+
with open(output_dir / "kfold_summary.json", "w", encoding="utf-8") as f:
|
| 451 |
+
json.dump(aggregate, f, indent=2)
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
def json_safe(value):
|
| 455 |
+
if isinstance(value, Path):
|
| 456 |
+
return str(value)
|
| 457 |
+
if isinstance(value, dict):
|
| 458 |
+
return {key: json_safe(item) for key, item in value.items()}
|
| 459 |
+
if isinstance(value, (list, tuple)):
|
| 460 |
+
return [json_safe(item) for item in value]
|
| 461 |
+
if isinstance(value, np.ndarray):
|
| 462 |
+
return value.tolist()
|
| 463 |
+
if isinstance(value, np.generic):
|
| 464 |
+
return value.item()
|
| 465 |
+
return value
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def run(args: argparse.Namespace) -> None:
|
| 469 |
+
if args.k_folds < 1:
|
| 470 |
+
raise ValueError("--k-folds must be at least 1.")
|
| 471 |
+
|
| 472 |
+
set_seed(args.seed)
|
| 473 |
+
data_dir = resolve_data_dir(args.data_dir)
|
| 474 |
+
args.output_dir.mkdir(parents=True, exist_ok=True)
|
| 475 |
+
|
| 476 |
+
df = load_paired_dataframe(data_dir)
|
| 477 |
+
class_names = sorted(df["label"].unique())
|
| 478 |
+
label_to_idx = {label: idx for idx, label in enumerate(class_names)}
|
| 479 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 480 |
+
clinical_backbone_backend, dermoscopic_backbone_backend = resolve_backbone_backends(args, device)
|
| 481 |
+
|
| 482 |
+
print(f"Data dir: {data_dir}")
|
| 483 |
+
if args.k_folds == 1:
|
| 484 |
+
train_single_run(
|
| 485 |
+
df,
|
| 486 |
+
class_names,
|
| 487 |
+
label_to_idx,
|
| 488 |
+
args,
|
| 489 |
+
device,
|
| 490 |
+
clinical_backbone_backend,
|
| 491 |
+
dermoscopic_backbone_backend,
|
| 492 |
+
)
|
| 493 |
+
else:
|
| 494 |
+
train_kfold(
|
| 495 |
+
df,
|
| 496 |
+
class_names,
|
| 497 |
+
label_to_idx,
|
| 498 |
+
args,
|
| 499 |
+
device,
|
| 500 |
+
clinical_backbone_backend,
|
| 501 |
+
dermoscopic_backbone_backend,
|
| 502 |
+
)
|