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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
MILK10k dataset utilities shared by training scripts.
|
| 4 |
+
|
| 5 |
+
Keep dataframe construction and torch Dataset classes here; training scripts
|
| 6 |
+
should build transforms/loaders and own model/training logic.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
import random
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
import pandas as pd
|
| 17 |
+
import torch
|
| 18 |
+
from PIL import Image, ImageFile
|
| 19 |
+
from sklearn.model_selection import train_test_split
|
| 20 |
+
from torch.utils.data import Dataset
|
| 21 |
+
|
| 22 |
+
ImageFile.LOAD_TRUNCATED_IMAGES = True
|
| 23 |
+
|
| 24 |
+
REQUIRED_DATA_FILES = (
|
| 25 |
+
"MILK10k_Training_GroundTruth.csv",
|
| 26 |
+
"MILK10k_Training_Metadata.csv",
|
| 27 |
+
"MILK10k_Training_Input",
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
LABEL_COLUMNS = [
|
| 31 |
+
"AKIEC",
|
| 32 |
+
"BCC",
|
| 33 |
+
"BEN_OTH",
|
| 34 |
+
"BKL",
|
| 35 |
+
"DF",
|
| 36 |
+
"INF",
|
| 37 |
+
"MAL_OTH",
|
| 38 |
+
"MEL",
|
| 39 |
+
"NV",
|
| 40 |
+
"SCCKA",
|
| 41 |
+
"VASC",
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class Milk10kDataset(Dataset):
|
| 46 |
+
def __init__(self, df: pd.DataFrame, label_to_idx: dict[str, int], transform=None) -> None:
|
| 47 |
+
self.paths = df["path"].tolist()
|
| 48 |
+
self.labels = [label_to_idx[label] for label in df["label"].tolist()]
|
| 49 |
+
self.transform = transform
|
| 50 |
+
|
| 51 |
+
def __len__(self) -> int:
|
| 52 |
+
return len(self.paths)
|
| 53 |
+
|
| 54 |
+
def __getitem__(self, idx: int) -> tuple[torch.Tensor, int]:
|
| 55 |
+
with Image.open(self.paths[idx]) as img:
|
| 56 |
+
img = img.convert("RGB")
|
| 57 |
+
if self.transform is not None:
|
| 58 |
+
img = self.transform(img)
|
| 59 |
+
return img, self.labels[idx]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class PairedMilk10kDataset(Dataset):
|
| 63 |
+
def __init__(self, df: pd.DataFrame, label_to_idx: dict[str, int], transform=None) -> None:
|
| 64 |
+
self.clinical_paths = df["clinical_path"].tolist()
|
| 65 |
+
self.dermoscopic_paths = df["dermoscopic_path"].tolist()
|
| 66 |
+
self.labels = [label_to_idx[label] for label in df["label"].tolist()]
|
| 67 |
+
self.transform = transform
|
| 68 |
+
|
| 69 |
+
def __len__(self) -> int:
|
| 70 |
+
return len(self.labels)
|
| 71 |
+
|
| 72 |
+
def _load_image(self, path: str) -> torch.Tensor:
|
| 73 |
+
with Image.open(path) as img:
|
| 74 |
+
img = img.convert("RGB")
|
| 75 |
+
if self.transform is not None:
|
| 76 |
+
img = self.transform(img)
|
| 77 |
+
return img
|
| 78 |
+
|
| 79 |
+
def __getitem__(self, idx: int) -> tuple[torch.Tensor, int]:
|
| 80 |
+
clinical = self._load_image(self.clinical_paths[idx])
|
| 81 |
+
dermoscopic = self._load_image(self.dermoscopic_paths[idx])
|
| 82 |
+
return torch.stack([clinical, dermoscopic], dim=0), self.labels[idx]
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def set_seed(seed: int) -> None:
|
| 86 |
+
os.environ["PYTHONHASHSEED"] = str(seed)
|
| 87 |
+
random.seed(seed)
|
| 88 |
+
np.random.seed(seed)
|
| 89 |
+
torch.manual_seed(seed)
|
| 90 |
+
torch.cuda.manual_seed_all(seed)
|
| 91 |
+
torch.backends.cudnn.benchmark = True
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def normalize_image_type(image_type: str) -> str:
|
| 95 |
+
if image_type == "clinical: close-up":
|
| 96 |
+
return "clinical_close_up"
|
| 97 |
+
return image_type.replace(" ", "_").replace(":", "").replace("-", "_")
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def has_milk10k_files(path: Path) -> bool:
|
| 101 |
+
return all((path / name).exists() for name in REQUIRED_DATA_FILES)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def resolve_data_dir(data_dir: Path | None) -> Path:
|
| 105 |
+
if data_dir is not None:
|
| 106 |
+
data_dir = data_dir.expanduser().resolve()
|
| 107 |
+
if not has_milk10k_files(data_dir):
|
| 108 |
+
expected = ", ".join(REQUIRED_DATA_FILES)
|
| 109 |
+
raise FileNotFoundError(f"--data-dir={data_dir} does not contain required MILK10k files: {expected}")
|
| 110 |
+
return data_dir
|
| 111 |
+
|
| 112 |
+
candidates = [Path.cwd()]
|
| 113 |
+
kaggle_input = Path("/kaggle/input")
|
| 114 |
+
if kaggle_input.exists():
|
| 115 |
+
candidates.extend(path.parent for path in kaggle_input.rglob("MILK10k_Training_GroundTruth.csv"))
|
| 116 |
+
|
| 117 |
+
seen = set()
|
| 118 |
+
for candidate in candidates:
|
| 119 |
+
candidate = candidate.resolve()
|
| 120 |
+
if candidate in seen:
|
| 121 |
+
continue
|
| 122 |
+
seen.add(candidate)
|
| 123 |
+
if has_milk10k_files(candidate):
|
| 124 |
+
return candidate
|
| 125 |
+
|
| 126 |
+
expected = ", ".join(REQUIRED_DATA_FILES)
|
| 127 |
+
raise FileNotFoundError(
|
| 128 |
+
f"Could not auto-detect MILK10k data dir. Pass --data-dir PATH containing: {expected}"
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def load_dataframe(data_dir: Path, image_type: str) -> pd.DataFrame:
|
| 133 |
+
input_dir = data_dir / "MILK10k_Training_Input"
|
| 134 |
+
gt = pd.read_csv(data_dir / "MILK10k_Training_GroundTruth.csv")
|
| 135 |
+
meta = pd.read_csv(data_dir / "MILK10k_Training_Metadata.csv")
|
| 136 |
+
|
| 137 |
+
gt["label"] = gt[LABEL_COLUMNS].idxmax(axis=1)
|
| 138 |
+
df = meta.merge(gt[["lesion_id", "label"]], on="lesion_id", how="inner")
|
| 139 |
+
df["image_type_norm"] = df["image_type"].map(normalize_image_type)
|
| 140 |
+
|
| 141 |
+
if image_type != "all":
|
| 142 |
+
df = df[df["image_type_norm"] == image_type].copy()
|
| 143 |
+
|
| 144 |
+
df["path"] = df.apply(lambda r: input_dir / r["lesion_id"] / f"{r['isic_id']}.jpg", axis=1)
|
| 145 |
+
df = df[df["path"].map(lambda p: p.exists())].copy()
|
| 146 |
+
df["path"] = df["path"].map(str)
|
| 147 |
+
|
| 148 |
+
if df.empty:
|
| 149 |
+
raise ValueError(f"No images found for image_type={image_type!r} under {input_dir}")
|
| 150 |
+
return df[["path", "label", "lesion_id", "isic_id", "image_type_norm"]]
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def to_paired_lesion_dataframe(df: pd.DataFrame) -> pd.DataFrame:
|
| 154 |
+
clinical = (
|
| 155 |
+
df[df["image_type_norm"] == "clinical_close_up"][["lesion_id", "path"]]
|
| 156 |
+
.rename(columns={"path": "clinical_path"})
|
| 157 |
+
.drop_duplicates("lesion_id")
|
| 158 |
+
)
|
| 159 |
+
dermoscopic = (
|
| 160 |
+
df[df["image_type_norm"] == "dermoscopic"][["lesion_id", "path"]]
|
| 161 |
+
.rename(columns={"path": "dermoscopic_path"})
|
| 162 |
+
.drop_duplicates("lesion_id")
|
| 163 |
+
)
|
| 164 |
+
labels = df[["lesion_id", "label"]].drop_duplicates("lesion_id")
|
| 165 |
+
paired = labels.merge(clinical, on="lesion_id", how="inner").merge(dermoscopic, on="lesion_id", how="inner")
|
| 166 |
+
if paired.empty:
|
| 167 |
+
raise ValueError("No paired clinical/dermoscopic lesions found.")
|
| 168 |
+
return paired[["lesion_id", "label", "clinical_path", "dermoscopic_path"]]
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def lesion_level_train_val_split(
|
| 172 |
+
df: pd.DataFrame,
|
| 173 |
+
val_size: float,
|
| 174 |
+
seed: int,
|
| 175 |
+
) -> tuple[pd.DataFrame, pd.DataFrame]:
|
| 176 |
+
lesion_df = df[["lesion_id", "label"]].drop_duplicates("lesion_id")
|
| 177 |
+
|
| 178 |
+
train_lesions, val_lesions = train_test_split(
|
| 179 |
+
lesion_df,
|
| 180 |
+
test_size=val_size,
|
| 181 |
+
stratify=lesion_df["label"],
|
| 182 |
+
random_state=seed,
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
train_df = df[df["lesion_id"].isin(train_lesions["lesion_id"])].copy()
|
| 186 |
+
val_df = df[df["lesion_id"].isin(val_lesions["lesion_id"])].copy()
|
| 187 |
+
return train_df, val_df
|
train_milk10k_effb2_dual_metadata.py
ADDED
|
@@ -0,0 +1,793 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Train a MILK10k dual EfficientNet-B2 classifier with metadata fusion.
|
| 3 |
+
|
| 4 |
+
This script is intentionally separate from the architecture benchmark package.
|
| 5 |
+
It treats clinical and dermoscopic encoders as different feature spaces:
|
| 6 |
+
each branch gets its own projection head, tabular metadata gets its own head,
|
| 7 |
+
and classification uses the concatenated branch representations.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import argparse
|
| 13 |
+
import json
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import pandas as pd
|
| 19 |
+
import torch
|
| 20 |
+
from PIL import Image, ImageFile
|
| 21 |
+
from sklearn.metrics import (
|
| 22 |
+
accuracy_score,
|
| 23 |
+
balanced_accuracy_score,
|
| 24 |
+
classification_report,
|
| 25 |
+
confusion_matrix,
|
| 26 |
+
precision_recall_fscore_support,
|
| 27 |
+
roc_auc_score,
|
| 28 |
+
)
|
| 29 |
+
from sklearn.model_selection import train_test_split
|
| 30 |
+
from sklearn.preprocessing import label_binarize
|
| 31 |
+
from sklearn.utils.class_weight import compute_class_weight
|
| 32 |
+
from torch import nn
|
| 33 |
+
from torch.amp import GradScaler, autocast
|
| 34 |
+
from torch.utils.data import DataLoader, Dataset
|
| 35 |
+
from torchvision import transforms
|
| 36 |
+
from torchvision.models import EfficientNet_B2_Weights, efficientnet_b2
|
| 37 |
+
from tqdm.auto import tqdm
|
| 38 |
+
|
| 39 |
+
from datasets import LABEL_COLUMNS, normalize_image_type, resolve_data_dir, set_seed
|
| 40 |
+
|
| 41 |
+
ImageFile.LOAD_TRUNCATED_IMAGES = True
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
METADATA_COLUMNS = ("age_approx", "sex", "skin_tone_class", "site")
|
| 45 |
+
CHECKPOINT_STATE_KEYS = ("model_state", "model_state_dict", "state_dict")
|
| 46 |
+
PREFIXES_TO_STRIP = ("module.", "model.", "_orig_mod.")
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class PairedMilk10kMetadataDataset(Dataset):
|
| 50 |
+
def __init__(
|
| 51 |
+
self,
|
| 52 |
+
df: pd.DataFrame,
|
| 53 |
+
label_to_idx: dict[str, int],
|
| 54 |
+
metadata_spec: dict[str, Any],
|
| 55 |
+
transform=None,
|
| 56 |
+
) -> None:
|
| 57 |
+
self.df = df.reset_index(drop=True)
|
| 58 |
+
self.labels = [label_to_idx[label] for label in self.df["label"].tolist()]
|
| 59 |
+
self.metadata = np.stack([metadata_vector(row, metadata_spec) for _, row in self.df.iterrows()])
|
| 60 |
+
self.transform = transform
|
| 61 |
+
|
| 62 |
+
def __len__(self) -> int:
|
| 63 |
+
return len(self.df)
|
| 64 |
+
|
| 65 |
+
def _load_image(self, path: str) -> torch.Tensor:
|
| 66 |
+
with Image.open(path) as img:
|
| 67 |
+
image = img.convert("RGB")
|
| 68 |
+
if self.transform is not None:
|
| 69 |
+
image = self.transform(image)
|
| 70 |
+
return image
|
| 71 |
+
|
| 72 |
+
def __getitem__(self, idx: int) -> dict[str, torch.Tensor]:
|
| 73 |
+
row = self.df.iloc[idx]
|
| 74 |
+
return {
|
| 75 |
+
"clinical": self._load_image(row["clinical_path"]),
|
| 76 |
+
"dermoscopic": self._load_image(row["dermoscopic_path"]),
|
| 77 |
+
"metadata": torch.from_numpy(self.metadata[idx]),
|
| 78 |
+
"label": torch.tensor(self.labels[idx], dtype=torch.long),
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class ProjectionHead(nn.Module):
|
| 83 |
+
def __init__(self, in_dim: int, out_dim: int, dropout: float) -> None:
|
| 84 |
+
super().__init__()
|
| 85 |
+
self.net = nn.Sequential(
|
| 86 |
+
nn.LayerNorm(in_dim),
|
| 87 |
+
nn.Dropout(dropout),
|
| 88 |
+
nn.Linear(in_dim, out_dim),
|
| 89 |
+
nn.GELU(),
|
| 90 |
+
nn.LayerNorm(out_dim),
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 94 |
+
return self.net(x)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class MetadataHead(nn.Module):
|
| 98 |
+
def __init__(self, in_dim: int, out_dim: int, dropout: float) -> None:
|
| 99 |
+
super().__init__()
|
| 100 |
+
hidden_dim = max(out_dim * 2, 32)
|
| 101 |
+
self.net = nn.Sequential(
|
| 102 |
+
nn.LayerNorm(in_dim),
|
| 103 |
+
nn.Linear(in_dim, hidden_dim),
|
| 104 |
+
nn.GELU(),
|
| 105 |
+
nn.Dropout(dropout),
|
| 106 |
+
nn.Linear(hidden_dim, out_dim),
|
| 107 |
+
nn.GELU(),
|
| 108 |
+
nn.LayerNorm(out_dim),
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
def forward(self, metadata: torch.Tensor) -> torch.Tensor:
|
| 112 |
+
return self.net(metadata)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class DualEffB2MetadataClassifier(nn.Module):
|
| 116 |
+
def __init__(
|
| 117 |
+
self,
|
| 118 |
+
num_classes: int,
|
| 119 |
+
metadata_input_dim: int,
|
| 120 |
+
branch_dim: int,
|
| 121 |
+
metadata_dim: int,
|
| 122 |
+
classifier_hidden_dim: int,
|
| 123 |
+
dropout: float,
|
| 124 |
+
imagenet_pretrained: bool,
|
| 125 |
+
) -> None:
|
| 126 |
+
super().__init__()
|
| 127 |
+
self.clinical_encoder, feature_dim = build_effb2_feature_encoder(imagenet_pretrained)
|
| 128 |
+
self.dermoscopic_encoder, derm_feature_dim = build_effb2_feature_encoder(imagenet_pretrained)
|
| 129 |
+
if feature_dim != derm_feature_dim:
|
| 130 |
+
raise RuntimeError(f"EfficientNet-B2 feature dims differ: {feature_dim} vs {derm_feature_dim}")
|
| 131 |
+
|
| 132 |
+
self.clinical_head = ProjectionHead(feature_dim, branch_dim, dropout)
|
| 133 |
+
self.dermoscopic_head = ProjectionHead(feature_dim, branch_dim, dropout)
|
| 134 |
+
self.metadata_head = MetadataHead(metadata_input_dim, metadata_dim, dropout)
|
| 135 |
+
fused_dim = branch_dim * 2 + metadata_dim
|
| 136 |
+
self.classifier = nn.Sequential(
|
| 137 |
+
nn.LayerNorm(fused_dim),
|
| 138 |
+
nn.Dropout(dropout),
|
| 139 |
+
nn.Linear(fused_dim, classifier_hidden_dim),
|
| 140 |
+
nn.GELU(),
|
| 141 |
+
nn.Dropout(dropout),
|
| 142 |
+
nn.Linear(classifier_hidden_dim, num_classes),
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
def forward(
|
| 146 |
+
self,
|
| 147 |
+
clinical: torch.Tensor,
|
| 148 |
+
dermoscopic: torch.Tensor,
|
| 149 |
+
metadata: torch.Tensor,
|
| 150 |
+
) -> torch.Tensor:
|
| 151 |
+
clinical_features = self.clinical_encoder(clinical)
|
| 152 |
+
dermoscopic_features = self.dermoscopic_encoder(dermoscopic)
|
| 153 |
+
clinical_repr = self.clinical_head(clinical_features)
|
| 154 |
+
dermoscopic_repr = self.dermoscopic_head(dermoscopic_features)
|
| 155 |
+
metadata_repr = self.metadata_head(metadata)
|
| 156 |
+
fused = torch.cat([clinical_repr, dermoscopic_repr, metadata_repr], dim=1)
|
| 157 |
+
return self.classifier(fused)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def parse_args() -> argparse.Namespace:
|
| 161 |
+
parser = argparse.ArgumentParser(description="Train MILK10k dual EfficientNet-B2 with metadata fusion.")
|
| 162 |
+
parser.add_argument("--data-dir", type=Path, default=None)
|
| 163 |
+
parser.add_argument("--clinical-checkpoint", type=Path, required=True)
|
| 164 |
+
parser.add_argument("--dermoscopic-checkpoint", type=Path, required=True)
|
| 165 |
+
parser.add_argument("--output-dir", type=Path, default=Path("milk10k_dual_effb2_metadata_runs"))
|
| 166 |
+
parser.add_argument("--freeze-epochs", type=int, default=8)
|
| 167 |
+
parser.add_argument("--finetune-epochs", type=int, default=20)
|
| 168 |
+
parser.add_argument("--batch-size", type=int, default=8)
|
| 169 |
+
parser.add_argument("--image-size", type=int, default=260)
|
| 170 |
+
parser.add_argument("--num-workers", type=int, default=4)
|
| 171 |
+
parser.add_argument("--head-lr", type=float, default=1e-4)
|
| 172 |
+
parser.add_argument("--encoder-lr", type=float, default=1e-5)
|
| 173 |
+
parser.add_argument("--weight-decay", type=float, default=1e-4)
|
| 174 |
+
parser.add_argument("--val-size", type=float, default=0.20)
|
| 175 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 176 |
+
parser.add_argument("--branch-dim", type=int, default=512)
|
| 177 |
+
parser.add_argument("--metadata-dim", type=int, default=64)
|
| 178 |
+
parser.add_argument("--classifier-hidden-dim", type=int, default=512)
|
| 179 |
+
parser.add_argument("--dropout", type=float, default=0.3)
|
| 180 |
+
parser.add_argument("--class-weight", action="store_true")
|
| 181 |
+
parser.add_argument("--amp", action="store_true")
|
| 182 |
+
parser.add_argument(
|
| 183 |
+
"--imagenet-pretrained",
|
| 184 |
+
action="store_true",
|
| 185 |
+
help="Initialize EfficientNet-B2 with ImageNet weights before loading branch checkpoints.",
|
| 186 |
+
)
|
| 187 |
+
parser.add_argument("--patience", type=int, default=6)
|
| 188 |
+
return parser.parse_args()
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def build_effb2_feature_encoder(imagenet_pretrained: bool) -> tuple[nn.Module, int]:
|
| 192 |
+
weights = EfficientNet_B2_Weights.IMAGENET1K_V1 if imagenet_pretrained else None
|
| 193 |
+
model = efficientnet_b2(weights=weights)
|
| 194 |
+
feature_dim = int(model.classifier[1].in_features)
|
| 195 |
+
model.classifier = nn.Identity()
|
| 196 |
+
return model, feature_dim
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def load_paired_dataframe(data_dir: Path) -> pd.DataFrame:
|
| 200 |
+
input_dir = data_dir / "MILK10k_Training_Input"
|
| 201 |
+
gt = pd.read_csv(data_dir / "MILK10k_Training_GroundTruth.csv")
|
| 202 |
+
meta = pd.read_csv(data_dir / "MILK10k_Training_Metadata.csv")
|
| 203 |
+
|
| 204 |
+
gt["label"] = gt[LABEL_COLUMNS].idxmax(axis=1)
|
| 205 |
+
meta["image_type_norm"] = meta["image_type"].map(normalize_image_type)
|
| 206 |
+
meta["path"] = meta.apply(lambda r: input_dir / r["lesion_id"] / f"{r['isic_id']}.jpg", axis=1)
|
| 207 |
+
meta = meta[meta["path"].map(lambda p: p.exists())].copy()
|
| 208 |
+
meta["path"] = meta["path"].map(str)
|
| 209 |
+
|
| 210 |
+
keep = ["lesion_id", "path", *METADATA_COLUMNS]
|
| 211 |
+
clinical = meta[meta["image_type_norm"] == "clinical_close_up"][keep].drop_duplicates("lesion_id")
|
| 212 |
+
dermoscopic = meta[meta["image_type_norm"] == "dermoscopic"][keep].drop_duplicates("lesion_id")
|
| 213 |
+
paired = (
|
| 214 |
+
gt[["lesion_id", "label"]]
|
| 215 |
+
.merge(clinical.add_prefix("clinical_"), left_on="lesion_id", right_on="clinical_lesion_id")
|
| 216 |
+
.merge(dermoscopic.add_prefix("dermoscopic_"), left_on="lesion_id", right_on="dermoscopic_lesion_id")
|
| 217 |
+
.drop(columns=["clinical_lesion_id", "dermoscopic_lesion_id"])
|
| 218 |
+
)
|
| 219 |
+
if paired.empty:
|
| 220 |
+
raise ValueError(f"No paired clinical/dermoscopic lesions found under {input_dir}")
|
| 221 |
+
return paired
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def lesion_split(df: pd.DataFrame, val_size: float, seed: int) -> tuple[pd.DataFrame, pd.DataFrame]:
|
| 225 |
+
lesion_df = df[["lesion_id", "label"]].drop_duplicates("lesion_id")
|
| 226 |
+
train_lesions, val_lesions = train_test_split(
|
| 227 |
+
lesion_df,
|
| 228 |
+
test_size=val_size,
|
| 229 |
+
stratify=lesion_df["label"],
|
| 230 |
+
random_state=seed,
|
| 231 |
+
)
|
| 232 |
+
return (
|
| 233 |
+
df[df["lesion_id"].isin(train_lesions["lesion_id"])].copy(),
|
| 234 |
+
df[df["lesion_id"].isin(val_lesions["lesion_id"])].copy(),
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def fit_metadata_spec(train_df: pd.DataFrame) -> dict[str, Any]:
|
| 239 |
+
sex_values = sorted({"unknown"} | collect_string_values(train_df, "sex"))
|
| 240 |
+
site_values = sorted({"unknown"} | collect_string_values(train_df, "site"))
|
| 241 |
+
return {"sex_values": sex_values, "site_values": site_values}
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def collect_string_values(df: pd.DataFrame, field: str) -> set[str]:
|
| 245 |
+
values: set[str] = set()
|
| 246 |
+
for prefix in ("clinical", "dermoscopic"):
|
| 247 |
+
series = df[f"{prefix}_{field}"].fillna("unknown").astype(str).str.strip()
|
| 248 |
+
values.update(value if value else "unknown" for value in series.tolist())
|
| 249 |
+
return values
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def metadata_vector(row: pd.Series, spec: dict[str, Any]) -> np.ndarray:
|
| 253 |
+
age = first_numeric(row, "age_approx")
|
| 254 |
+
skin_tone = first_numeric(row, "skin_tone_class")
|
| 255 |
+
sex = first_string(row, "sex")
|
| 256 |
+
site = first_string(row, "site")
|
| 257 |
+
|
| 258 |
+
values: list[float] = [
|
| 259 |
+
0.0 if age is None else float(age) / 100.0,
|
| 260 |
+
0.0 if skin_tone is None else float(skin_tone) / 6.0,
|
| 261 |
+
]
|
| 262 |
+
values.extend(1.0 if sex == item else 0.0 for item in spec["sex_values"])
|
| 263 |
+
values.extend(1.0 if site == item else 0.0 for item in spec["site_values"])
|
| 264 |
+
return np.asarray(values, dtype=np.float32)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def first_numeric(row: pd.Series, field: str) -> float | None:
|
| 268 |
+
for prefix in ("clinical", "dermoscopic"):
|
| 269 |
+
value = pd.to_numeric(row.get(f"{prefix}_{field}"), errors="coerce")
|
| 270 |
+
if not pd.isna(value):
|
| 271 |
+
return float(value)
|
| 272 |
+
return None
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def first_string(row: pd.Series, field: str) -> str:
|
| 276 |
+
for prefix in ("clinical", "dermoscopic"):
|
| 277 |
+
value = row.get(f"{prefix}_{field}")
|
| 278 |
+
if pd.notna(value):
|
| 279 |
+
value = str(value).strip()
|
| 280 |
+
if value:
|
| 281 |
+
return value
|
| 282 |
+
return "unknown"
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def make_transforms(image_size: int):
|
| 286 |
+
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
| 287 |
+
train_transform = transforms.Compose(
|
| 288 |
+
[
|
| 289 |
+
transforms.Resize((image_size, image_size)),
|
| 290 |
+
transforms.RandomHorizontalFlip(),
|
| 291 |
+
transforms.RandomVerticalFlip(),
|
| 292 |
+
transforms.RandomRotation(20),
|
| 293 |
+
transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2),
|
| 294 |
+
transforms.ToTensor(),
|
| 295 |
+
normalize,
|
| 296 |
+
]
|
| 297 |
+
)
|
| 298 |
+
eval_transform = transforms.Compose(
|
| 299 |
+
[
|
| 300 |
+
transforms.Resize((image_size, image_size)),
|
| 301 |
+
transforms.ToTensor(),
|
| 302 |
+
normalize,
|
| 303 |
+
]
|
| 304 |
+
)
|
| 305 |
+
return train_transform, eval_transform
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def make_loaders(
|
| 309 |
+
train_df: pd.DataFrame,
|
| 310 |
+
val_df: pd.DataFrame,
|
| 311 |
+
label_to_idx: dict[str, int],
|
| 312 |
+
metadata_spec: dict[str, Any],
|
| 313 |
+
args: argparse.Namespace,
|
| 314 |
+
) -> tuple[DataLoader, DataLoader]:
|
| 315 |
+
train_transform, eval_transform = make_transforms(args.image_size)
|
| 316 |
+
train_ds = PairedMilk10kMetadataDataset(train_df, label_to_idx, metadata_spec, train_transform)
|
| 317 |
+
val_ds = PairedMilk10kMetadataDataset(val_df, label_to_idx, metadata_spec, eval_transform)
|
| 318 |
+
common = dict(
|
| 319 |
+
batch_size=args.batch_size,
|
| 320 |
+
num_workers=args.num_workers,
|
| 321 |
+
pin_memory=torch.cuda.is_available(),
|
| 322 |
+
drop_last=False,
|
| 323 |
+
)
|
| 324 |
+
return DataLoader(train_ds, shuffle=True, **common), DataLoader(val_ds, shuffle=False, **common)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def extract_state_dict(checkpoint: Any) -> dict[str, torch.Tensor]:
|
| 328 |
+
if isinstance(checkpoint, dict):
|
| 329 |
+
for key in CHECKPOINT_STATE_KEYS:
|
| 330 |
+
value = checkpoint.get(key)
|
| 331 |
+
if isinstance(value, dict):
|
| 332 |
+
return value
|
| 333 |
+
if isinstance(checkpoint, dict) and all(torch.is_tensor(value) for value in checkpoint.values()):
|
| 334 |
+
return checkpoint
|
| 335 |
+
raise ValueError("Checkpoint does not contain a supported state dict.")
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def normalize_key(key: str) -> str:
|
| 339 |
+
changed = True
|
| 340 |
+
while changed:
|
| 341 |
+
changed = False
|
| 342 |
+
for prefix in PREFIXES_TO_STRIP:
|
| 343 |
+
if key.startswith(prefix):
|
| 344 |
+
key = key.removeprefix(prefix)
|
| 345 |
+
changed = True
|
| 346 |
+
return key
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def load_encoder_checkpoint(path: Path, encoder: nn.Module, branch_name: str, device: torch.device) -> None:
|
| 350 |
+
if not path.exists():
|
| 351 |
+
raise FileNotFoundError(f"{branch_name} checkpoint not found: {path}")
|
| 352 |
+
try:
|
| 353 |
+
checkpoint = torch.load(path, map_location=device, weights_only=False)
|
| 354 |
+
except TypeError:
|
| 355 |
+
checkpoint = torch.load(path, map_location=device)
|
| 356 |
+
|
| 357 |
+
raw_state = extract_state_dict(checkpoint)
|
| 358 |
+
source_state = {normalize_key(key): value for key, value in raw_state.items()}
|
| 359 |
+
target_state = encoder.state_dict()
|
| 360 |
+
matched = {
|
| 361 |
+
key: value
|
| 362 |
+
for key, value in source_state.items()
|
| 363 |
+
if key in target_state and tuple(value.shape) == tuple(target_state[key].shape)
|
| 364 |
+
}
|
| 365 |
+
skipped = len(source_state) - len(matched)
|
| 366 |
+
if not matched:
|
| 367 |
+
raise RuntimeError(f"{branch_name}: no matching encoder weights loaded from {path}")
|
| 368 |
+
|
| 369 |
+
target_state.update(matched)
|
| 370 |
+
encoder.load_state_dict(target_state)
|
| 371 |
+
print(f"{branch_name}: loaded {len(matched)} keys from {path}; skipped {skipped} keys")
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def set_encoder_trainable(model: DualEffB2MetadataClassifier, trainable: bool) -> None:
|
| 375 |
+
for param in model.clinical_encoder.parameters():
|
| 376 |
+
param.requires_grad = trainable
|
| 377 |
+
for param in model.dermoscopic_encoder.parameters():
|
| 378 |
+
param.requires_grad = trainable
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def build_optimizer(model: DualEffB2MetadataClassifier, args: argparse.Namespace, encoders_trainable: bool) -> torch.optim.Optimizer:
|
| 382 |
+
head_params = []
|
| 383 |
+
encoder_params = []
|
| 384 |
+
for name, param in model.named_parameters():
|
| 385 |
+
if not param.requires_grad:
|
| 386 |
+
continue
|
| 387 |
+
if name.startswith(("clinical_encoder.", "dermoscopic_encoder.")):
|
| 388 |
+
encoder_params.append(param)
|
| 389 |
+
else:
|
| 390 |
+
head_params.append(param)
|
| 391 |
+
|
| 392 |
+
groups = [{"params": head_params, "lr": args.head_lr}]
|
| 393 |
+
if encoders_trainable and encoder_params:
|
| 394 |
+
groups.append({"params": encoder_params, "lr": args.encoder_lr})
|
| 395 |
+
return torch.optim.AdamW(groups, weight_decay=args.weight_decay)
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def build_loss(train_df: pd.DataFrame, label_to_idx: dict[str, int], args: argparse.Namespace, device: torch.device) -> nn.Module:
|
| 399 |
+
weight = None
|
| 400 |
+
if args.class_weight:
|
| 401 |
+
y = np.array([label_to_idx[label] for label in train_df["label"]])
|
| 402 |
+
weights = compute_class_weight(class_weight="balanced", classes=np.arange(len(label_to_idx)), y=y)
|
| 403 |
+
weight = torch.tensor(weights, dtype=torch.float32, device=device)
|
| 404 |
+
return nn.CrossEntropyLoss(weight=weight)
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def move_batch(batch: dict[str, torch.Tensor], device: torch.device) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 408 |
+
clinical = batch["clinical"].to(device, non_blocking=True)
|
| 409 |
+
dermoscopic = batch["dermoscopic"].to(device, non_blocking=True)
|
| 410 |
+
metadata = batch["metadata"].to(device, non_blocking=True)
|
| 411 |
+
labels = batch["label"].to(device, non_blocking=True)
|
| 412 |
+
return clinical, dermoscopic, metadata, labels
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def run_epoch(
|
| 416 |
+
model: DualEffB2MetadataClassifier,
|
| 417 |
+
loader: DataLoader,
|
| 418 |
+
criterion: nn.Module,
|
| 419 |
+
device: torch.device,
|
| 420 |
+
optimizer: torch.optim.Optimizer | None = None,
|
| 421 |
+
scaler: GradScaler | None = None,
|
| 422 |
+
use_amp: bool = False,
|
| 423 |
+
) -> dict[str, float]:
|
| 424 |
+
training = optimizer is not None
|
| 425 |
+
model.train(training)
|
| 426 |
+
total_loss = 0.0
|
| 427 |
+
correct = 0
|
| 428 |
+
top3_correct = 0
|
| 429 |
+
total = 0
|
| 430 |
+
|
| 431 |
+
for batch in tqdm(loader, leave=False):
|
| 432 |
+
clinical, dermoscopic, metadata, labels = move_batch(batch, device)
|
| 433 |
+
if training:
|
| 434 |
+
optimizer.zero_grad(set_to_none=True)
|
| 435 |
+
|
| 436 |
+
with torch.set_grad_enabled(training):
|
| 437 |
+
with autocast("cuda", enabled=use_amp):
|
| 438 |
+
logits = model(clinical, dermoscopic, metadata)
|
| 439 |
+
loss = criterion(logits, labels)
|
| 440 |
+
if training:
|
| 441 |
+
if scaler is not None and use_amp:
|
| 442 |
+
scaler.scale(loss).backward()
|
| 443 |
+
scaler.unscale_(optimizer)
|
| 444 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
|
| 445 |
+
scaler.step(optimizer)
|
| 446 |
+
scaler.update()
|
| 447 |
+
else:
|
| 448 |
+
loss.backward()
|
| 449 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
|
| 450 |
+
optimizer.step()
|
| 451 |
+
|
| 452 |
+
batch_size = labels.size(0)
|
| 453 |
+
total_loss += float(loss.detach().item()) * batch_size
|
| 454 |
+
correct += (logits.argmax(dim=1) == labels).sum().item()
|
| 455 |
+
topk = min(3, logits.size(1))
|
| 456 |
+
top3_correct += logits.topk(topk, dim=1).indices.eq(labels[:, None]).any(dim=1).sum().item()
|
| 457 |
+
total += batch_size
|
| 458 |
+
|
| 459 |
+
return {
|
| 460 |
+
"loss": total_loss / max(total, 1),
|
| 461 |
+
"accuracy": correct / max(total, 1),
|
| 462 |
+
"top3_accuracy": top3_correct / max(total, 1),
|
| 463 |
+
}
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
@torch.no_grad()
|
| 467 |
+
def predict(model: DualEffB2MetadataClassifier, loader: DataLoader, device: torch.device) -> tuple[np.ndarray, np.ndarray]:
|
| 468 |
+
model.eval()
|
| 469 |
+
labels_all = []
|
| 470 |
+
probs_all = []
|
| 471 |
+
for batch in tqdm(loader, leave=False):
|
| 472 |
+
clinical, dermoscopic, metadata, labels = move_batch(batch, device)
|
| 473 |
+
logits = model(clinical, dermoscopic, metadata)
|
| 474 |
+
labels_all.append(labels.cpu().numpy())
|
| 475 |
+
probs_all.append(torch.softmax(logits, dim=1).cpu().numpy())
|
| 476 |
+
return np.concatenate(labels_all), np.concatenate(probs_all)
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
def compute_metrics(y_true: np.ndarray, y_prob: np.ndarray, class_names: list[str]) -> tuple[dict[str, Any], pd.DataFrame, np.ndarray]:
|
| 480 |
+
y_pred = y_prob.argmax(axis=1)
|
| 481 |
+
labels = list(range(len(class_names)))
|
| 482 |
+
y_true_bin = label_binarize(y_true, classes=labels)
|
| 483 |
+
cm = confusion_matrix(y_true, y_pred, labels=labels)
|
| 484 |
+
|
| 485 |
+
precision_macro, recall_macro, f1_macro, _ = precision_recall_fscore_support(
|
| 486 |
+
y_true, y_pred, labels=labels, average="macro", zero_division=0
|
| 487 |
+
)
|
| 488 |
+
precision_weighted, recall_weighted, f1_weighted, _ = precision_recall_fscore_support(
|
| 489 |
+
y_true, y_pred, labels=labels, average="weighted", zero_division=0
|
| 490 |
+
)
|
| 491 |
+
precision_per_class, recall_per_class, f1_per_class, support_per_class = precision_recall_fscore_support(
|
| 492 |
+
y_true, y_pred, labels=labels, average=None, zero_division=0
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
total = cm.sum()
|
| 496 |
+
per_class_rows = []
|
| 497 |
+
for idx, class_name in enumerate(class_names):
|
| 498 |
+
tp = int(cm[idx, idx])
|
| 499 |
+
fn = int(cm[idx, :].sum() - tp)
|
| 500 |
+
fp = int(cm[:, idx].sum() - tp)
|
| 501 |
+
tn = int(total - tp - fn - fp)
|
| 502 |
+
try:
|
| 503 |
+
auc_ovr = float(roc_auc_score(y_true_bin[:, idx], y_prob[:, idx]))
|
| 504 |
+
except ValueError:
|
| 505 |
+
auc_ovr = None
|
| 506 |
+
per_class_rows.append(
|
| 507 |
+
{
|
| 508 |
+
"class": class_name,
|
| 509 |
+
"support": int(support_per_class[idx]),
|
| 510 |
+
"precision": float(precision_per_class[idx]),
|
| 511 |
+
"recall_sensitivity": float(recall_per_class[idx]),
|
| 512 |
+
"specificity": tn / (tn + fp) if (tn + fp) else 0.0,
|
| 513 |
+
"f1": float(f1_per_class[idx]),
|
| 514 |
+
"auc_ovr": auc_ovr,
|
| 515 |
+
}
|
| 516 |
+
)
|
| 517 |
+
|
| 518 |
+
metrics = {
|
| 519 |
+
"accuracy": float(accuracy_score(y_true, y_pred)),
|
| 520 |
+
"balanced_accuracy": float(balanced_accuracy_score(y_true, y_pred)),
|
| 521 |
+
"top2_accuracy": float(np.mean((np.argsort(y_prob, axis=1)[:, -min(2, len(class_names)) :] == y_true[:, None]).any(axis=1))),
|
| 522 |
+
"top3_accuracy": float(np.mean((np.argsort(y_prob, axis=1)[:, -min(3, len(class_names)) :] == y_true[:, None]).any(axis=1))),
|
| 523 |
+
"precision_macro": float(precision_macro),
|
| 524 |
+
"recall_macro": float(recall_macro),
|
| 525 |
+
"f1_macro": float(f1_macro),
|
| 526 |
+
"precision_weighted": float(precision_weighted),
|
| 527 |
+
"recall_weighted": float(recall_weighted),
|
| 528 |
+
"f1_weighted": float(f1_weighted),
|
| 529 |
+
"roc_auc_macro_ovr": safe_roc_auc(y_true_bin, y_prob, "macro"),
|
| 530 |
+
"roc_auc_weighted_ovr": safe_roc_auc(y_true_bin, y_prob, "weighted"),
|
| 531 |
+
"classification_report": classification_report(
|
| 532 |
+
y_true,
|
| 533 |
+
y_pred,
|
| 534 |
+
labels=labels,
|
| 535 |
+
target_names=class_names,
|
| 536 |
+
zero_division=0,
|
| 537 |
+
output_dict=True,
|
| 538 |
+
),
|
| 539 |
+
"class_names": class_names,
|
| 540 |
+
}
|
| 541 |
+
return metrics, pd.DataFrame(per_class_rows), cm
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
def safe_roc_auc(y_true_bin: np.ndarray, y_prob: np.ndarray, average: str | None) -> float | None:
|
| 545 |
+
try:
|
| 546 |
+
return float(roc_auc_score(y_true_bin, y_prob, average=average, multi_class="ovr"))
|
| 547 |
+
except ValueError:
|
| 548 |
+
return None
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
def save_checkpoint(
|
| 552 |
+
path: Path,
|
| 553 |
+
model: DualEffB2MetadataClassifier,
|
| 554 |
+
optimizer: torch.optim.Optimizer,
|
| 555 |
+
epoch: int,
|
| 556 |
+
phase: str,
|
| 557 |
+
best_val_loss: float,
|
| 558 |
+
class_names: list[str],
|
| 559 |
+
label_to_idx: dict[str, int],
|
| 560 |
+
metadata_spec: dict[str, Any],
|
| 561 |
+
args: argparse.Namespace,
|
| 562 |
+
) -> None:
|
| 563 |
+
torch.save(
|
| 564 |
+
{
|
| 565 |
+
"epoch": epoch,
|
| 566 |
+
"phase": phase,
|
| 567 |
+
"model_state": model.state_dict(),
|
| 568 |
+
"optimizer_state": optimizer.state_dict(),
|
| 569 |
+
"best_val_loss": best_val_loss,
|
| 570 |
+
"class_names": class_names,
|
| 571 |
+
"label_to_idx": label_to_idx,
|
| 572 |
+
"metadata_spec": metadata_spec,
|
| 573 |
+
"args": {key: str(value) if isinstance(value, Path) else value for key, value in vars(args).items()},
|
| 574 |
+
},
|
| 575 |
+
path,
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
def save_predictions(
|
| 580 |
+
val_df: pd.DataFrame,
|
| 581 |
+
y_true: np.ndarray,
|
| 582 |
+
y_prob: np.ndarray,
|
| 583 |
+
class_names: list[str],
|
| 584 |
+
output_dir: Path,
|
| 585 |
+
) -> None:
|
| 586 |
+
y_pred = y_prob.argmax(axis=1)
|
| 587 |
+
prediction_df = pd.DataFrame(
|
| 588 |
+
{
|
| 589 |
+
"lesion_id": val_df["lesion_id"].tolist(),
|
| 590 |
+
"clinical_path": val_df["clinical_path"].tolist(),
|
| 591 |
+
"dermoscopic_path": val_df["dermoscopic_path"].tolist(),
|
| 592 |
+
"y_true": y_true,
|
| 593 |
+
"y_pred": y_pred,
|
| 594 |
+
"label_true": [class_names[idx] for idx in y_true],
|
| 595 |
+
"label_pred": [class_names[idx] for idx in y_pred],
|
| 596 |
+
"confidence": y_prob.max(axis=1),
|
| 597 |
+
}
|
| 598 |
+
)
|
| 599 |
+
probability_df = pd.DataFrame(y_prob, columns=[f"prob_{name}" for name in class_names])
|
| 600 |
+
pd.concat([prediction_df, probability_df], axis=1).to_csv(output_dir / "val_predictions.csv", index=False)
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
def train_phase(
|
| 604 |
+
phase: str,
|
| 605 |
+
num_epochs: int,
|
| 606 |
+
start_epoch: int,
|
| 607 |
+
model: DualEffB2MetadataClassifier,
|
| 608 |
+
train_loader: DataLoader,
|
| 609 |
+
val_loader: DataLoader,
|
| 610 |
+
criterion: nn.Module,
|
| 611 |
+
device: torch.device,
|
| 612 |
+
args: argparse.Namespace,
|
| 613 |
+
class_names: list[str],
|
| 614 |
+
label_to_idx: dict[str, int],
|
| 615 |
+
metadata_spec: dict[str, Any],
|
| 616 |
+
output_dir: Path,
|
| 617 |
+
history: list[dict[str, Any]],
|
| 618 |
+
best_val_loss: float,
|
| 619 |
+
) -> tuple[int, float]:
|
| 620 |
+
if num_epochs <= 0:
|
| 621 |
+
return start_epoch, best_val_loss
|
| 622 |
+
|
| 623 |
+
encoders_trainable = phase == "finetune"
|
| 624 |
+
set_encoder_trainable(model, encoders_trainable)
|
| 625 |
+
optimizer = build_optimizer(model, args, encoders_trainable)
|
| 626 |
+
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode="min", factor=0.2, patience=2)
|
| 627 |
+
scaler = GradScaler("cuda", enabled=args.amp and device.type == "cuda")
|
| 628 |
+
use_amp = args.amp and device.type == "cuda"
|
| 629 |
+
patience_count = 0
|
| 630 |
+
|
| 631 |
+
print(f"\nPhase: {phase}, epochs={num_epochs}, encoders_trainable={encoders_trainable}")
|
| 632 |
+
for local_epoch in range(1, num_epochs + 1):
|
| 633 |
+
epoch = start_epoch + local_epoch - 1
|
| 634 |
+
train_stats = run_epoch(model, train_loader, criterion, device, optimizer, scaler, use_amp)
|
| 635 |
+
val_stats = run_epoch(model, val_loader, criterion, device)
|
| 636 |
+
scheduler.step(val_stats["loss"])
|
| 637 |
+
row = {
|
| 638 |
+
"phase": phase,
|
| 639 |
+
"epoch": epoch,
|
| 640 |
+
**{f"train_{key}": value for key, value in train_stats.items()},
|
| 641 |
+
**{f"val_{key}": value for key, value in val_stats.items()},
|
| 642 |
+
}
|
| 643 |
+
history.append(row)
|
| 644 |
+
pd.DataFrame(history).to_csv(output_dir / "history.csv", index=False)
|
| 645 |
+
print(
|
| 646 |
+
f"{phase} epoch {epoch:03d}: "
|
| 647 |
+
f"train_loss={train_stats['loss']:.4f} val_loss={val_stats['loss']:.4f} "
|
| 648 |
+
f"val_acc={val_stats['accuracy']:.4f} val_top3={val_stats['top3_accuracy']:.4f}"
|
| 649 |
+
)
|
| 650 |
+
|
| 651 |
+
if val_stats["loss"] < best_val_loss:
|
| 652 |
+
best_val_loss = val_stats["loss"]
|
| 653 |
+
patience_count = 0
|
| 654 |
+
save_checkpoint(
|
| 655 |
+
output_dir / "best.pt",
|
| 656 |
+
model,
|
| 657 |
+
optimizer,
|
| 658 |
+
epoch,
|
| 659 |
+
phase,
|
| 660 |
+
best_val_loss,
|
| 661 |
+
class_names,
|
| 662 |
+
label_to_idx,
|
| 663 |
+
metadata_spec,
|
| 664 |
+
args,
|
| 665 |
+
)
|
| 666 |
+
else:
|
| 667 |
+
patience_count += 1
|
| 668 |
+
if patience_count >= args.patience:
|
| 669 |
+
print(f"Early stopping {phase} at epoch {epoch}")
|
| 670 |
+
break
|
| 671 |
+
|
| 672 |
+
return start_epoch + num_epochs, best_val_loss
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
def save_run_config(
|
| 676 |
+
output_dir: Path,
|
| 677 |
+
args: argparse.Namespace,
|
| 678 |
+
class_names: list[str],
|
| 679 |
+
metadata_spec: dict[str, Any],
|
| 680 |
+
train_df: pd.DataFrame,
|
| 681 |
+
val_df: pd.DataFrame,
|
| 682 |
+
) -> None:
|
| 683 |
+
payload = {
|
| 684 |
+
"args": {key: str(value) if isinstance(value, Path) else value for key, value in vars(args).items()},
|
| 685 |
+
"class_names": class_names,
|
| 686 |
+
"metadata_spec": metadata_spec,
|
| 687 |
+
"train_size": len(train_df),
|
| 688 |
+
"val_size": len(val_df),
|
| 689 |
+
"fusion": "concat(clinical_head, dermoscopic_head, metadata_head)",
|
| 690 |
+
"backbone": "torchvision efficientnet_b2",
|
| 691 |
+
}
|
| 692 |
+
with open(output_dir / "run_config.json", "w", encoding="utf-8") as f:
|
| 693 |
+
json.dump(payload, f, indent=2)
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
def main() -> None:
|
| 697 |
+
args = parse_args()
|
| 698 |
+
set_seed(args.seed)
|
| 699 |
+
data_dir = resolve_data_dir(args.data_dir)
|
| 700 |
+
args.output_dir.mkdir(parents=True, exist_ok=True)
|
| 701 |
+
|
| 702 |
+
df = load_paired_dataframe(data_dir)
|
| 703 |
+
class_names = sorted(df["label"].unique())
|
| 704 |
+
label_to_idx = {label: idx for idx, label in enumerate(class_names)}
|
| 705 |
+
train_df, val_df = lesion_split(df, args.val_size, args.seed)
|
| 706 |
+
metadata_spec = fit_metadata_spec(train_df)
|
| 707 |
+
metadata_dim = len(metadata_vector(train_df.iloc[0], metadata_spec))
|
| 708 |
+
|
| 709 |
+
split_dir = args.output_dir / "splits"
|
| 710 |
+
split_dir.mkdir(exist_ok=True)
|
| 711 |
+
train_df.to_csv(split_dir / "train.csv", index=False)
|
| 712 |
+
val_df.to_csv(split_dir / "val.csv", index=False)
|
| 713 |
+
save_run_config(args.output_dir, args, class_names, metadata_spec, train_df, val_df)
|
| 714 |
+
|
| 715 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 716 |
+
model = DualEffB2MetadataClassifier(
|
| 717 |
+
num_classes=len(class_names),
|
| 718 |
+
metadata_input_dim=metadata_dim,
|
| 719 |
+
branch_dim=args.branch_dim,
|
| 720 |
+
metadata_dim=args.metadata_dim,
|
| 721 |
+
classifier_hidden_dim=args.classifier_hidden_dim,
|
| 722 |
+
dropout=args.dropout,
|
| 723 |
+
imagenet_pretrained=args.imagenet_pretrained,
|
| 724 |
+
).to(device)
|
| 725 |
+
load_encoder_checkpoint(args.clinical_checkpoint, model.clinical_encoder, "clinical", device)
|
| 726 |
+
load_encoder_checkpoint(args.dermoscopic_checkpoint, model.dermoscopic_encoder, "dermoscopic", device)
|
| 727 |
+
|
| 728 |
+
train_loader, val_loader = make_loaders(train_df, val_df, label_to_idx, metadata_spec, args)
|
| 729 |
+
criterion = build_loss(train_df, label_to_idx, args, device)
|
| 730 |
+
print(f"Data dir: {data_dir}")
|
| 731 |
+
print(f"Output dir: {args.output_dir}")
|
| 732 |
+
print(f"Device: {device}")
|
| 733 |
+
print(f"Classes: {class_names}")
|
| 734 |
+
print(f"Paired lesions: train={len(train_df)}, val={len(val_df)}, total={len(df)}")
|
| 735 |
+
print(f"Metadata input dim: {metadata_dim}")
|
| 736 |
+
|
| 737 |
+
history: list[dict[str, Any]] = []
|
| 738 |
+
epoch, best_val_loss = train_phase(
|
| 739 |
+
"freeze",
|
| 740 |
+
args.freeze_epochs,
|
| 741 |
+
1,
|
| 742 |
+
model,
|
| 743 |
+
train_loader,
|
| 744 |
+
val_loader,
|
| 745 |
+
criterion,
|
| 746 |
+
device,
|
| 747 |
+
args,
|
| 748 |
+
class_names,
|
| 749 |
+
label_to_idx,
|
| 750 |
+
metadata_spec,
|
| 751 |
+
args.output_dir,
|
| 752 |
+
history,
|
| 753 |
+
float("inf"),
|
| 754 |
+
)
|
| 755 |
+
epoch, best_val_loss = train_phase(
|
| 756 |
+
"finetune",
|
| 757 |
+
args.finetune_epochs,
|
| 758 |
+
epoch,
|
| 759 |
+
model,
|
| 760 |
+
train_loader,
|
| 761 |
+
val_loader,
|
| 762 |
+
criterion,
|
| 763 |
+
device,
|
| 764 |
+
args,
|
| 765 |
+
class_names,
|
| 766 |
+
label_to_idx,
|
| 767 |
+
metadata_spec,
|
| 768 |
+
args.output_dir,
|
| 769 |
+
history,
|
| 770 |
+
best_val_loss,
|
| 771 |
+
)
|
| 772 |
+
|
| 773 |
+
best_path = args.output_dir / "best.pt"
|
| 774 |
+
if best_path.exists():
|
| 775 |
+
checkpoint = torch.load(best_path, map_location=device, weights_only=False)
|
| 776 |
+
model.load_state_dict(checkpoint["model_state"])
|
| 777 |
+
y_true, y_prob = predict(model, val_loader, device)
|
| 778 |
+
metrics, per_class_df, cm = compute_metrics(y_true, y_prob, class_names)
|
| 779 |
+
metrics = {"best_val_loss": float(best_val_loss), **metrics}
|
| 780 |
+
with open(args.output_dir / "metrics.json", "w", encoding="utf-8") as f:
|
| 781 |
+
json.dump(metrics, f, indent=2)
|
| 782 |
+
pd.DataFrame(cm, index=class_names, columns=class_names).to_csv(args.output_dir / "confusion_matrix.csv")
|
| 783 |
+
per_class_df.to_csv(args.output_dir / "per_class_metrics.csv", index=False)
|
| 784 |
+
save_predictions(val_df, y_true, y_prob, class_names, args.output_dir)
|
| 785 |
+
print(
|
| 786 |
+
f"Done: best_val_loss={best_val_loss:.4f}, "
|
| 787 |
+
f"val_acc={metrics['accuracy']:.4f}, balanced_acc={metrics['balanced_accuracy']:.4f}, "
|
| 788 |
+
f"f1_macro={metrics['f1_macro']:.4f}"
|
| 789 |
+
)
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
if __name__ == "__main__":
|
| 793 |
+
main()
|