Upload 171 files
Browse files- milk10k_effb2_metadata/__pycache__/__init__.cpython-310.pyc +0 -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__/datasets.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/engine.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/inference.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/losses.cpython-310.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__/model_setup.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/models.cpython-310.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/models.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/predict_milk10k_effb2_dual_metadata.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/reporting.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/runner.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/train_milk10k_effb2_dual_metadata.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/training.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/training_utils.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/checkpoints.py +2 -3
- milk10k_effb2_metadata/cli.py +58 -1
- milk10k_effb2_metadata/data.py +253 -10
- milk10k_effb2_metadata/engine.py +82 -6
- milk10k_effb2_metadata/inference.py +85 -8
- milk10k_effb2_metadata/losses.py +33 -1
- milk10k_effb2_metadata/metrics.py +33 -0
- milk10k_effb2_metadata/model_setup.py +19 -1
- milk10k_effb2_metadata/models.py +35 -4
- milk10k_effb2_metadata/reporting.py +27 -0
- milk10k_effb2_metadata/runner.py +320 -27
- milk10k_effb2_metadata/tests/__pycache__/test_fusion_and_f1_loss.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/training.py +53 -1
- milk10k_effb2_metadata/training_utils.py +1 -0
milk10k_effb2_metadata/__pycache__/__init__.cpython-310.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/__init__.cpython-310.pyc and b/milk10k_effb2_metadata/__pycache__/__init__.cpython-310.pyc differ
|
|
|
milk10k_effb2_metadata/__pycache__/__init__.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/__init__.cpython-314.pyc and b/milk10k_effb2_metadata/__pycache__/__init__.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/__pycache__/checkpoints.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/checkpoints.cpython-314.pyc and b/milk10k_effb2_metadata/__pycache__/checkpoints.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/__pycache__/cli.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/cli.cpython-314.pyc and b/milk10k_effb2_metadata/__pycache__/cli.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/__pycache__/data.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/data.cpython-314.pyc and b/milk10k_effb2_metadata/__pycache__/data.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/__pycache__/datasets.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/datasets.cpython-314.pyc and b/milk10k_effb2_metadata/__pycache__/datasets.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/__pycache__/engine.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/engine.cpython-314.pyc and b/milk10k_effb2_metadata/__pycache__/engine.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/__pycache__/inference.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/inference.cpython-314.pyc and b/milk10k_effb2_metadata/__pycache__/inference.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/__pycache__/losses.cpython-310.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/losses.cpython-310.pyc and b/milk10k_effb2_metadata/__pycache__/losses.cpython-310.pyc differ
|
|
|
milk10k_effb2_metadata/__pycache__/losses.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/losses.cpython-314.pyc and b/milk10k_effb2_metadata/__pycache__/losses.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/__pycache__/metrics.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/metrics.cpython-314.pyc and b/milk10k_effb2_metadata/__pycache__/metrics.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/__pycache__/model_setup.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/model_setup.cpython-314.pyc and b/milk10k_effb2_metadata/__pycache__/model_setup.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/__pycache__/models.cpython-310.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/models.cpython-310.pyc and b/milk10k_effb2_metadata/__pycache__/models.cpython-310.pyc differ
|
|
|
milk10k_effb2_metadata/__pycache__/models.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/models.cpython-314.pyc and b/milk10k_effb2_metadata/__pycache__/models.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/__pycache__/predict_milk10k_effb2_dual_metadata.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/predict_milk10k_effb2_dual_metadata.cpython-314.pyc and b/milk10k_effb2_metadata/__pycache__/predict_milk10k_effb2_dual_metadata.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/__pycache__/reporting.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/reporting.cpython-314.pyc and b/milk10k_effb2_metadata/__pycache__/reporting.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/__pycache__/runner.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/runner.cpython-314.pyc and b/milk10k_effb2_metadata/__pycache__/runner.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/__pycache__/train_milk10k_effb2_dual_metadata.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/train_milk10k_effb2_dual_metadata.cpython-314.pyc and b/milk10k_effb2_metadata/__pycache__/train_milk10k_effb2_dual_metadata.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/__pycache__/training.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/training.cpython-314.pyc and b/milk10k_effb2_metadata/__pycache__/training.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/__pycache__/training_utils.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/training_utils.cpython-314.pyc and b/milk10k_effb2_metadata/__pycache__/training_utils.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/checkpoints.py
CHANGED
|
@@ -9,8 +9,8 @@ from typing import Any
|
|
| 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]:
|
|
@@ -91,4 +91,3 @@ def load_encoder_checkpoint(path: Path, encoder: nn.Module, branch_name: str, de
|
|
| 91 |
target_state.update(matched)
|
| 92 |
encoder.load_state_dict(target_state)
|
| 93 |
print(f"{branch_name}: loaded {len(matched)} keys from {path}; skipped {skipped} keys")
|
| 94 |
-
|
|
|
|
| 9 |
import torch
|
| 10 |
from torch import nn
|
| 11 |
|
| 12 |
+
CHECKPOINT_STATE_KEYS = ("encoder_state_dict", "model_state", "model_state_dict", "state_dict")
|
| 13 |
+
PREFIXES_TO_STRIP = ("module.", "model.", "encoder.", "backbone.", "_orig_mod.")
|
| 14 |
|
| 15 |
|
| 16 |
def extract_state_dict(checkpoint: Any) -> dict[str, torch.Tensor]:
|
|
|
|
| 91 |
target_state.update(matched)
|
| 92 |
encoder.load_state_dict(target_state)
|
| 93 |
print(f"{branch_name}: loaded {len(matched)} keys from {path}; skipped {skipped} keys")
|
|
|
milk10k_effb2_metadata/cli.py
CHANGED
|
@@ -9,6 +9,18 @@ from pathlib import Path
|
|
| 9 |
def parse_args() -> argparse.Namespace:
|
| 10 |
parser = argparse.ArgumentParser(description="Train MILK10k dual-image backbones with metadata fusion.")
|
| 11 |
parser.add_argument("--data-dir", type=Path, default=None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
parser.add_argument(
|
| 13 |
"--clinical-checkpoint",
|
| 14 |
type=Path,
|
|
@@ -35,7 +47,10 @@ def parse_args() -> argparse.Namespace:
|
|
| 35 |
parser.add_argument(
|
| 36 |
"--backbone",
|
| 37 |
default="efficientnet_b2",
|
| 38 |
-
help=
|
|
|
|
|
|
|
|
|
|
| 39 |
)
|
| 40 |
parser.add_argument(
|
| 41 |
"--num-workers",
|
|
@@ -122,6 +137,15 @@ def parse_args() -> argparse.Namespace:
|
|
| 122 |
parser.add_argument("--branch-dim", type=int, default=512)
|
| 123 |
parser.add_argument("--metadata-dim", type=int, default=64)
|
| 124 |
parser.add_argument("--classifier-hidden-dim", type=int, default=512)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
parser.add_argument("--dropout", type=float, default=0.3)
|
| 126 |
parser.add_argument(
|
| 127 |
"--logit-fusion-mode",
|
|
@@ -135,6 +159,30 @@ def parse_args() -> argparse.Namespace:
|
|
| 135 |
parser.add_argument("--class-weight", action="store_true")
|
| 136 |
parser.add_argument("--weighted-sampler", action="store_true")
|
| 137 |
parser.add_argument("--sampler-power", type=float, default=1.0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
parser.add_argument("--loss", choices=["ce", "focal", "ldam", "ce_dice", "ce_f1"], default="ce")
|
| 139 |
parser.add_argument("--focal-gamma", type=float, default=2.0)
|
| 140 |
parser.add_argument("--dice-weight", type=float, default=0.3)
|
|
@@ -195,4 +243,13 @@ def parse_args() -> argparse.Namespace:
|
|
| 195 |
parser.add_argument("--calibration-step", type=float, default=0.25)
|
| 196 |
parser.add_argument("--calibration-passes", type=int, default=3)
|
| 197 |
parser.add_argument("--patience", type=int, default=6)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
return parser.parse_args()
|
|
|
|
| 9 |
def parse_args() -> argparse.Namespace:
|
| 10 |
parser = argparse.ArgumentParser(description="Train MILK10k dual-image backbones with metadata fusion.")
|
| 11 |
parser.add_argument("--data-dir", type=Path, default=None)
|
| 12 |
+
parser.add_argument(
|
| 13 |
+
"--dermoscopic-mask-dir",
|
| 14 |
+
type=Path,
|
| 15 |
+
default=None,
|
| 16 |
+
help="Optional directory containing <lesion_id>_dermoscopic_mask.png files.",
|
| 17 |
+
)
|
| 18 |
+
parser.add_argument(
|
| 19 |
+
"--min-dermoscopic-mask-ratio",
|
| 20 |
+
type=float,
|
| 21 |
+
default=0.01,
|
| 22 |
+
help="Fallback to the original dermoscopic image when mask foreground ratio is below this value.",
|
| 23 |
+
)
|
| 24 |
parser.add_argument(
|
| 25 |
"--clinical-checkpoint",
|
| 26 |
type=Path,
|
|
|
|
| 47 |
parser.add_argument(
|
| 48 |
"--backbone",
|
| 49 |
default="efficientnet_b2",
|
| 50 |
+
help=(
|
| 51 |
+
"Backbone model architecture (efficientnet_b2, tf_efficientnetv2_b2, "
|
| 52 |
+
"efficientnet_b1, resnet50, convnext_base)."
|
| 53 |
+
),
|
| 54 |
)
|
| 55 |
parser.add_argument(
|
| 56 |
"--num-workers",
|
|
|
|
| 137 |
parser.add_argument("--branch-dim", type=int, default=512)
|
| 138 |
parser.add_argument("--metadata-dim", type=int, default=64)
|
| 139 |
parser.add_argument("--classifier-hidden-dim", type=int, default=512)
|
| 140 |
+
parser.add_argument(
|
| 141 |
+
"--classifier-style",
|
| 142 |
+
choices=["legacy", "simple"],
|
| 143 |
+
default="legacy",
|
| 144 |
+
help=(
|
| 145 |
+
"Final fused classifier architecture. legacy keeps the existing LayerNorm/GELU head; "
|
| 146 |
+
"simple uses Linear-ReLU-Dropout-Linear."
|
| 147 |
+
),
|
| 148 |
+
)
|
| 149 |
parser.add_argument("--dropout", type=float, default=0.3)
|
| 150 |
parser.add_argument(
|
| 151 |
"--logit-fusion-mode",
|
|
|
|
| 159 |
parser.add_argument("--class-weight", action="store_true")
|
| 160 |
parser.add_argument("--weighted-sampler", action="store_true")
|
| 161 |
parser.add_argument("--sampler-power", type=float, default=1.0)
|
| 162 |
+
parser.add_argument(
|
| 163 |
+
"--balance-mode",
|
| 164 |
+
choices=["none", "hybrid"],
|
| 165 |
+
default="none",
|
| 166 |
+
help="Train-only epoch balancing. hybrid caps the largest class and mildly oversamples eligible tail classes.",
|
| 167 |
+
)
|
| 168 |
+
parser.add_argument(
|
| 169 |
+
"--balance-head-ratio",
|
| 170 |
+
type=float,
|
| 171 |
+
default=2.0,
|
| 172 |
+
help="In hybrid mode, cap the largest class at this multiple of the second-largest class.",
|
| 173 |
+
)
|
| 174 |
+
parser.add_argument(
|
| 175 |
+
"--balance-tail-floor",
|
| 176 |
+
type=int,
|
| 177 |
+
default=100,
|
| 178 |
+
help="In hybrid mode, oversample eligible classes below this count up to this many rows per epoch.",
|
| 179 |
+
)
|
| 180 |
+
parser.add_argument(
|
| 181 |
+
"--balance-min-source-count",
|
| 182 |
+
type=int,
|
| 183 |
+
default=20,
|
| 184 |
+
help="Do not oversample a class with fewer real train rows than this value.",
|
| 185 |
+
)
|
| 186 |
parser.add_argument("--loss", choices=["ce", "focal", "ldam", "ce_dice", "ce_f1"], default="ce")
|
| 187 |
parser.add_argument("--focal-gamma", type=float, default=2.0)
|
| 188 |
parser.add_argument("--dice-weight", type=float, default=0.3)
|
|
|
|
| 243 |
parser.add_argument("--calibration-step", type=float, default=0.25)
|
| 244 |
parser.add_argument("--calibration-passes", type=int, default=3)
|
| 245 |
parser.add_argument("--patience", type=int, default=6)
|
| 246 |
+
parser.add_argument("--tau", type=float, default=0.0, help="Generalized Balanced Softmax strength in [0, 0.5].")
|
| 247 |
+
parser.add_argument("--lws-epochs", type=int, default=0, help="Number of LWS post-training epochs; 0 disables LWS.")
|
| 248 |
+
parser.add_argument("--lws-lr", type=float, default=1e-2)
|
| 249 |
+
parser.add_argument("--lws-sampler-power", type=float, default=0.5)
|
| 250 |
+
parser.add_argument("--lws-min-scale", type=float, default=0.75)
|
| 251 |
+
parser.add_argument("--lws-max-scale", type=float, default=1.5)
|
| 252 |
+
parser.add_argument("--ema", action="store_true", help="Enable Exponential Moving Average (EMA) for model weights")
|
| 253 |
+
parser.add_argument("--ema-decay", type=float, default=0.999, help="Decay rate for EMA")
|
| 254 |
+
parser.add_argument("--fit-temperature", action="store_true", help="Fit one positive validation temperature per checkpoint variant.")
|
| 255 |
return parser.parse_args()
|
milk10k_effb2_metadata/data.py
CHANGED
|
@@ -11,7 +11,7 @@ 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
|
|
@@ -19,6 +19,110 @@ from datasets import LABEL_COLUMNS, normalize_image_type
|
|
| 19 |
ImageFile.LOAD_TRUNCATED_IMAGES = True
|
| 20 |
|
| 21 |
METADATA_COLUMNS = ("age_approx", "sex", "skin_tone_class", "site")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
|
| 24 |
class PairedMilk10kMetadataDataset(Dataset):
|
|
@@ -28,6 +132,8 @@ class PairedMilk10kMetadataDataset(Dataset):
|
|
| 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()]
|
|
@@ -36,24 +142,87 @@ class PairedMilk10kMetadataDataset(Dataset):
|
|
| 36 |
ignore_mask = self.df["ignore_metadata"].fillna(False).astype(bool).to_numpy()
|
| 37 |
self.metadata[ignore_mask] = 0.0
|
| 38 |
self.transform = transform
|
|
|
|
|
|
|
| 39 |
|
| 40 |
def __len__(self) -> int:
|
| 41 |
return len(self.df)
|
| 42 |
|
| 43 |
-
def _load_image(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
with Image.open(path) as img:
|
| 45 |
-
image =
|
| 46 |
-
|
| 47 |
-
|
|
|
|
| 48 |
return image
|
| 49 |
|
| 50 |
def __getitem__(self, idx: int) -> dict[str, torch.Tensor]:
|
| 51 |
row = self.df.iloc[idx]
|
|
|
|
|
|
|
| 52 |
return {
|
| 53 |
-
"clinical": self._load_image(row["clinical_path"]),
|
| 54 |
-
"dermoscopic": self._load_image(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
"metadata": torch.from_numpy(self.metadata[idx]),
|
| 56 |
-
"label": torch.tensor(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
}
|
| 58 |
|
| 59 |
|
|
@@ -229,6 +398,62 @@ def make_transforms(image_size: int):
|
|
| 229 |
return train_transform, eval_transform
|
| 230 |
|
| 231 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
def make_loaders(
|
| 233 |
train_df: pd.DataFrame,
|
| 234 |
val_df: pd.DataFrame,
|
|
@@ -237,7 +462,24 @@ def make_loaders(
|
|
| 237 |
args: argparse.Namespace,
|
| 238 |
) -> tuple[DataLoader, DataLoader]:
|
| 239 |
train_transform, eval_transform = make_transforms(args.image_size)
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
val_ds = PairedMilk10kMetadataDataset(val_df, label_to_idx, metadata_spec, eval_transform)
|
| 242 |
common = dict(
|
| 243 |
batch_size=args.batch_size,
|
|
@@ -245,7 +487,8 @@ def make_loaders(
|
|
| 245 |
pin_memory=torch.cuda.is_available(),
|
| 246 |
drop_last=False,
|
| 247 |
)
|
| 248 |
-
|
|
|
|
| 249 |
train_loader = DataLoader(train_ds, shuffle=sampler is None, sampler=sampler, **common)
|
| 250 |
val_loader = DataLoader(val_ds, shuffle=False, **common)
|
| 251 |
return train_loader, val_loader
|
|
|
|
| 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, Sampler, WeightedRandomSampler
|
| 15 |
from torchvision import transforms
|
| 16 |
|
| 17 |
from datasets import LABEL_COLUMNS, normalize_image_type
|
|
|
|
| 19 |
ImageFile.LOAD_TRUNCATED_IMAGES = True
|
| 20 |
|
| 21 |
METADATA_COLUMNS = ("age_approx", "sex", "skin_tone_class", "site")
|
| 22 |
+
DERMOSCOPIC_MASK_PATH_COLUMN = "dermoscopic_mask_path"
|
| 23 |
+
DERMOSCOPIC_MASK_RATIO_COLUMN = "dermoscopic_mask_ratio"
|
| 24 |
+
DERMOSCOPIC_MASK_STATUS_COLUMN = "dermoscopic_mask_status"
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def apply_dermoscopic_mask(image: Image.Image, mask_path: str | Path | None) -> Image.Image:
|
| 28 |
+
"""Return an RGB image with non-mask pixels black, or the original RGB image on read failure."""
|
| 29 |
+
image = image.convert("RGB")
|
| 30 |
+
if not isinstance(mask_path, (str, Path)) or not str(mask_path):
|
| 31 |
+
return image
|
| 32 |
+
try:
|
| 33 |
+
with Image.open(mask_path) as mask_image:
|
| 34 |
+
mask = mask_image.convert("L")
|
| 35 |
+
if mask.size != image.size:
|
| 36 |
+
return image
|
| 37 |
+
binary_mask = mask.point(lambda value: 255 if value else 0)
|
| 38 |
+
return Image.composite(image, Image.new("RGB", image.size), binary_mask)
|
| 39 |
+
except (OSError, ValueError):
|
| 40 |
+
return image
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def audit_dermoscopic_masks(
|
| 44 |
+
df: pd.DataFrame,
|
| 45 |
+
mask_dir: Path,
|
| 46 |
+
min_foreground_ratio: float = 0.01,
|
| 47 |
+
mask_id_column: str = "lesion_id",
|
| 48 |
+
mask_suffix: str = "_dermoscopic_mask.png",
|
| 49 |
+
) -> tuple[pd.DataFrame, pd.DataFrame]:
|
| 50 |
+
"""Attach valid mask paths and return one audit row per paired dermoscopic image."""
|
| 51 |
+
if not 0.0 <= min_foreground_ratio <= 1.0:
|
| 52 |
+
raise ValueError("--min-dermoscopic-mask-ratio must be between 0 and 1.")
|
| 53 |
+
mask_dir = mask_dir.expanduser().resolve()
|
| 54 |
+
if not mask_dir.is_dir():
|
| 55 |
+
raise FileNotFoundError(f"Dermoscopic mask directory does not exist: {mask_dir}")
|
| 56 |
+
if mask_id_column not in df.columns:
|
| 57 |
+
raise ValueError(f"Mask ID column is missing from dataframe: {mask_id_column}")
|
| 58 |
+
|
| 59 |
+
audited_df = df.copy()
|
| 60 |
+
mask_paths: list[str | None] = []
|
| 61 |
+
ratios: list[float | None] = []
|
| 62 |
+
statuses: list[str] = []
|
| 63 |
+
audit_rows: list[dict[str, Any]] = []
|
| 64 |
+
|
| 65 |
+
for _, row in audited_df.iterrows():
|
| 66 |
+
lesion_id = str(row["lesion_id"])
|
| 67 |
+
mask_id = str(row[mask_id_column])
|
| 68 |
+
image_path = Path(row["dermoscopic_path"])
|
| 69 |
+
mask_path = mask_dir / f"{mask_id}{mask_suffix}"
|
| 70 |
+
ratio: float | None = None
|
| 71 |
+
status = "valid"
|
| 72 |
+
image_size: tuple[int, int] | None = None
|
| 73 |
+
mask_size: tuple[int, int] | None = None
|
| 74 |
+
|
| 75 |
+
if not mask_path.is_file():
|
| 76 |
+
status = "missing"
|
| 77 |
+
else:
|
| 78 |
+
try:
|
| 79 |
+
with Image.open(image_path) as image:
|
| 80 |
+
image_size = image.size
|
| 81 |
+
with Image.open(mask_path) as mask_image:
|
| 82 |
+
mask = mask_image.convert("L")
|
| 83 |
+
mask.load()
|
| 84 |
+
mask_size = mask.size
|
| 85 |
+
histogram = mask.histogram()
|
| 86 |
+
total_pixels = mask.width * mask.height
|
| 87 |
+
ratio = (total_pixels - histogram[0]) / total_pixels if total_pixels else 0.0
|
| 88 |
+
if mask_size != image_size:
|
| 89 |
+
status = "size_mismatch"
|
| 90 |
+
elif ratio < min_foreground_ratio:
|
| 91 |
+
status = "too_small"
|
| 92 |
+
except (OSError, ValueError):
|
| 93 |
+
status = "unreadable"
|
| 94 |
+
|
| 95 |
+
valid_path = str(mask_path) if status == "valid" else None
|
| 96 |
+
mask_paths.append(valid_path)
|
| 97 |
+
ratios.append(ratio)
|
| 98 |
+
statuses.append(status)
|
| 99 |
+
audit_rows.append(
|
| 100 |
+
{
|
| 101 |
+
"lesion_id": lesion_id,
|
| 102 |
+
"mask_id": mask_id,
|
| 103 |
+
"dermoscopic_path": str(image_path),
|
| 104 |
+
"mask_path": str(mask_path),
|
| 105 |
+
"foreground_ratio": ratio,
|
| 106 |
+
"status": status,
|
| 107 |
+
"image_size": None if image_size is None else f"{image_size[0]}x{image_size[1]}",
|
| 108 |
+
"mask_size": None if mask_size is None else f"{mask_size[0]}x{mask_size[1]}",
|
| 109 |
+
}
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
audited_df[DERMOSCOPIC_MASK_PATH_COLUMN] = mask_paths
|
| 113 |
+
audited_df[DERMOSCOPIC_MASK_RATIO_COLUMN] = ratios
|
| 114 |
+
audited_df[DERMOSCOPIC_MASK_STATUS_COLUMN] = statuses
|
| 115 |
+
return audited_df, pd.DataFrame(audit_rows)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def print_mask_audit_summary(audit_df: pd.DataFrame, min_foreground_ratio: float) -> None:
|
| 119 |
+
counts = audit_df["status"].value_counts().sort_index().to_dict()
|
| 120 |
+
valid = int(counts.get("valid", 0))
|
| 121 |
+
print(
|
| 122 |
+
"Dermoscopic masks: "
|
| 123 |
+
f"total={len(audit_df)}, valid={valid}, fallback={len(audit_df) - valid}, "
|
| 124 |
+
f"min_foreground_ratio={min_foreground_ratio:.6f}, status_counts={counts}"
|
| 125 |
+
)
|
| 126 |
|
| 127 |
|
| 128 |
class PairedMilk10kMetadataDataset(Dataset):
|
|
|
|
| 132 |
label_to_idx: dict[str, int],
|
| 133 |
metadata_spec: dict[str, Any],
|
| 134 |
transform=None,
|
| 135 |
+
strong_transform=None,
|
| 136 |
+
strong_augment_labels: set[int] | None = None,
|
| 137 |
) -> None:
|
| 138 |
self.df = df.reset_index(drop=True)
|
| 139 |
self.labels = [label_to_idx[label] for label in self.df["label"].tolist()]
|
|
|
|
| 142 |
ignore_mask = self.df["ignore_metadata"].fillna(False).astype(bool).to_numpy()
|
| 143 |
self.metadata[ignore_mask] = 0.0
|
| 144 |
self.transform = transform
|
| 145 |
+
self.strong_transform = strong_transform
|
| 146 |
+
self.strong_augment_labels = strong_augment_labels or set()
|
| 147 |
|
| 148 |
def __len__(self) -> int:
|
| 149 |
return len(self.df)
|
| 150 |
|
| 151 |
+
def _load_image(
|
| 152 |
+
self,
|
| 153 |
+
path: str,
|
| 154 |
+
mask_path: str | Path | None = None,
|
| 155 |
+
transform=None,
|
| 156 |
+
) -> torch.Tensor:
|
| 157 |
with Image.open(path) as img:
|
| 158 |
+
image = apply_dermoscopic_mask(img, mask_path)
|
| 159 |
+
transform = self.transform if transform is None else transform
|
| 160 |
+
if transform is not None:
|
| 161 |
+
image = transform(image)
|
| 162 |
return image
|
| 163 |
|
| 164 |
def __getitem__(self, idx: int) -> dict[str, torch.Tensor]:
|
| 165 |
row = self.df.iloc[idx]
|
| 166 |
+
label = self.labels[idx]
|
| 167 |
+
transform = self.strong_transform if label in self.strong_augment_labels else self.transform
|
| 168 |
return {
|
| 169 |
+
"clinical": self._load_image(row["clinical_path"], transform=transform),
|
| 170 |
+
"dermoscopic": self._load_image(
|
| 171 |
+
row["dermoscopic_path"],
|
| 172 |
+
row.get(DERMOSCOPIC_MASK_PATH_COLUMN),
|
| 173 |
+
transform,
|
| 174 |
+
),
|
| 175 |
"metadata": torch.from_numpy(self.metadata[idx]),
|
| 176 |
+
"label": torch.tensor(label, dtype=torch.long),
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class HybridEpochSampler(Sampler[int]):
|
| 181 |
+
"""Cap the largest class and oversample eligible tail classes per epoch."""
|
| 182 |
+
|
| 183 |
+
def __init__(
|
| 184 |
+
self,
|
| 185 |
+
labels: list[int],
|
| 186 |
+
target_counts: np.ndarray,
|
| 187 |
+
seed: int,
|
| 188 |
+
label_names: dict[int, str] | None = None,
|
| 189 |
+
) -> None:
|
| 190 |
+
self.labels = np.asarray(labels, dtype=np.int64)
|
| 191 |
+
self.target_counts = np.asarray(target_counts, dtype=np.int64)
|
| 192 |
+
self.seed = int(seed)
|
| 193 |
+
self.epoch = 0
|
| 194 |
+
self.label_names = label_names or {}
|
| 195 |
+
self.class_indices = [np.flatnonzero(self.labels == idx) for idx in range(len(self.target_counts))]
|
| 196 |
+
self.original_counts = np.asarray([len(indices) for indices in self.class_indices], dtype=np.int64)
|
| 197 |
+
|
| 198 |
+
def __len__(self) -> int:
|
| 199 |
+
return int(self.target_counts.sum())
|
| 200 |
+
|
| 201 |
+
def set_epoch(self, epoch: int) -> None:
|
| 202 |
+
self.epoch = int(epoch)
|
| 203 |
+
|
| 204 |
+
def __iter__(self):
|
| 205 |
+
generator = torch.Generator().manual_seed(self.seed + self.epoch)
|
| 206 |
+
selected: list[torch.Tensor] = []
|
| 207 |
+
for indices, target in zip(self.class_indices, self.target_counts):
|
| 208 |
+
source = torch.as_tensor(indices, dtype=torch.long)
|
| 209 |
+
target = int(target)
|
| 210 |
+
if target <= len(source):
|
| 211 |
+
selected.append(source[torch.randperm(len(source), generator=generator)[:target]])
|
| 212 |
+
continue
|
| 213 |
+
full_repeats, remainder = divmod(target, len(source))
|
| 214 |
+
chunks = [source[torch.randperm(len(source), generator=generator)] for _ in range(full_repeats)]
|
| 215 |
+
if remainder:
|
| 216 |
+
chunks.append(source[torch.randperm(len(source), generator=generator)[:remainder]])
|
| 217 |
+
selected.append(torch.cat(chunks))
|
| 218 |
+
epoch_indices = torch.cat(selected)
|
| 219 |
+
order = torch.randperm(len(epoch_indices), generator=generator)
|
| 220 |
+
return iter(epoch_indices[order].tolist())
|
| 221 |
+
|
| 222 |
+
def exposure_summary(self) -> dict[str, int]:
|
| 223 |
+
return {
|
| 224 |
+
self.label_names.get(idx, str(idx)): int(count)
|
| 225 |
+
for idx, count in enumerate(self.target_counts)
|
| 226 |
}
|
| 227 |
|
| 228 |
|
|
|
|
| 398 |
return train_transform, eval_transform
|
| 399 |
|
| 400 |
|
| 401 |
+
def make_strong_train_transform(image_size: int):
|
| 402 |
+
"""A conservative stronger variant used only for oversampled tail classes."""
|
| 403 |
+
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
| 404 |
+
return transforms.Compose(
|
| 405 |
+
[
|
| 406 |
+
transforms.RandomResizedCrop(image_size, scale=(0.65, 1.0), ratio=(1.15, 1.5)),
|
| 407 |
+
transforms.RandomHorizontalFlip(),
|
| 408 |
+
transforms.RandomVerticalFlip(),
|
| 409 |
+
transforms.RandomRotation(30),
|
| 410 |
+
transforms.ColorJitter(brightness=0.3, contrast=0.3, saturation=0.25),
|
| 411 |
+
transforms.RandomAffine(degrees=0, translate=(0.05, 0.05), scale=(0.95, 1.05)),
|
| 412 |
+
transforms.ToTensor(),
|
| 413 |
+
normalize,
|
| 414 |
+
]
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def hybrid_target_counts(labels: list[int], args: argparse.Namespace) -> tuple[np.ndarray, set[int]]:
|
| 419 |
+
"""Return per-class epoch targets and classes eligible for strong augmentation."""
|
| 420 |
+
counts = np.bincount(np.asarray(labels, dtype=np.int64))
|
| 421 |
+
if np.any(counts == 0):
|
| 422 |
+
raise ValueError("Cannot build hybrid sampler because at least one class has zero training samples.")
|
| 423 |
+
targets = counts.copy()
|
| 424 |
+
|
| 425 |
+
if len(counts) >= 2:
|
| 426 |
+
descending = np.argsort(-counts, kind="stable")
|
| 427 |
+
head_idx, second_idx = int(descending[0]), int(descending[1])
|
| 428 |
+
head_cap = max(1, int(np.floor(counts[second_idx] * args.balance_head_ratio)))
|
| 429 |
+
targets[head_idx] = min(int(counts[head_idx]), head_cap)
|
| 430 |
+
|
| 431 |
+
strong_labels: set[int] = set()
|
| 432 |
+
for idx, count in enumerate(counts):
|
| 433 |
+
if args.balance_min_source_count <= count < args.balance_tail_floor:
|
| 434 |
+
targets[idx] = args.balance_tail_floor
|
| 435 |
+
strong_labels.add(idx)
|
| 436 |
+
return targets, strong_labels
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def hybrid_balance_summary(
|
| 440 |
+
labels: list[int],
|
| 441 |
+
label_names: dict[int, str],
|
| 442 |
+
args: argparse.Namespace,
|
| 443 |
+
) -> dict[str, Any]:
|
| 444 |
+
counts = np.bincount(np.asarray(labels, dtype=np.int64))
|
| 445 |
+
targets, strong_labels = hybrid_target_counts(labels, args)
|
| 446 |
+
return {
|
| 447 |
+
"mode": "hybrid",
|
| 448 |
+
"original_class_counts": {label_names[idx]: int(count) for idx, count in enumerate(counts)},
|
| 449 |
+
"effective_class_counts_per_epoch": {
|
| 450 |
+
label_names[idx]: int(count) for idx, count in enumerate(targets)
|
| 451 |
+
},
|
| 452 |
+
"strong_augmentation_classes": [label_names[idx] for idx in sorted(strong_labels)],
|
| 453 |
+
"effective_rows_per_epoch": int(targets.sum()),
|
| 454 |
+
}
|
| 455 |
+
|
| 456 |
+
|
| 457 |
def make_loaders(
|
| 458 |
train_df: pd.DataFrame,
|
| 459 |
val_df: pd.DataFrame,
|
|
|
|
| 462 |
args: argparse.Namespace,
|
| 463 |
) -> tuple[DataLoader, DataLoader]:
|
| 464 |
train_transform, eval_transform = make_transforms(args.image_size)
|
| 465 |
+
label_names = {idx: label for label, idx in label_to_idx.items()}
|
| 466 |
+
train_labels = [label_to_idx[label] for label in train_df["label"].tolist()]
|
| 467 |
+
sampler = None
|
| 468 |
+
strong_transform = None
|
| 469 |
+
strong_labels: set[int] = set()
|
| 470 |
+
if args.balance_mode == "hybrid":
|
| 471 |
+
targets, strong_labels = hybrid_target_counts(train_labels, args)
|
| 472 |
+
sampler = HybridEpochSampler(train_labels, targets, args.seed, label_names)
|
| 473 |
+
strong_transform = make_strong_train_transform(args.image_size)
|
| 474 |
+
|
| 475 |
+
train_ds = PairedMilk10kMetadataDataset(
|
| 476 |
+
train_df,
|
| 477 |
+
label_to_idx,
|
| 478 |
+
metadata_spec,
|
| 479 |
+
train_transform,
|
| 480 |
+
strong_transform=strong_transform,
|
| 481 |
+
strong_augment_labels=strong_labels,
|
| 482 |
+
)
|
| 483 |
val_ds = PairedMilk10kMetadataDataset(val_df, label_to_idx, metadata_spec, eval_transform)
|
| 484 |
common = dict(
|
| 485 |
batch_size=args.batch_size,
|
|
|
|
| 487 |
pin_memory=torch.cuda.is_available(),
|
| 488 |
drop_last=False,
|
| 489 |
)
|
| 490 |
+
if args.weighted_sampler:
|
| 491 |
+
sampler = build_weighted_sampler(train_ds, args)
|
| 492 |
train_loader = DataLoader(train_ds, shuffle=sampler is None, sampler=sampler, **common)
|
| 493 |
val_loader = DataLoader(val_ds, shuffle=False, **common)
|
| 494 |
return train_loader, val_loader
|
milk10k_effb2_metadata/engine.py
CHANGED
|
@@ -35,9 +35,11 @@ def run_epoch(
|
|
| 35 |
use_amp: bool = False,
|
| 36 |
tail_class_indices: list[int] | None = None,
|
| 37 |
class_names: list[str] | None = None,
|
|
|
|
| 38 |
) -> dict[str, float]:
|
| 39 |
training = optimizer is not None
|
| 40 |
model.train(training)
|
|
|
|
| 41 |
total_loss = 0.0
|
| 42 |
correct = 0
|
| 43 |
top3_correct = 0
|
|
@@ -65,6 +67,8 @@ def run_epoch(
|
|
| 65 |
loss.backward()
|
| 66 |
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
|
| 67 |
optimizer.step()
|
|
|
|
|
|
|
| 68 |
|
| 69 |
batch_size = labels.size(0)
|
| 70 |
total_loss += float(loss.detach().item()) * batch_size
|
|
@@ -161,6 +165,7 @@ def save_checkpoint(
|
|
| 161 |
metadata_spec: dict[str, Any],
|
| 162 |
args: argparse.Namespace,
|
| 163 |
extra: dict[str, Any] | None = None,
|
|
|
|
| 164 |
) -> None:
|
| 165 |
payload = {
|
| 166 |
"epoch": epoch,
|
|
@@ -176,6 +181,8 @@ def save_checkpoint(
|
|
| 176 |
"metadata_spec": metadata_spec,
|
| 177 |
"args": json_safe(vars(args)),
|
| 178 |
}
|
|
|
|
|
|
|
| 179 |
if extra:
|
| 180 |
payload.update(json_safe(extra))
|
| 181 |
torch.save(payload, path)
|
|
@@ -202,9 +209,12 @@ def train_phase(
|
|
| 202 |
tail_class_names: list[str] | None = None,
|
| 203 |
train_class_counts: dict[str, int] | None = None,
|
| 204 |
best_val_tail_recall: float = float("-inf"),
|
| 205 |
-
|
|
|
|
|
|
|
|
|
|
| 206 |
if num_epochs <= 0:
|
| 207 |
-
return start_epoch, best_val_f1, best_val_tail_recall
|
| 208 |
|
| 209 |
encoders_trainable = phase == "finetune"
|
| 210 |
set_encoder_trainable(model, encoders_trainable)
|
|
@@ -222,6 +232,11 @@ def train_phase(
|
|
| 222 |
continue
|
| 223 |
if hasattr(criterion, "set_epoch"):
|
| 224 |
criterion.set_epoch(epoch)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
train_stats = run_epoch(
|
| 226 |
model,
|
| 227 |
train_loader,
|
|
@@ -232,8 +247,9 @@ def train_phase(
|
|
| 232 |
use_amp,
|
| 233 |
tail_class_indices,
|
| 234 |
class_names,
|
|
|
|
| 235 |
)
|
| 236 |
-
|
| 237 |
model,
|
| 238 |
val_loader,
|
| 239 |
criterion,
|
|
@@ -241,14 +257,32 @@ def train_phase(
|
|
| 241 |
tail_class_indices=tail_class_indices,
|
| 242 |
class_names=class_names,
|
| 243 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
selection_metric = args.selection_metric
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
scheduler.step(val_stats[selection_metric])
|
| 246 |
row = {
|
| 247 |
"phase": phase,
|
| 248 |
"epoch": epoch,
|
| 249 |
**{f"train_{key}": value for key, value in train_stats.items()},
|
| 250 |
**{f"val_{key}": value for key, value in val_stats.items()},
|
|
|
|
| 251 |
}
|
|
|
|
|
|
|
|
|
|
| 252 |
history.append(row)
|
| 253 |
pd.DataFrame(history).to_csv(output_dir / "history.csv", index=False)
|
| 254 |
print(
|
|
@@ -257,8 +291,26 @@ def train_phase(
|
|
| 257 |
f"train_bal_acc={train_stats['balanced_accuracy']:.4f} train_f1={train_stats['f1_macro']:.4f} "
|
| 258 |
f"val_acc={val_stats['accuracy']:.4f} val_bal_acc={val_stats['balanced_accuracy']:.4f} "
|
| 259 |
f"val_f1={val_stats['f1_macro']:.4f} val_dice={val_stats.get('dice_macro', 0.0):.4f} "
|
| 260 |
-
f"val_top3={val_stats['top3_accuracy']:.4f}"
|
| 261 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
if tail_class_indices:
|
| 263 |
print(
|
| 264 |
f"LDAM tail: classes={tail_class_names} "
|
|
@@ -274,7 +326,7 @@ def train_phase(
|
|
| 274 |
patience_count = 0
|
| 275 |
save_checkpoint(
|
| 276 |
output_dir / "best.pt",
|
| 277 |
-
|
| 278 |
optimizer,
|
| 279 |
epoch,
|
| 280 |
phase,
|
|
@@ -283,6 +335,7 @@ def train_phase(
|
|
| 283 |
label_to_idx,
|
| 284 |
metadata_spec,
|
| 285 |
args,
|
|
|
|
| 286 |
)
|
| 287 |
print(
|
| 288 |
f"Saved best checkpoint: phase={phase} epoch={epoch:03d} "
|
|
@@ -311,14 +364,37 @@ def train_phase(
|
|
| 311 |
"train_class_counts": train_class_counts or {},
|
| 312 |
"selection_metric": "val_tail_recall_macro",
|
| 313 |
},
|
|
|
|
| 314 |
)
|
| 315 |
print(
|
| 316 |
f"Saved tail checkpoint: phase={phase} epoch={epoch:03d} "
|
| 317 |
f"best_val_tail_recall_macro={best_val_tail_recall:.4f} path={output_dir / 'tail_best.pt'}"
|
| 318 |
)
|
| 319 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 320 |
if patience_count >= args.patience:
|
| 321 |
print(f"Early stopping {phase} at epoch {epoch}")
|
| 322 |
break
|
| 323 |
|
| 324 |
-
return epoch + 1, best_val_f1, best_val_tail_recall
|
|
|
|
| 35 |
use_amp: bool = False,
|
| 36 |
tail_class_indices: list[int] | None = None,
|
| 37 |
class_names: list[str] | None = None,
|
| 38 |
+
ema_model: nn.Module | None = None,
|
| 39 |
) -> dict[str, float]:
|
| 40 |
training = optimizer is not None
|
| 41 |
model.train(training)
|
| 42 |
+
criterion.train(training)
|
| 43 |
total_loss = 0.0
|
| 44 |
correct = 0
|
| 45 |
top3_correct = 0
|
|
|
|
| 67 |
loss.backward()
|
| 68 |
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
|
| 69 |
optimizer.step()
|
| 70 |
+
if ema_model is not None:
|
| 71 |
+
ema_model.update_parameters(model)
|
| 72 |
|
| 73 |
batch_size = labels.size(0)
|
| 74 |
total_loss += float(loss.detach().item()) * batch_size
|
|
|
|
| 165 |
metadata_spec: dict[str, Any],
|
| 166 |
args: argparse.Namespace,
|
| 167 |
extra: dict[str, Any] | None = None,
|
| 168 |
+
ema_model: nn.Module | None = None,
|
| 169 |
) -> None:
|
| 170 |
payload = {
|
| 171 |
"epoch": epoch,
|
|
|
|
| 181 |
"metadata_spec": metadata_spec,
|
| 182 |
"args": json_safe(vars(args)),
|
| 183 |
}
|
| 184 |
+
if ema_model is not None:
|
| 185 |
+
payload["ema_model_state"] = ema_model.state_dict()
|
| 186 |
if extra:
|
| 187 |
payload.update(json_safe(extra))
|
| 188 |
torch.save(payload, path)
|
|
|
|
| 209 |
tail_class_names: list[str] | None = None,
|
| 210 |
train_class_counts: dict[str, int] | None = None,
|
| 211 |
best_val_tail_recall: float = float("-inf"),
|
| 212 |
+
ema_model: nn.Module | None = None,
|
| 213 |
+
variant_best: dict[str, float] | None = None,
|
| 214 |
+
) -> tuple[int, float, float, dict[str, float]]:
|
| 215 |
+
variant_best = variant_best if variant_best is not None else {"raw": float("-inf"), "ema": float("-inf")}
|
| 216 |
if num_epochs <= 0:
|
| 217 |
+
return start_epoch, best_val_f1, best_val_tail_recall, variant_best
|
| 218 |
|
| 219 |
encoders_trainable = phase == "finetune"
|
| 220 |
set_encoder_trainable(model, encoders_trainable)
|
|
|
|
| 232 |
continue
|
| 233 |
if hasattr(criterion, "set_epoch"):
|
| 234 |
criterion.set_epoch(epoch)
|
| 235 |
+
sampler = getattr(train_loader, "sampler", None)
|
| 236 |
+
if hasattr(sampler, "set_epoch"):
|
| 237 |
+
sampler.set_epoch(epoch)
|
| 238 |
+
if hasattr(sampler, "exposure_summary"):
|
| 239 |
+
print(f"Hybrid balance epoch {epoch:03d}: effective_class_counts={sampler.exposure_summary()}")
|
| 240 |
train_stats = run_epoch(
|
| 241 |
model,
|
| 242 |
train_loader,
|
|
|
|
| 247 |
use_amp,
|
| 248 |
tail_class_indices,
|
| 249 |
class_names,
|
| 250 |
+
ema_model=ema_model,
|
| 251 |
)
|
| 252 |
+
raw_val_stats = run_epoch(
|
| 253 |
model,
|
| 254 |
val_loader,
|
| 255 |
criterion,
|
|
|
|
| 257 |
tail_class_indices=tail_class_indices,
|
| 258 |
class_names=class_names,
|
| 259 |
)
|
| 260 |
+
ema_val_stats = None
|
| 261 |
+
if ema_model is not None:
|
| 262 |
+
ema_val_stats = run_epoch(
|
| 263 |
+
ema_model,
|
| 264 |
+
val_loader,
|
| 265 |
+
criterion,
|
| 266 |
+
device,
|
| 267 |
+
tail_class_indices=tail_class_indices,
|
| 268 |
+
class_names=class_names,
|
| 269 |
+
)
|
| 270 |
selection_metric = args.selection_metric
|
| 271 |
+
candidates = [("raw", raw_val_stats, model)]
|
| 272 |
+
if ema_val_stats is not None:
|
| 273 |
+
candidates.append(("ema", ema_val_stats, ema_model.module))
|
| 274 |
+
epoch_variant, val_stats, epoch_model = max(candidates, key=lambda item: item[1][selection_metric])
|
| 275 |
scheduler.step(val_stats[selection_metric])
|
| 276 |
row = {
|
| 277 |
"phase": phase,
|
| 278 |
"epoch": epoch,
|
| 279 |
**{f"train_{key}": value for key, value in train_stats.items()},
|
| 280 |
**{f"val_{key}": value for key, value in val_stats.items()},
|
| 281 |
+
**{f"val_raw_{key}": value for key, value in raw_val_stats.items()},
|
| 282 |
}
|
| 283 |
+
if ema_val_stats is not None:
|
| 284 |
+
row.update({f"val_ema_{key}": value for key, value in ema_val_stats.items()})
|
| 285 |
+
row["selected_variant"] = epoch_variant
|
| 286 |
history.append(row)
|
| 287 |
pd.DataFrame(history).to_csv(output_dir / "history.csv", index=False)
|
| 288 |
print(
|
|
|
|
| 291 |
f"train_bal_acc={train_stats['balanced_accuracy']:.4f} train_f1={train_stats['f1_macro']:.4f} "
|
| 292 |
f"val_acc={val_stats['accuracy']:.4f} val_bal_acc={val_stats['balanced_accuracy']:.4f} "
|
| 293 |
f"val_f1={val_stats['f1_macro']:.4f} val_dice={val_stats.get('dice_macro', 0.0):.4f} "
|
| 294 |
+
f"val_top3={val_stats['top3_accuracy']:.4f} selected={epoch_variant}"
|
| 295 |
)
|
| 296 |
+
for variant, stats, variant_model in candidates:
|
| 297 |
+
if stats[selection_metric] <= variant_best.get(variant, float("-inf")):
|
| 298 |
+
continue
|
| 299 |
+
variant_best[variant] = float(stats[selection_metric])
|
| 300 |
+
save_checkpoint(
|
| 301 |
+
output_dir / f"best_{variant}.pt",
|
| 302 |
+
variant_model,
|
| 303 |
+
optimizer,
|
| 304 |
+
epoch,
|
| 305 |
+
phase,
|
| 306 |
+
variant_best[variant],
|
| 307 |
+
class_names,
|
| 308 |
+
label_to_idx,
|
| 309 |
+
metadata_spec,
|
| 310 |
+
args,
|
| 311 |
+
{"checkpoint_variant": variant, "variant_val_stats": stats},
|
| 312 |
+
)
|
| 313 |
+
print(f"Saved best {variant}: {selection_metric}={variant_best[variant]:.4f}")
|
| 314 |
if tail_class_indices:
|
| 315 |
print(
|
| 316 |
f"LDAM tail: classes={tail_class_names} "
|
|
|
|
| 326 |
patience_count = 0
|
| 327 |
save_checkpoint(
|
| 328 |
output_dir / "best.pt",
|
| 329 |
+
epoch_model,
|
| 330 |
optimizer,
|
| 331 |
epoch,
|
| 332 |
phase,
|
|
|
|
| 335 |
label_to_idx,
|
| 336 |
metadata_spec,
|
| 337 |
args,
|
| 338 |
+
extra={"checkpoint_variant": epoch_variant, "variant_val_stats": val_stats},
|
| 339 |
)
|
| 340 |
print(
|
| 341 |
f"Saved best checkpoint: phase={phase} epoch={epoch:03d} "
|
|
|
|
| 364 |
"train_class_counts": train_class_counts or {},
|
| 365 |
"selection_metric": "val_tail_recall_macro",
|
| 366 |
},
|
| 367 |
+
ema_model=ema_model,
|
| 368 |
)
|
| 369 |
print(
|
| 370 |
f"Saved tail checkpoint: phase={phase} epoch={epoch:03d} "
|
| 371 |
f"best_val_tail_recall_macro={best_val_tail_recall:.4f} path={output_dir / 'tail_best.pt'}"
|
| 372 |
)
|
| 373 |
|
| 374 |
+
save_checkpoint(
|
| 375 |
+
output_dir / "last.pt",
|
| 376 |
+
model,
|
| 377 |
+
optimizer,
|
| 378 |
+
epoch,
|
| 379 |
+
phase,
|
| 380 |
+
best_val_f1,
|
| 381 |
+
class_names,
|
| 382 |
+
label_to_idx,
|
| 383 |
+
metadata_spec,
|
| 384 |
+
args,
|
| 385 |
+
{
|
| 386 |
+
"last_selection_metric": float(val_stats[selection_metric]),
|
| 387 |
+
"last_val_stats": val_stats,
|
| 388 |
+
},
|
| 389 |
+
ema_model=ema_model,
|
| 390 |
+
)
|
| 391 |
+
print(
|
| 392 |
+
f"Saved last checkpoint: phase={phase} epoch={epoch:03d} "
|
| 393 |
+
f"{selection_metric}={val_stats[selection_metric]:.4f} path={output_dir / 'last.pt'}"
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
if patience_count >= args.patience:
|
| 397 |
print(f"Early stopping {phase} at epoch {epoch}")
|
| 398 |
break
|
| 399 |
|
| 400 |
+
return epoch + 1, best_val_f1, best_val_tail_recall, variant_best
|
milk10k_effb2_metadata/inference.py
CHANGED
|
@@ -15,8 +15,18 @@ from torch.utils.data import DataLoader, Dataset
|
|
| 15 |
from tqdm.auto import tqdm
|
| 16 |
|
| 17 |
from datasets import LABEL_COLUMNS, normalize_image_type
|
| 18 |
-
from milk10k_effb2_metadata.data import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
from milk10k_effb2_metadata.metrics import apply_class_bias, compute_metrics
|
|
|
|
| 20 |
from milk10k_effb2_metadata.models import (
|
| 21 |
DualEffB2MetadataClassifier,
|
| 22 |
model_class_for_backbone,
|
|
@@ -35,9 +45,9 @@ class InferencePairedDataset(Dataset):
|
|
| 35 |
def __len__(self) -> int:
|
| 36 |
return len(self.df)
|
| 37 |
|
| 38 |
-
def _load_image(self, path: str) -> torch.Tensor:
|
| 39 |
with Image.open(path) as img:
|
| 40 |
-
image =
|
| 41 |
if self.transform is not None:
|
| 42 |
image = self.transform(image)
|
| 43 |
return image
|
|
@@ -46,7 +56,10 @@ class InferencePairedDataset(Dataset):
|
|
| 46 |
row = self.df.iloc[idx]
|
| 47 |
return {
|
| 48 |
"clinical": self._load_image(row["clinical_path"]),
|
| 49 |
-
"dermoscopic": self._load_image(
|
|
|
|
|
|
|
|
|
|
| 50 |
"metadata": torch.from_numpy(self.metadata[idx]),
|
| 51 |
}
|
| 52 |
|
|
@@ -63,6 +76,18 @@ def parse_args() -> argparse.Namespace:
|
|
| 63 |
parser.add_argument("--data-dir", type=Path, default=None, help="Directory containing MILK10k input/metadata files.")
|
| 64 |
parser.add_argument("--input-dir", type=Path, default=None, help="Image root. Overrides --data-dir/MILK10k_Training_Input.")
|
| 65 |
parser.add_argument("--metadata-csv", type=Path, default=None, help="Metadata CSV. Overrides --data-dir/MILK10k_Training_Metadata.csv.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
parser.add_argument("--groundtruth-csv", type=Path, default=None, help="Optional ground-truth CSV for metrics.")
|
| 67 |
parser.add_argument("--output", type=Path, default=Path("test_predictions.csv"))
|
| 68 |
parser.add_argument("--batch-size", type=int, default=16)
|
|
@@ -198,18 +223,27 @@ def build_model_from_checkpoint(checkpoint: dict[str, Any], metadata_dim: int, d
|
|
| 198 |
metadata_fusion=checkpoint_arg(checkpoint_args, "metadata_fusion", "concat"),
|
| 199 |
image_fusion=checkpoint_arg(checkpoint_args, "image_fusion", "concat"),
|
| 200 |
metadata_gate_hidden_dim=checkpoint_args.get("metadata_gate_hidden_dim"),
|
|
|
|
| 201 |
logit_fusion_mode=checkpoint_arg(checkpoint_args, "logit_fusion_mode", "single"),
|
| 202 |
fusion_logit_weight=checkpoint_arg(checkpoint_args, "fusion_logit_weight", 0.6),
|
| 203 |
clinical_logit_weight=checkpoint_arg(checkpoint_args, "clinical_logit_weight", 0.2),
|
| 204 |
dermoscopic_logit_weight=checkpoint_arg(checkpoint_args, "dermoscopic_logit_weight", 0.2),
|
| 205 |
).to(device)
|
| 206 |
-
|
| 207 |
model.eval()
|
| 208 |
return model
|
| 209 |
|
| 210 |
|
| 211 |
@torch.no_grad()
|
| 212 |
-
def predict_dataframe(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
probs_all = []
|
| 214 |
for batch in tqdm(loader, leave=False):
|
| 215 |
clinical = batch["clinical"].to(device, non_blocking=True)
|
|
@@ -227,7 +261,7 @@ def predict_dataframe(model: DualEffB2MetadataClassifier, loader: DataLoader, de
|
|
| 227 |
probs = None
|
| 228 |
for clinical_view, dermoscopic_view in views:
|
| 229 |
logits = model(clinical_view, dermoscopic_view, metadata)
|
| 230 |
-
view_prob = torch.softmax(logits, dim=1)
|
| 231 |
probs = view_prob if probs is None else probs + view_prob
|
| 232 |
probs_all.append((probs / len(views)).cpu().numpy())
|
| 233 |
return np.concatenate(probs_all)
|
|
@@ -294,6 +328,21 @@ def main() -> None:
|
|
| 294 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 295 |
input_dir, metadata_csv, groundtruth_csv = resolve_input_paths(args)
|
| 296 |
df = load_inference_dataframe(input_dir, metadata_csv, groundtruth_csv)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
checkpoint_paths = resolve_checkpoint_paths(args)
|
| 298 |
ensemble_probs = []
|
| 299 |
class_names: list[str] | None = None
|
|
@@ -324,7 +373,18 @@ def main() -> None:
|
|
| 324 |
shuffle=False,
|
| 325 |
)
|
| 326 |
model = build_model_from_checkpoint(checkpoint, dataset.metadata.shape[1], device)
|
| 327 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 328 |
class_bias = load_calibration_bias(checkpoint_path, args, checkpoint_class_names)
|
| 329 |
if class_bias is not None:
|
| 330 |
y_prob = apply_class_bias(y_prob, class_bias)
|
|
@@ -334,6 +394,23 @@ def main() -> None:
|
|
| 334 |
y_prob = np.mean(ensemble_probs, axis=0)
|
| 335 |
save_inference_outputs(df, y_prob, class_names, args.output, args.include_debug_columns)
|
| 336 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 337 |
print(f"Saved predictions: {args.output}")
|
| 338 |
if "label" in df.columns and df["label"].notna().all():
|
| 339 |
label_to_idx = {label: idx for idx, label in enumerate(class_names)}
|
|
|
|
| 15 |
from tqdm.auto import tqdm
|
| 16 |
|
| 17 |
from datasets import LABEL_COLUMNS, normalize_image_type
|
| 18 |
+
from milk10k_effb2_metadata.data import (
|
| 19 |
+
DERMOSCOPIC_MASK_PATH_COLUMN,
|
| 20 |
+
METADATA_COLUMNS,
|
| 21 |
+
apply_dermoscopic_mask,
|
| 22 |
+
audit_dermoscopic_masks,
|
| 23 |
+
make_transforms,
|
| 24 |
+
metadata_vector,
|
| 25 |
+
print_mask_audit_summary,
|
| 26 |
+
resolve_monet_columns,
|
| 27 |
+
)
|
| 28 |
from milk10k_effb2_metadata.metrics import apply_class_bias, compute_metrics
|
| 29 |
+
from milk10k_effb2_metadata.model_setup import load_model_state_compat
|
| 30 |
from milk10k_effb2_metadata.models import (
|
| 31 |
DualEffB2MetadataClassifier,
|
| 32 |
model_class_for_backbone,
|
|
|
|
| 45 |
def __len__(self) -> int:
|
| 46 |
return len(self.df)
|
| 47 |
|
| 48 |
+
def _load_image(self, path: str, mask_path: str | Path | None = None) -> torch.Tensor:
|
| 49 |
with Image.open(path) as img:
|
| 50 |
+
image = apply_dermoscopic_mask(img, mask_path)
|
| 51 |
if self.transform is not None:
|
| 52 |
image = self.transform(image)
|
| 53 |
return image
|
|
|
|
| 56 |
row = self.df.iloc[idx]
|
| 57 |
return {
|
| 58 |
"clinical": self._load_image(row["clinical_path"]),
|
| 59 |
+
"dermoscopic": self._load_image(
|
| 60 |
+
row["dermoscopic_path"],
|
| 61 |
+
row.get(DERMOSCOPIC_MASK_PATH_COLUMN),
|
| 62 |
+
),
|
| 63 |
"metadata": torch.from_numpy(self.metadata[idx]),
|
| 64 |
}
|
| 65 |
|
|
|
|
| 76 |
parser.add_argument("--data-dir", type=Path, default=None, help="Directory containing MILK10k input/metadata files.")
|
| 77 |
parser.add_argument("--input-dir", type=Path, default=None, help="Image root. Overrides --data-dir/MILK10k_Training_Input.")
|
| 78 |
parser.add_argument("--metadata-csv", type=Path, default=None, help="Metadata CSV. Overrides --data-dir/MILK10k_Training_Metadata.csv.")
|
| 79 |
+
parser.add_argument(
|
| 80 |
+
"--dermoscopic-mask-dir",
|
| 81 |
+
type=Path,
|
| 82 |
+
default=None,
|
| 83 |
+
help="Optional directory containing <lesion_id>_dermoscopic_mask.png files.",
|
| 84 |
+
)
|
| 85 |
+
parser.add_argument(
|
| 86 |
+
"--min-dermoscopic-mask-ratio",
|
| 87 |
+
type=float,
|
| 88 |
+
default=0.01,
|
| 89 |
+
help="Fallback to the original dermoscopic image when mask foreground ratio is below this value.",
|
| 90 |
+
)
|
| 91 |
parser.add_argument("--groundtruth-csv", type=Path, default=None, help="Optional ground-truth CSV for metrics.")
|
| 92 |
parser.add_argument("--output", type=Path, default=Path("test_predictions.csv"))
|
| 93 |
parser.add_argument("--batch-size", type=int, default=16)
|
|
|
|
| 223 |
metadata_fusion=checkpoint_arg(checkpoint_args, "metadata_fusion", "concat"),
|
| 224 |
image_fusion=checkpoint_arg(checkpoint_args, "image_fusion", "concat"),
|
| 225 |
metadata_gate_hidden_dim=checkpoint_args.get("metadata_gate_hidden_dim"),
|
| 226 |
+
classifier_style=checkpoint_arg(checkpoint_args, "classifier_style", "legacy"),
|
| 227 |
logit_fusion_mode=checkpoint_arg(checkpoint_args, "logit_fusion_mode", "single"),
|
| 228 |
fusion_logit_weight=checkpoint_arg(checkpoint_args, "fusion_logit_weight", 0.6),
|
| 229 |
clinical_logit_weight=checkpoint_arg(checkpoint_args, "clinical_logit_weight", 0.2),
|
| 230 |
dermoscopic_logit_weight=checkpoint_arg(checkpoint_args, "dermoscopic_logit_weight", 0.2),
|
| 231 |
).to(device)
|
| 232 |
+
load_model_state_compat(model, state)
|
| 233 |
model.eval()
|
| 234 |
return model
|
| 235 |
|
| 236 |
|
| 237 |
@torch.no_grad()
|
| 238 |
+
def predict_dataframe(
|
| 239 |
+
model: DualEffB2MetadataClassifier,
|
| 240 |
+
loader: DataLoader,
|
| 241 |
+
device: torch.device,
|
| 242 |
+
tta_flips: bool = False,
|
| 243 |
+
temperature: float = 1.0,
|
| 244 |
+
) -> np.ndarray:
|
| 245 |
+
if temperature <= 0.0:
|
| 246 |
+
raise ValueError(f"Checkpoint temperature must be positive, got {temperature}.")
|
| 247 |
probs_all = []
|
| 248 |
for batch in tqdm(loader, leave=False):
|
| 249 |
clinical = batch["clinical"].to(device, non_blocking=True)
|
|
|
|
| 261 |
probs = None
|
| 262 |
for clinical_view, dermoscopic_view in views:
|
| 263 |
logits = model(clinical_view, dermoscopic_view, metadata)
|
| 264 |
+
view_prob = torch.softmax(logits / temperature, dim=1)
|
| 265 |
probs = view_prob if probs is None else probs + view_prob
|
| 266 |
probs_all.append((probs / len(views)).cpu().numpy())
|
| 267 |
return np.concatenate(probs_all)
|
|
|
|
| 328 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 329 |
input_dir, metadata_csv, groundtruth_csv = resolve_input_paths(args)
|
| 330 |
df = load_inference_dataframe(input_dir, metadata_csv, groundtruth_csv)
|
| 331 |
+
if not 0.0 <= args.min_dermoscopic_mask_ratio <= 1.0:
|
| 332 |
+
raise ValueError("--min-dermoscopic-mask-ratio must be between 0 and 1.")
|
| 333 |
+
if args.dermoscopic_mask_dir is not None:
|
| 334 |
+
args.dermoscopic_mask_dir = args.dermoscopic_mask_dir.expanduser().resolve()
|
| 335 |
+
df, mask_audit = audit_dermoscopic_masks(
|
| 336 |
+
df,
|
| 337 |
+
args.dermoscopic_mask_dir,
|
| 338 |
+
args.min_dermoscopic_mask_ratio,
|
| 339 |
+
mask_id_column="dermoscopic_isic_id",
|
| 340 |
+
mask_suffix="_mask.png",
|
| 341 |
+
)
|
| 342 |
+
audit_output = args.output.with_name(f"{args.output.stem}.mask_audit.csv")
|
| 343 |
+
audit_output.parent.mkdir(parents=True, exist_ok=True)
|
| 344 |
+
mask_audit.to_csv(audit_output, index=False)
|
| 345 |
+
print_mask_audit_summary(mask_audit, args.min_dermoscopic_mask_ratio)
|
| 346 |
checkpoint_paths = resolve_checkpoint_paths(args)
|
| 347 |
ensemble_probs = []
|
| 348 |
class_names: list[str] | None = None
|
|
|
|
| 373 |
shuffle=False,
|
| 374 |
)
|
| 375 |
model = build_model_from_checkpoint(checkpoint, dataset.metadata.shape[1], device)
|
| 376 |
+
temperature = float(checkpoint.get("temperature", 1.0))
|
| 377 |
+
y_prob = predict_dataframe(
|
| 378 |
+
model,
|
| 379 |
+
loader,
|
| 380 |
+
device,
|
| 381 |
+
tta_flips=args.tta_flips,
|
| 382 |
+
temperature=temperature,
|
| 383 |
+
)
|
| 384 |
+
print(
|
| 385 |
+
f"Checkpoint {checkpoint_path.name}: variant={checkpoint.get('checkpoint_variant', 'legacy')}, "
|
| 386 |
+
f"temperature={temperature:.4f}"
|
| 387 |
+
)
|
| 388 |
class_bias = load_calibration_bias(checkpoint_path, args, checkpoint_class_names)
|
| 389 |
if class_bias is not None:
|
| 390 |
y_prob = apply_class_bias(y_prob, class_bias)
|
|
|
|
| 394 |
y_prob = np.mean(ensemble_probs, axis=0)
|
| 395 |
save_inference_outputs(df, y_prob, class_names, args.output, args.include_debug_columns)
|
| 396 |
|
| 397 |
+
y_pred = y_prob.argmax(axis=1)
|
| 398 |
+
for tail_name in ("DF", "INF"):
|
| 399 |
+
if tail_name not in class_names:
|
| 400 |
+
continue
|
| 401 |
+
idx = class_names.index(tail_name)
|
| 402 |
+
predicted_count = int((y_pred == idx).sum())
|
| 403 |
+
max_probability = float(y_prob[:, idx].max())
|
| 404 |
+
mean_probability = float(y_prob[:, idx].mean())
|
| 405 |
+
print(
|
| 406 |
+
f"Tail audit {tail_name}: predicted_count={predicted_count}, "
|
| 407 |
+
f"mean_probability={mean_probability:.6f}, max_probability={max_probability:.6f}"
|
| 408 |
+
)
|
| 409 |
+
if predicted_count == 0:
|
| 410 |
+
print(f"WARNING: no sample is predicted as {tail_name}.")
|
| 411 |
+
if max_probability < 0.01:
|
| 412 |
+
print(f"WARNING: {tail_name} maximum probability is below 0.01.")
|
| 413 |
+
|
| 414 |
print(f"Saved predictions: {args.output}")
|
| 415 |
if "label" in df.columns and df["label"].notna().all():
|
| 416 |
label_to_idx = {label: idx for idx, label in enumerate(class_names)}
|
milk10k_effb2_metadata/losses.py
CHANGED
|
@@ -27,6 +27,31 @@ class FocalLoss(nn.Module):
|
|
| 27 |
return loss.mean()
|
| 28 |
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
class LDAMLoss(nn.Module):
|
| 31 |
"""LDAM with deferred effective-number reweighting."""
|
| 32 |
|
|
@@ -179,7 +204,14 @@ def build_loss(train_df: pd.DataFrame, label_to_idx: dict[str, int], args: argpa
|
|
| 179 |
y = np.array([label_to_idx[label] for label in train_df["label"]])
|
| 180 |
weights = compute_class_weight(class_weight="balanced", classes=np.arange(len(label_to_idx)), y=y)
|
| 181 |
weight = torch.tensor(weights, dtype=torch.float32, device=device)
|
| 182 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
if args.loss == "focal":
|
| 184 |
return FocalLoss(weight=weight, gamma=args.focal_gamma)
|
| 185 |
if args.loss == "ce_dice":
|
|
|
|
| 27 |
return loss.mean()
|
| 28 |
|
| 29 |
|
| 30 |
+
class GeneralizedBalancedSoftmaxLoss(nn.Module):
|
| 31 |
+
def __init__(
|
| 32 |
+
self,
|
| 33 |
+
class_counts: torch.Tensor,
|
| 34 |
+
tau: float = 1.0,
|
| 35 |
+
weight: torch.Tensor | None = None,
|
| 36 |
+
) -> None:
|
| 37 |
+
super().__init__()
|
| 38 |
+
if not 0.0 <= tau <= 0.5:
|
| 39 |
+
raise ValueError("--tau must be between 0.0 and 0.5.")
|
| 40 |
+
if weight is not None:
|
| 41 |
+
raise ValueError("Generalized Balanced Softmax cannot be combined with class weights.")
|
| 42 |
+
self.tau = tau
|
| 43 |
+
counts = class_counts.float().clamp_min(1.0)
|
| 44 |
+
self.register_buffer("log_counts", torch.log(counts))
|
| 45 |
+
|
| 46 |
+
def forward(self, logits: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
|
| 47 |
+
if self.training and self.tau > 0.0:
|
| 48 |
+
log_counts = self.log_counts.to(device=logits.device, dtype=logits.dtype)
|
| 49 |
+
adjusted_logits = logits + self.tau * log_counts
|
| 50 |
+
else:
|
| 51 |
+
adjusted_logits = logits
|
| 52 |
+
return F.cross_entropy(adjusted_logits, labels)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
class LDAMLoss(nn.Module):
|
| 56 |
"""LDAM with deferred effective-number reweighting."""
|
| 57 |
|
|
|
|
| 204 |
y = np.array([label_to_idx[label] for label in train_df["label"]])
|
| 205 |
weights = compute_class_weight(class_weight="balanced", classes=np.arange(len(label_to_idx)), y=y)
|
| 206 |
weight = torch.tensor(weights, dtype=torch.float32, device=device)
|
| 207 |
+
|
| 208 |
+
if getattr(args, "tau", 0.0) > 0.0:
|
| 209 |
+
if args.class_weight:
|
| 210 |
+
raise ValueError("--tau > 0 cannot be combined with --class-weight.")
|
| 211 |
+
counts = class_count_tensor(train_df, label_to_idx, device)
|
| 212 |
+
ce_loss: nn.Module = GeneralizedBalancedSoftmaxLoss(counts, tau=args.tau)
|
| 213 |
+
else:
|
| 214 |
+
ce_loss: nn.Module = nn.CrossEntropyLoss(weight=weight)
|
| 215 |
if args.loss == "focal":
|
| 216 |
return FocalLoss(weight=weight, gamma=args.focal_gamma)
|
| 217 |
if args.loss == "ce_dice":
|
milk10k_effb2_metadata/metrics.py
CHANGED
|
@@ -13,6 +13,7 @@ from sklearn.metrics import (
|
|
| 13 |
balanced_accuracy_score,
|
| 14 |
classification_report,
|
| 15 |
confusion_matrix,
|
|
|
|
| 16 |
precision_recall_fscore_support,
|
| 17 |
roc_auc_score,
|
| 18 |
)
|
|
@@ -56,6 +57,9 @@ def macro_dice_from_confusion_matrix(cm: np.ndarray) -> float:
|
|
| 56 |
|
| 57 |
|
| 58 |
def compute_metrics(y_true: np.ndarray, y_prob: np.ndarray, class_names: list[str]) -> tuple[dict[str, Any], pd.DataFrame, np.ndarray]:
|
|
|
|
|
|
|
|
|
|
| 59 |
y_pred = y_prob.argmax(axis=1)
|
| 60 |
labels = list(range(len(class_names)))
|
| 61 |
y_true_bin = label_binarize(y_true, classes=labels)
|
|
@@ -91,11 +95,23 @@ def compute_metrics(y_true: np.ndarray, y_prob: np.ndarray, class_names: list[st
|
|
| 91 |
"specificity": tn / (tn + fp) if (tn + fp) else 0.0,
|
| 92 |
"f1": float(f1_per_class[idx]),
|
| 93 |
"auc_ovr": auc_ovr,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
}
|
| 95 |
)
|
| 96 |
|
|
|
|
|
|
|
|
|
|
| 97 |
metrics = {
|
| 98 |
"accuracy": float(accuracy_score(y_true, y_pred)),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
"balanced_accuracy": float(balanced_accuracy_score(y_true, y_pred)),
|
| 100 |
"top2_accuracy": float(np.mean((np.argsort(y_prob, axis=1)[:, -min(2, len(class_names)) :] == y_true[:, None]).any(axis=1))),
|
| 101 |
"top3_accuracy": float(np.mean((np.argsort(y_prob, axis=1)[:, -min(3, len(class_names)) :] == y_true[:, None]).any(axis=1))),
|
|
@@ -124,6 +140,23 @@ def compute_metrics(y_true: np.ndarray, y_prob: np.ndarray, class_names: list[st
|
|
| 124 |
return metrics, pd.DataFrame(per_class_rows), cm
|
| 125 |
|
| 126 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
def safe_roc_auc(y_true_bin: np.ndarray, y_prob: np.ndarray, average: str | None) -> float | None:
|
| 128 |
try:
|
| 129 |
return float(roc_auc_score(y_true_bin, y_prob, average=average, multi_class="ovr"))
|
|
|
|
| 13 |
balanced_accuracy_score,
|
| 14 |
classification_report,
|
| 15 |
confusion_matrix,
|
| 16 |
+
log_loss,
|
| 17 |
precision_recall_fscore_support,
|
| 18 |
roc_auc_score,
|
| 19 |
)
|
|
|
|
| 57 |
|
| 58 |
|
| 59 |
def compute_metrics(y_true: np.ndarray, y_prob: np.ndarray, class_names: list[str]) -> tuple[dict[str, Any], pd.DataFrame, np.ndarray]:
|
| 60 |
+
y_prob = np.asarray(y_prob, dtype=np.float64)
|
| 61 |
+
y_prob = np.clip(y_prob, 1e-12, 1.0)
|
| 62 |
+
y_prob = y_prob / y_prob.sum(axis=1, keepdims=True)
|
| 63 |
y_pred = y_prob.argmax(axis=1)
|
| 64 |
labels = list(range(len(class_names)))
|
| 65 |
y_true_bin = label_binarize(y_true, classes=labels)
|
|
|
|
| 95 |
"specificity": tn / (tn + fp) if (tn + fp) else 0.0,
|
| 96 |
"f1": float(f1_per_class[idx]),
|
| 97 |
"auc_ovr": auc_ovr,
|
| 98 |
+
"mean_correct_confidence": (
|
| 99 |
+
float(y_prob[(y_true == idx) & (y_pred == idx), idx].mean())
|
| 100 |
+
if np.any((y_true == idx) & (y_pred == idx))
|
| 101 |
+
else None
|
| 102 |
+
),
|
| 103 |
}
|
| 104 |
)
|
| 105 |
|
| 106 |
+
correct_mask = y_pred == y_true
|
| 107 |
+
confidence = y_prob.max(axis=1)
|
| 108 |
+
|
| 109 |
metrics = {
|
| 110 |
"accuracy": float(accuracy_score(y_true, y_pred)),
|
| 111 |
+
"nll": float(log_loss(y_true, y_prob, labels=labels)),
|
| 112 |
+
"ece": expected_calibration_error(y_true, y_prob),
|
| 113 |
+
"mean_confidence": float(confidence.mean()),
|
| 114 |
+
"mean_correct_confidence": float(confidence[correct_mask].mean()) if np.any(correct_mask) else None,
|
| 115 |
"balanced_accuracy": float(balanced_accuracy_score(y_true, y_pred)),
|
| 116 |
"top2_accuracy": float(np.mean((np.argsort(y_prob, axis=1)[:, -min(2, len(class_names)) :] == y_true[:, None]).any(axis=1))),
|
| 117 |
"top3_accuracy": float(np.mean((np.argsort(y_prob, axis=1)[:, -min(3, len(class_names)) :] == y_true[:, None]).any(axis=1))),
|
|
|
|
| 140 |
return metrics, pd.DataFrame(per_class_rows), cm
|
| 141 |
|
| 142 |
|
| 143 |
+
def expected_calibration_error(y_true: np.ndarray, y_prob: np.ndarray, bins: int = 15) -> float:
|
| 144 |
+
y_pred = y_prob.argmax(axis=1)
|
| 145 |
+
confidence = y_prob.max(axis=1)
|
| 146 |
+
correct = (y_pred == y_true).astype(np.float64)
|
| 147 |
+
edges = np.linspace(0.0, 1.0, bins + 1)
|
| 148 |
+
ece = 0.0
|
| 149 |
+
for idx in range(bins):
|
| 150 |
+
lower, upper = edges[idx], edges[idx + 1]
|
| 151 |
+
mask = (confidence > lower) & (confidence <= upper)
|
| 152 |
+
if idx == 0:
|
| 153 |
+
mask |= confidence == 0.0
|
| 154 |
+
if not np.any(mask):
|
| 155 |
+
continue
|
| 156 |
+
ece += float(mask.mean()) * abs(float(correct[mask].mean()) - float(confidence[mask].mean()))
|
| 157 |
+
return float(ece)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
def safe_roc_auc(y_true_bin: np.ndarray, y_prob: np.ndarray, average: str | None) -> float | None:
|
| 161 |
try:
|
| 162 |
return float(roc_auc_score(y_true_bin, y_prob, average=average, multi_class="ovr"))
|
milk10k_effb2_metadata/model_setup.py
CHANGED
|
@@ -15,6 +15,20 @@ from milk10k_effb2_metadata.checkpoints import (
|
|
| 15 |
from milk10k_effb2_metadata.models import DualEffB2MetadataClassifier, model_class_for_backbone
|
| 16 |
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
def infer_branch_backend_from_state(state: dict[str, torch.Tensor], branch_prefix: str) -> str:
|
| 19 |
keys = [key.removeprefix(branch_prefix) for key in state if key.startswith(branch_prefix)]
|
| 20 |
timm_prefixes = ("conv_stem.", "bn1.", "blocks.", "conv_head.", "bn2.", "stages.", "stem.")
|
|
@@ -103,6 +117,7 @@ def load_resume_checkpoint(
|
|
| 103 |
checkpoint_path: Path | None,
|
| 104 |
model: DualEffB2MetadataClassifier,
|
| 105 |
device: torch.device,
|
|
|
|
| 106 |
) -> tuple[int, float, str | None]:
|
| 107 |
if checkpoint_path is None:
|
| 108 |
return 1, float("-inf"), None
|
|
@@ -110,7 +125,9 @@ def load_resume_checkpoint(
|
|
| 110 |
if not checkpoint_path.exists():
|
| 111 |
raise FileNotFoundError(f"Resume checkpoint not found: {checkpoint_path}")
|
| 112 |
checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=False)
|
| 113 |
-
|
|
|
|
|
|
|
| 114 |
next_epoch = int(checkpoint.get("epoch", 0)) + 1
|
| 115 |
best_val_f1 = float(
|
| 116 |
checkpoint.get(
|
|
@@ -152,6 +169,7 @@ def build_model(
|
|
| 152 |
metadata_fusion=args.metadata_fusion,
|
| 153 |
image_fusion=getattr(args, "image_fusion", "concat"),
|
| 154 |
metadata_gate_hidden_dim=args.metadata_gate_hidden_dim,
|
|
|
|
| 155 |
logit_fusion_mode=args.logit_fusion_mode,
|
| 156 |
fusion_logit_weight=args.fusion_logit_weight,
|
| 157 |
clinical_logit_weight=args.clinical_logit_weight,
|
|
|
|
| 15 |
from milk10k_effb2_metadata.models import DualEffB2MetadataClassifier, model_class_for_backbone
|
| 16 |
|
| 17 |
|
| 18 |
+
def load_model_state_compat(model: DualEffB2MetadataClassifier, state: dict[str, torch.Tensor]) -> None:
|
| 19 |
+
"""Load checkpoints created before LWS added the class_scales parameter."""
|
| 20 |
+
incompatible = model.load_state_dict(state, strict=False)
|
| 21 |
+
missing = set(incompatible.missing_keys)
|
| 22 |
+
unexpected = set(incompatible.unexpected_keys)
|
| 23 |
+
allowed_missing = {"class_scales"}
|
| 24 |
+
if missing - allowed_missing or unexpected:
|
| 25 |
+
raise RuntimeError(
|
| 26 |
+
f"Checkpoint state mismatch: missing={sorted(missing)}, unexpected={sorted(unexpected)}"
|
| 27 |
+
)
|
| 28 |
+
if "class_scales" in missing:
|
| 29 |
+
model.class_scales.data.fill_(1.0)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
def infer_branch_backend_from_state(state: dict[str, torch.Tensor], branch_prefix: str) -> str:
|
| 33 |
keys = [key.removeprefix(branch_prefix) for key in state if key.startswith(branch_prefix)]
|
| 34 |
timm_prefixes = ("conv_stem.", "bn1.", "blocks.", "conv_head.", "bn2.", "stages.", "stem.")
|
|
|
|
| 117 |
checkpoint_path: Path | None,
|
| 118 |
model: DualEffB2MetadataClassifier,
|
| 119 |
device: torch.device,
|
| 120 |
+
ema_model: torch.nn.Module | None = None,
|
| 121 |
) -> tuple[int, float, str | None]:
|
| 122 |
if checkpoint_path is None:
|
| 123 |
return 1, float("-inf"), None
|
|
|
|
| 125 |
if not checkpoint_path.exists():
|
| 126 |
raise FileNotFoundError(f"Resume checkpoint not found: {checkpoint_path}")
|
| 127 |
checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=False)
|
| 128 |
+
load_model_state_compat(model, checkpoint["model_state"])
|
| 129 |
+
if ema_model is not None and "ema_model_state" in checkpoint:
|
| 130 |
+
ema_model.load_state_dict(checkpoint["ema_model_state"])
|
| 131 |
next_epoch = int(checkpoint.get("epoch", 0)) + 1
|
| 132 |
best_val_f1 = float(
|
| 133 |
checkpoint.get(
|
|
|
|
| 169 |
metadata_fusion=args.metadata_fusion,
|
| 170 |
image_fusion=getattr(args, "image_fusion", "concat"),
|
| 171 |
metadata_gate_hidden_dim=args.metadata_gate_hidden_dim,
|
| 172 |
+
classifier_style=getattr(args, "classifier_style", "legacy"),
|
| 173 |
logit_fusion_mode=args.logit_fusion_mode,
|
| 174 |
fusion_logit_weight=args.fusion_logit_weight,
|
| 175 |
clinical_logit_weight=args.clinical_logit_weight,
|
milk10k_effb2_metadata/models.py
CHANGED
|
@@ -107,6 +107,7 @@ class DualEffB2MetadataClassifier(nn.Module):
|
|
| 107 |
metadata_fusion: str = "concat",
|
| 108 |
image_fusion: str = "concat",
|
| 109 |
metadata_gate_hidden_dim: int | None = None,
|
|
|
|
| 110 |
logit_fusion_mode: str = "single",
|
| 111 |
fusion_logit_weight: float = 0.6,
|
| 112 |
clinical_logit_weight: float = 0.2,
|
|
@@ -128,6 +129,8 @@ class DualEffB2MetadataClassifier(nn.Module):
|
|
| 128 |
raise ValueError(f"Unsupported image_fusion: {image_fusion}")
|
| 129 |
if logit_fusion_mode not in ("single", "fixed"):
|
| 130 |
raise ValueError(f"Unsupported logit_fusion_mode: {logit_fusion_mode}")
|
|
|
|
|
|
|
| 131 |
self.clinical_backbone_backend = clinical_backbone_backend
|
| 132 |
self.dermoscopic_backbone_backend = dermoscopic_backbone_backend
|
| 133 |
self.backbone = normalize_backbone_name(backbone)
|
|
@@ -135,6 +138,7 @@ class DualEffB2MetadataClassifier(nn.Module):
|
|
| 135 |
self.metadata_dim = metadata_dim
|
| 136 |
self.metadata_fusion = metadata_fusion
|
| 137 |
self.image_fusion = image_fusion
|
|
|
|
| 138 |
self.logit_fusion_mode = logit_fusion_mode
|
| 139 |
self.fusion_logit_weight = fusion_logit_weight
|
| 140 |
self.clinical_logit_weight = clinical_logit_weight
|
|
@@ -212,16 +216,37 @@ class DualEffB2MetadataClassifier(nn.Module):
|
|
| 212 |
if clinical_feature_dim != dermoscopic_feature_dim:
|
| 213 |
raise ValueError("shared_private image fusion requires matching branch feature dimensions.")
|
| 214 |
self.shared_head = ProjectionHead(clinical_feature_dim, branch_dim, dropout)
|
| 215 |
-
self.classifier =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
if logit_fusion_mode == "fixed":
|
| 217 |
self.clinical_classifier = BranchClassifier(branch_dim, num_classes, dropout)
|
| 218 |
self.dermoscopic_classifier = BranchClassifier(branch_dim, num_classes, dropout)
|
| 219 |
else:
|
| 220 |
self.clinical_classifier = None
|
| 221 |
self.dermoscopic_classifier = None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
|
| 223 |
@staticmethod
|
| 224 |
-
def _classifier(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
return nn.Sequential(
|
| 226 |
nn.LayerNorm(in_dim),
|
| 227 |
nn.Dropout(dropout),
|
|
@@ -287,14 +312,14 @@ class DualEffB2MetadataClassifier(nn.Module):
|
|
| 287 |
fused = self._fused_features(clinical_features, dermoscopic_features, clinical_repr, dermoscopic_repr, metadata_repr)
|
| 288 |
fusion_logits = self.classifier(fused)
|
| 289 |
if self.logit_fusion_mode != "fixed":
|
| 290 |
-
return fusion_logits
|
| 291 |
clinical_logits = self.clinical_classifier(clinical_repr)
|
| 292 |
dermoscopic_logits = self.dermoscopic_classifier(dermoscopic_repr)
|
| 293 |
return (
|
| 294 |
self.fusion_logit_weight * fusion_logits
|
| 295 |
+ self.clinical_logit_weight * clinical_logits
|
| 296 |
+ self.dermoscopic_logit_weight * dermoscopic_logits
|
| 297 |
-
)
|
| 298 |
|
| 299 |
def _append_metadata(self, features: torch.Tensor, metadata_repr: torch.Tensor | None) -> torch.Tensor:
|
| 300 |
if metadata_repr is None:
|
|
@@ -401,6 +426,8 @@ class DualConvNeXtMetadataClassifier(DualEffB2MetadataClassifier):
|
|
| 401 |
|
| 402 |
def normalize_backbone_name(name: str) -> str:
|
| 403 |
name = name.lower().replace(" ", "").replace("_", "").replace("-", "")
|
|
|
|
|
|
|
| 404 |
if name in ("efficientnetb2", "effnetb2", "effb2"):
|
| 405 |
return "efficientnet_b2"
|
| 406 |
if name in ("efficientnetb1", "effnetb1", "effb1"):
|
|
@@ -425,6 +452,8 @@ def default_image_size(backbone: str) -> int:
|
|
| 425 |
backbone = normalize_backbone_name(backbone)
|
| 426 |
if backbone == "efficientnet_b2":
|
| 427 |
return 260
|
|
|
|
|
|
|
| 428 |
if backbone == "efficientnet_b1":
|
| 429 |
return 240
|
| 430 |
if backbone == "convnext_base":
|
|
@@ -478,6 +507,8 @@ def build_feature_encoder(backbone: str, backbone_backend: str, imagenet_pretrai
|
|
| 478 |
return model, int(model.num_features)
|
| 479 |
|
| 480 |
if backbone_backend == "torchvision":
|
|
|
|
|
|
|
| 481 |
if backbone == "efficientnet_b2":
|
| 482 |
from torchvision.models import efficientnet_b2, EfficientNet_B2_Weights
|
| 483 |
weights = EfficientNet_B2_Weights.IMAGENET1K_V1 if imagenet_pretrained else None
|
|
|
|
| 107 |
metadata_fusion: str = "concat",
|
| 108 |
image_fusion: str = "concat",
|
| 109 |
metadata_gate_hidden_dim: int | None = None,
|
| 110 |
+
classifier_style: str = "legacy",
|
| 111 |
logit_fusion_mode: str = "single",
|
| 112 |
fusion_logit_weight: float = 0.6,
|
| 113 |
clinical_logit_weight: float = 0.2,
|
|
|
|
| 129 |
raise ValueError(f"Unsupported image_fusion: {image_fusion}")
|
| 130 |
if logit_fusion_mode not in ("single", "fixed"):
|
| 131 |
raise ValueError(f"Unsupported logit_fusion_mode: {logit_fusion_mode}")
|
| 132 |
+
if classifier_style not in ("legacy", "simple"):
|
| 133 |
+
raise ValueError(f"Unsupported classifier_style: {classifier_style}")
|
| 134 |
self.clinical_backbone_backend = clinical_backbone_backend
|
| 135 |
self.dermoscopic_backbone_backend = dermoscopic_backbone_backend
|
| 136 |
self.backbone = normalize_backbone_name(backbone)
|
|
|
|
| 138 |
self.metadata_dim = metadata_dim
|
| 139 |
self.metadata_fusion = metadata_fusion
|
| 140 |
self.image_fusion = image_fusion
|
| 141 |
+
self.classifier_style = classifier_style
|
| 142 |
self.logit_fusion_mode = logit_fusion_mode
|
| 143 |
self.fusion_logit_weight = fusion_logit_weight
|
| 144 |
self.clinical_logit_weight = clinical_logit_weight
|
|
|
|
| 216 |
if clinical_feature_dim != dermoscopic_feature_dim:
|
| 217 |
raise ValueError("shared_private image fusion requires matching branch feature dimensions.")
|
| 218 |
self.shared_head = ProjectionHead(clinical_feature_dim, branch_dim, dropout)
|
| 219 |
+
self.classifier = (
|
| 220 |
+
None
|
| 221 |
+
if image_fusion == "moe"
|
| 222 |
+
else self._classifier(fused_dim, classifier_hidden_dim, num_classes, dropout, classifier_style)
|
| 223 |
+
)
|
| 224 |
if logit_fusion_mode == "fixed":
|
| 225 |
self.clinical_classifier = BranchClassifier(branch_dim, num_classes, dropout)
|
| 226 |
self.dermoscopic_classifier = BranchClassifier(branch_dim, num_classes, dropout)
|
| 227 |
else:
|
| 228 |
self.clinical_classifier = None
|
| 229 |
self.dermoscopic_classifier = None
|
| 230 |
+
|
| 231 |
+
# LWS is a post-training stage. Keep scales frozen during normal
|
| 232 |
+
# representation/classifier training and enable them explicitly later.
|
| 233 |
+
self.class_scales = nn.Parameter(torch.ones(num_classes), requires_grad=False)
|
| 234 |
|
| 235 |
@staticmethod
|
| 236 |
+
def _classifier(
|
| 237 |
+
in_dim: int,
|
| 238 |
+
hidden_dim: int,
|
| 239 |
+
num_classes: int,
|
| 240 |
+
dropout: float,
|
| 241 |
+
classifier_style: str,
|
| 242 |
+
) -> nn.Sequential:
|
| 243 |
+
if classifier_style == "simple":
|
| 244 |
+
return nn.Sequential(
|
| 245 |
+
nn.Linear(in_dim, hidden_dim),
|
| 246 |
+
nn.ReLU(),
|
| 247 |
+
nn.Dropout(dropout),
|
| 248 |
+
nn.Linear(hidden_dim, num_classes),
|
| 249 |
+
)
|
| 250 |
return nn.Sequential(
|
| 251 |
nn.LayerNorm(in_dim),
|
| 252 |
nn.Dropout(dropout),
|
|
|
|
| 312 |
fused = self._fused_features(clinical_features, dermoscopic_features, clinical_repr, dermoscopic_repr, metadata_repr)
|
| 313 |
fusion_logits = self.classifier(fused)
|
| 314 |
if self.logit_fusion_mode != "fixed":
|
| 315 |
+
return fusion_logits * self.class_scales
|
| 316 |
clinical_logits = self.clinical_classifier(clinical_repr)
|
| 317 |
dermoscopic_logits = self.dermoscopic_classifier(dermoscopic_repr)
|
| 318 |
return (
|
| 319 |
self.fusion_logit_weight * fusion_logits
|
| 320 |
+ self.clinical_logit_weight * clinical_logits
|
| 321 |
+ self.dermoscopic_logit_weight * dermoscopic_logits
|
| 322 |
+
) * self.class_scales
|
| 323 |
|
| 324 |
def _append_metadata(self, features: torch.Tensor, metadata_repr: torch.Tensor | None) -> torch.Tensor:
|
| 325 |
if metadata_repr is None:
|
|
|
|
| 426 |
|
| 427 |
def normalize_backbone_name(name: str) -> str:
|
| 428 |
name = name.lower().replace(" ", "").replace("_", "").replace("-", "")
|
| 429 |
+
if name in ("tfefficientnetv2b2", "efficientnetv2b2", "effnetv2b2", "effv2b2"):
|
| 430 |
+
return "tf_efficientnetv2_b2"
|
| 431 |
if name in ("efficientnetb2", "effnetb2", "effb2"):
|
| 432 |
return "efficientnet_b2"
|
| 433 |
if name in ("efficientnetb1", "effnetb1", "effb1"):
|
|
|
|
| 452 |
backbone = normalize_backbone_name(backbone)
|
| 453 |
if backbone == "efficientnet_b2":
|
| 454 |
return 260
|
| 455 |
+
if backbone == "tf_efficientnetv2_b2":
|
| 456 |
+
return 384
|
| 457 |
if backbone == "efficientnet_b1":
|
| 458 |
return 240
|
| 459 |
if backbone == "convnext_base":
|
|
|
|
| 507 |
return model, int(model.num_features)
|
| 508 |
|
| 509 |
if backbone_backend == "torchvision":
|
| 510 |
+
if backbone == "tf_efficientnetv2_b2":
|
| 511 |
+
raise ValueError("tf_efficientnetv2_b2 is only available with --backbone-backend timm.")
|
| 512 |
if backbone == "efficientnet_b2":
|
| 513 |
from torchvision.models import efficientnet_b2, EfficientNet_B2_Weights
|
| 514 |
weights = EfficientNet_B2_Weights.IMAGENET1K_V1 if imagenet_pretrained else None
|
milk10k_effb2_metadata/reporting.py
CHANGED
|
@@ -95,6 +95,11 @@ def class_distribution(df: pd.DataFrame, class_names: list[str]) -> dict[str, An
|
|
| 95 |
if len(df)
|
| 96 |
else {name: 0 for name in class_names}
|
| 97 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
return {
|
| 99 |
"rows": int(len(df)),
|
| 100 |
"class_counts": counts,
|
|
@@ -102,6 +107,7 @@ def class_distribution(df: pd.DataFrame, class_names: list[str]) -> dict[str, An
|
|
| 102 |
"synthetic_rows": int(is_augmented.sum()),
|
| 103 |
"synthetic_class_counts": augmented_counts,
|
| 104 |
"ignore_metadata_rows": int(ignore_metadata.sum()),
|
|
|
|
| 105 |
}
|
| 106 |
|
| 107 |
|
|
@@ -353,6 +359,21 @@ def render_split_summary(data_summary: dict[str, Any]) -> str:
|
|
| 353 |
lines.append(f"| {class_name} | {count} | {summary['synthetic_class_counts'].get(class_name, 0)} |")
|
| 354 |
lines.append("")
|
| 355 |
lines.append(f"- synthetic_train_only: {data_summary['synthetic_train_only']}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 356 |
lines.append("")
|
| 357 |
return "\n".join(lines)
|
| 358 |
|
|
@@ -380,7 +401,13 @@ def render_run_report(
|
|
| 380 |
f"- loss: {getattr(args, 'loss', None)}",
|
| 381 |
f"- class_weight: {getattr(args, 'class_weight', None)}",
|
| 382 |
f"- weighted_sampler: {getattr(args, 'weighted_sampler', None)}",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 383 |
f"- augmented_data_dir: {getattr(args, 'augmented_data_dir', None)}",
|
|
|
|
|
|
|
| 384 |
f"- augmented_classes: {getattr(args, 'augmented_classes', None)}",
|
| 385 |
f"- augmented_max_per_class: {getattr(args, 'augmented_max_per_class', None)}",
|
| 386 |
f"- freeze_metadata_head: {getattr(args, 'freeze_metadata_head', None)}",
|
|
|
|
| 95 |
if len(df)
|
| 96 |
else {name: 0 for name in class_names}
|
| 97 |
)
|
| 98 |
+
mask_status_counts = (
|
| 99 |
+
df["dermoscopic_mask_status"].fillna("not_audited").value_counts().sort_index().astype(int).to_dict()
|
| 100 |
+
if "dermoscopic_mask_status" in df.columns
|
| 101 |
+
else {}
|
| 102 |
+
)
|
| 103 |
return {
|
| 104 |
"rows": int(len(df)),
|
| 105 |
"class_counts": counts,
|
|
|
|
| 107 |
"synthetic_rows": int(is_augmented.sum()),
|
| 108 |
"synthetic_class_counts": augmented_counts,
|
| 109 |
"ignore_metadata_rows": int(ignore_metadata.sum()),
|
| 110 |
+
"dermoscopic_mask_status_counts": mask_status_counts,
|
| 111 |
}
|
| 112 |
|
| 113 |
|
|
|
|
| 359 |
lines.append(f"| {class_name} | {count} | {summary['synthetic_class_counts'].get(class_name, 0)} |")
|
| 360 |
lines.append("")
|
| 361 |
lines.append(f"- synthetic_train_only: {data_summary['synthetic_train_only']}")
|
| 362 |
+
balance = data_summary.get("balance")
|
| 363 |
+
if balance:
|
| 364 |
+
lines.extend(
|
| 365 |
+
[
|
| 366 |
+
f"- balance_mode: {balance['mode']}",
|
| 367 |
+
f"- effective_rows_per_epoch: {balance['effective_rows_per_epoch']}",
|
| 368 |
+
f"- strong_augmentation_classes: {balance['strong_augmentation_classes']}",
|
| 369 |
+
"",
|
| 370 |
+
"| class | original train | effective per epoch |",
|
| 371 |
+
"|---|---:|---:|",
|
| 372 |
+
]
|
| 373 |
+
)
|
| 374 |
+
for class_name, count in balance["original_class_counts"].items():
|
| 375 |
+
effective = balance["effective_class_counts_per_epoch"][class_name]
|
| 376 |
+
lines.append(f"| {class_name} | {count} | {effective} |")
|
| 377 |
lines.append("")
|
| 378 |
return "\n".join(lines)
|
| 379 |
|
|
|
|
| 401 |
f"- loss: {getattr(args, 'loss', None)}",
|
| 402 |
f"- class_weight: {getattr(args, 'class_weight', None)}",
|
| 403 |
f"- weighted_sampler: {getattr(args, 'weighted_sampler', None)}",
|
| 404 |
+
f"- balance_mode: {getattr(args, 'balance_mode', None)}",
|
| 405 |
+
f"- balance_head_ratio: {getattr(args, 'balance_head_ratio', None)}",
|
| 406 |
+
f"- balance_tail_floor: {getattr(args, 'balance_tail_floor', None)}",
|
| 407 |
+
f"- balance_min_source_count: {getattr(args, 'balance_min_source_count', None)}",
|
| 408 |
f"- augmented_data_dir: {getattr(args, 'augmented_data_dir', None)}",
|
| 409 |
+
f"- dermoscopic_mask_dir: {getattr(args, 'dermoscopic_mask_dir', None)}",
|
| 410 |
+
f"- min_dermoscopic_mask_ratio: {getattr(args, 'min_dermoscopic_mask_ratio', None)}",
|
| 411 |
f"- augmented_classes: {getattr(args, 'augmented_classes', None)}",
|
| 412 |
f"- augmented_max_per_class: {getattr(args, 'augmented_max_per_class', None)}",
|
| 413 |
f"- freeze_metadata_head: {getattr(args, 'freeze_metadata_head', None)}",
|
milk10k_effb2_metadata/runner.py
CHANGED
|
@@ -7,11 +7,16 @@ import json
|
|
| 7 |
from pathlib import Path
|
| 8 |
from typing import Any
|
| 9 |
|
|
|
|
| 10 |
import pandas as pd
|
| 11 |
import torch
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
from milk10k_effb2_metadata.data import (
|
| 14 |
fit_metadata_spec,
|
|
|
|
| 15 |
kfold_splits,
|
| 16 |
lesion_split,
|
| 17 |
load_paired_dataframe,
|
|
@@ -21,10 +26,162 @@ from milk10k_effb2_metadata.data import (
|
|
| 21 |
from milk10k_effb2_metadata.engine import train_phase
|
| 22 |
from milk10k_effb2_metadata.losses import build_loss
|
| 23 |
from milk10k_effb2_metadata.metrics import apply_class_bias, compute_metrics, optimize_class_bias, predict, save_predictions
|
| 24 |
-
from milk10k_effb2_metadata.model_setup import build_model, load_resume_checkpoint
|
|
|
|
| 25 |
from milk10k_effb2_metadata.reporting import build_data_summary, save_data_summary, save_kfold_report, save_run_diagnostics
|
| 26 |
from milk10k_effb2_metadata.training_utils import json_safe, save_kfold_summary, save_run_config
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
def build_tail_tracking_config(
|
| 30 |
train_df: pd.DataFrame,
|
|
@@ -55,6 +212,11 @@ def resolve_label_name(class_names: list[str], name: str) -> str:
|
|
| 55 |
return normalized[key]
|
| 56 |
|
| 57 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
def load_augmented_subset(
|
| 59 |
base_df: pd.DataFrame,
|
| 60 |
class_names: list[str],
|
|
@@ -74,14 +236,6 @@ def load_augmented_subset(
|
|
| 74 |
augmented_max_per_class = getattr(args, "augmented_max_per_class", 0)
|
| 75 |
if augmented_max_per_class < 0:
|
| 76 |
raise ValueError("--augmented-max-per-class must be >= 0.")
|
| 77 |
-
if augmented_max_per_class > 0 and not augmented_df.empty:
|
| 78 |
-
augmented_df = (
|
| 79 |
-
augmented_df.sample(frac=1.0, random_state=args.seed)
|
| 80 |
-
.groupby("label", group_keys=False)
|
| 81 |
-
.head(augmented_max_per_class)
|
| 82 |
-
.sort_values(["label", "lesion_id"])
|
| 83 |
-
.reset_index(drop=True)
|
| 84 |
-
)
|
| 85 |
augmented_df["is_augmented"] = True
|
| 86 |
augmented_df["ignore_metadata"] = bool(getattr(args, "zero_augmented_metadata", False))
|
| 87 |
return augmented_df
|
|
@@ -90,6 +244,7 @@ def load_augmented_subset(
|
|
| 90 |
def append_augmented_train_rows(
|
| 91 |
base_df: pd.DataFrame,
|
| 92 |
train_df: pd.DataFrame,
|
|
|
|
| 93 |
class_names: list[str],
|
| 94 |
args: argparse.Namespace,
|
| 95 |
) -> pd.DataFrame:
|
|
@@ -98,10 +253,39 @@ def append_augmented_train_rows(
|
|
| 98 |
if getattr(args, "augmented_data_dir", None) is not None:
|
| 99 |
print("Augmented data: no extra rows selected.")
|
| 100 |
return train_df
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
counts = augmented_df["label"].value_counts().sort_index().to_dict()
|
| 102 |
print(
|
| 103 |
-
"
|
| 104 |
f"rows={len(augmented_df)}, counts={counts}, "
|
|
|
|
| 105 |
f"zero_metadata={getattr(args, 'zero_augmented_metadata', False)}, "
|
| 106 |
f"source={getattr(args, 'augmented_data_dir', None)}"
|
| 107 |
)
|
|
@@ -127,6 +311,12 @@ def run_training_split(
|
|
| 127 |
train_df.to_csv(split_dir / "train.csv", index=False)
|
| 128 |
val_df.to_csv(split_dir / "val.csv", index=False)
|
| 129 |
data_summary = build_data_summary(df, train_df, val_df, class_names)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
save_data_summary(output_dir, data_summary)
|
| 131 |
|
| 132 |
metadata_spec = fit_metadata_spec(train_df)
|
|
@@ -152,7 +342,13 @@ def run_training_split(
|
|
| 152 |
clinical_backbone_backend,
|
| 153 |
dermoscopic_backbone_backend,
|
| 154 |
)
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
train_loader, val_loader = make_loaders(train_df, val_df, label_to_idx, metadata_spec, args)
|
| 157 |
criterion = build_loss(train_df, label_to_idx, args, device)
|
| 158 |
tail_config = build_tail_tracking_config(train_df, class_names, label_to_idx, args)
|
|
@@ -169,7 +365,12 @@ def run_training_split(
|
|
| 169 |
f"metadata_fusion={args.metadata_fusion}, image_fusion={getattr(args, 'image_fusion', 'concat')}, "
|
| 170 |
f"gate_hidden_dim={args.metadata_gate_hidden_dim}"
|
| 171 |
)
|
| 172 |
-
print(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
if getattr(args, "image_fusion", "concat") == "moe" and args.logit_fusion_mode == "fixed":
|
| 174 |
print("Note: --image-fusion moe already mixes expert logits; --logit-fusion-mode fixed adds extra branch logits.")
|
| 175 |
if args.loss == "ce_f1":
|
|
@@ -194,7 +395,8 @@ def run_training_split(
|
|
| 194 |
if resume_phase == "finetune":
|
| 195 |
skip_freeze_until = args.freeze_epochs + 1
|
| 196 |
skip_finetune_until = resume_epoch if resume_phase == "finetune" else 1
|
| 197 |
-
|
|
|
|
| 198 |
"freeze",
|
| 199 |
args.freeze_epochs,
|
| 200 |
1,
|
|
@@ -213,8 +415,10 @@ def run_training_split(
|
|
| 213 |
skip_freeze_until,
|
| 214 |
**(tail_config or {}),
|
| 215 |
best_val_tail_recall=best_tail_start,
|
|
|
|
|
|
|
| 216 |
)
|
| 217 |
-
epoch, best_val_f1, best_val_tail_recall = train_phase(
|
| 218 |
"finetune",
|
| 219 |
args.finetune_epochs,
|
| 220 |
epoch,
|
|
@@ -233,18 +437,97 @@ def run_training_split(
|
|
| 233 |
skip_finetune_until,
|
| 234 |
**(tail_config or {}),
|
| 235 |
best_val_tail_recall=best_val_tail_recall,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
)
|
| 237 |
|
| 238 |
-
best_path = output_dir / "best.pt"
|
| 239 |
-
if best_path.exists():
|
| 240 |
-
checkpoint = torch.load(best_path, map_location=device, weights_only=False)
|
| 241 |
-
model.load_state_dict(checkpoint["model_state"])
|
| 242 |
-
y_true, y_prob = predict(model, val_loader, device)
|
| 243 |
metrics, per_class_df, cm = compute_metrics(y_true, y_prob, class_names)
|
|
|
|
| 244 |
metrics = {
|
| 245 |
-
"best_selection_metric": float(
|
| 246 |
"selection_metric_name": args.selection_metric,
|
| 247 |
-
"best_val_f1_macro": float(
|
|
|
|
|
|
|
|
|
|
| 248 |
**metrics,
|
| 249 |
}
|
| 250 |
if tail_config is not None:
|
|
@@ -293,7 +576,7 @@ def run_training_split(
|
|
| 293 |
fold,
|
| 294 |
)
|
| 295 |
print(
|
| 296 |
-
f"Done: best_val_f1_macro={
|
| 297 |
f"val_acc={metrics['accuracy']:.4f}, balanced_acc={metrics['balanced_accuracy']:.4f}, "
|
| 298 |
f"f1_macro={metrics['f1_macro']:.4f}, top3={metrics['top3_accuracy']:.4f}, "
|
| 299 |
f"auc_macro={metrics['roc_auc_macro_ovr']}"
|
|
@@ -318,14 +601,24 @@ def train_single_run(
|
|
| 318 |
real_df = df[~synthetic_mask].copy()
|
| 319 |
synthetic_df = df[synthetic_mask].copy()
|
| 320 |
train_df, val_df = lesion_split(real_df, args.val_size, args.seed)
|
| 321 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 322 |
print(
|
| 323 |
-
f"
|
| 324 |
-
f"synthetic_train={len(
|
|
|
|
| 325 |
)
|
| 326 |
else:
|
| 327 |
train_df, val_df = lesion_split(df, args.val_size, args.seed)
|
| 328 |
-
train_df = append_augmented_train_rows(df, train_df, class_names, args)
|
| 329 |
return run_training_split(
|
| 330 |
df,
|
| 331 |
train_df,
|
|
@@ -355,7 +648,7 @@ def train_kfold(
|
|
| 355 |
fold_metrics = []
|
| 356 |
for fold_idx, (train_df, val_df) in enumerate(kfold_splits(df, args.k_folds, args.seed)):
|
| 357 |
print(f"\nK-fold {fold_idx + 1}/{args.k_folds}")
|
| 358 |
-
train_df = append_augmented_train_rows(df, train_df, class_names, args)
|
| 359 |
metrics = run_training_split(
|
| 360 |
df,
|
| 361 |
train_df,
|
|
|
|
| 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 |
+
import torch.nn.functional as F
|
| 14 |
+
from torch import nn
|
| 15 |
+
from torch.utils.data import DataLoader, WeightedRandomSampler
|
| 16 |
|
| 17 |
from milk10k_effb2_metadata.data import (
|
| 18 |
fit_metadata_spec,
|
| 19 |
+
hybrid_balance_summary,
|
| 20 |
kfold_splits,
|
| 21 |
lesion_split,
|
| 22 |
load_paired_dataframe,
|
|
|
|
| 26 |
from milk10k_effb2_metadata.engine import train_phase
|
| 27 |
from milk10k_effb2_metadata.losses import build_loss
|
| 28 |
from milk10k_effb2_metadata.metrics import apply_class_bias, compute_metrics, optimize_class_bias, predict, save_predictions
|
| 29 |
+
from milk10k_effb2_metadata.model_setup import build_model, load_model_state_compat, load_resume_checkpoint
|
| 30 |
+
from milk10k_effb2_metadata.models import DualEffB2MetadataClassifier
|
| 31 |
from milk10k_effb2_metadata.reporting import build_data_summary, save_data_summary, save_kfold_report, save_run_diagnostics
|
| 32 |
from milk10k_effb2_metadata.training_utils import json_safe, save_kfold_summary, save_run_config
|
| 33 |
|
| 34 |
+
def train_lws_post_training(
|
| 35 |
+
model: DualEffB2MetadataClassifier,
|
| 36 |
+
train_loader: DataLoader,
|
| 37 |
+
val_loader: DataLoader,
|
| 38 |
+
device: torch.device,
|
| 39 |
+
args: argparse.Namespace,
|
| 40 |
+
source_checkpoint: dict[str, Any],
|
| 41 |
+
output_path: Path,
|
| 42 |
+
) -> dict[str, Any] | None:
|
| 43 |
+
if args.lws_epochs <= 0:
|
| 44 |
+
return None
|
| 45 |
+
|
| 46 |
+
print(f"\nStarting LWS Post-Training for {args.lws_epochs} epochs...")
|
| 47 |
+
model.requires_grad_(False)
|
| 48 |
+
model.class_scales.data.fill_(1.0)
|
| 49 |
+
model.class_scales.requires_grad_(True)
|
| 50 |
+
optimizer = torch.optim.Adam([model.class_scales], lr=args.lws_lr)
|
| 51 |
+
criterion = nn.CrossEntropyLoss()
|
| 52 |
+
|
| 53 |
+
dataset = train_loader.dataset
|
| 54 |
+
labels = np.asarray(dataset.labels, dtype=np.int64)
|
| 55 |
+
counts = np.bincount(labels)
|
| 56 |
+
class_weights = 1.0 / np.power(counts.astype(np.float64), args.lws_sampler_power)
|
| 57 |
+
generator = torch.Generator().manual_seed(args.seed)
|
| 58 |
+
lws_sampler = WeightedRandomSampler(
|
| 59 |
+
torch.as_tensor(class_weights[labels], dtype=torch.double),
|
| 60 |
+
num_samples=len(dataset),
|
| 61 |
+
replacement=True,
|
| 62 |
+
generator=generator,
|
| 63 |
+
)
|
| 64 |
+
lws_loader = DataLoader(
|
| 65 |
+
dataset,
|
| 66 |
+
batch_size=args.batch_size,
|
| 67 |
+
num_workers=args.num_workers,
|
| 68 |
+
pin_memory=torch.cuda.is_available(),
|
| 69 |
+
sampler=lws_sampler,
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
# Keep dropout and batch normalization disabled. Gradients still flow to
|
| 73 |
+
# class_scales while every representation/classifier parameter is frozen.
|
| 74 |
+
model.eval()
|
| 75 |
+
from milk10k_effb2_metadata.metrics import move_batch
|
| 76 |
+
best_score = float("-inf")
|
| 77 |
+
best_metrics: dict[str, Any] | None = None
|
| 78 |
+
for epoch in range(1, args.lws_epochs + 1):
|
| 79 |
+
total_loss = 0.0
|
| 80 |
+
for batch in lws_loader:
|
| 81 |
+
clinical, dermoscopic, metadata, labels = move_batch(batch, device)
|
| 82 |
+
optimizer.zero_grad()
|
| 83 |
+
logits = model(clinical, dermoscopic, metadata)
|
| 84 |
+
loss = criterion(logits, labels)
|
| 85 |
+
loss.backward()
|
| 86 |
+
optimizer.step()
|
| 87 |
+
|
| 88 |
+
model.class_scales.data.clamp_(args.lws_min_scale, args.lws_max_scale)
|
| 89 |
+
total_loss += loss.item()
|
| 90 |
+
|
| 91 |
+
y_true, y_prob = predict(model, val_loader, device)
|
| 92 |
+
metrics, _, _ = compute_metrics(y_true, y_prob, source_checkpoint["class_names"])
|
| 93 |
+
scales_str = np.array2string(model.class_scales.detach().cpu().numpy(), precision=3, separator=',')
|
| 94 |
+
print(
|
| 95 |
+
f"LWS Epoch {epoch}/{args.lws_epochs} - Loss: {total_loss / max(len(lws_loader), 1):.4f} "
|
| 96 |
+
f"- F1: {metrics['f1_macro']:.4f} - Scales: {scales_str}"
|
| 97 |
+
)
|
| 98 |
+
if metrics[args.selection_metric] > best_score:
|
| 99 |
+
best_score = float(metrics[args.selection_metric])
|
| 100 |
+
best_metrics = metrics
|
| 101 |
+
payload = dict(source_checkpoint)
|
| 102 |
+
payload["model_state"] = {
|
| 103 |
+
name: value.detach().cpu().clone() for name, value in model.state_dict().items()
|
| 104 |
+
}
|
| 105 |
+
payload["checkpoint_variant"] = "lws"
|
| 106 |
+
payload["best_selection_metric"] = best_score
|
| 107 |
+
payload["best_val_f1_macro"] = float(metrics["f1_macro"])
|
| 108 |
+
payload["lws_epoch"] = epoch
|
| 109 |
+
payload["lws_scales"] = model.class_scales.detach().cpu().tolist()
|
| 110 |
+
payload["variant_val_metrics"] = json_safe(metrics)
|
| 111 |
+
torch.save(payload, output_path)
|
| 112 |
+
model.class_scales.requires_grad_(False)
|
| 113 |
+
return best_metrics
|
| 114 |
+
|
| 115 |
+
def fit_global_temperature(
|
| 116 |
+
model: nn.Module,
|
| 117 |
+
val_loader: DataLoader,
|
| 118 |
+
device: torch.device,
|
| 119 |
+
) -> float:
|
| 120 |
+
model.eval()
|
| 121 |
+
all_logits = []
|
| 122 |
+
all_labels = []
|
| 123 |
+
from milk10k_effb2_metadata.metrics import move_batch
|
| 124 |
+
with torch.no_grad():
|
| 125 |
+
for batch in val_loader:
|
| 126 |
+
clinical, dermoscopic, metadata, labels = move_batch(batch, device)
|
| 127 |
+
logits = model(clinical, dermoscopic, metadata)
|
| 128 |
+
all_logits.append(logits)
|
| 129 |
+
all_labels.append(labels)
|
| 130 |
+
|
| 131 |
+
all_logits = torch.cat(all_logits)
|
| 132 |
+
all_labels = torch.cat(all_labels)
|
| 133 |
+
|
| 134 |
+
log_temperature = torch.nn.Parameter(torch.zeros(1, device=device))
|
| 135 |
+
optimizer = torch.optim.LBFGS([log_temperature], lr=0.05, max_iter=50)
|
| 136 |
+
|
| 137 |
+
def eval_fn():
|
| 138 |
+
optimizer.zero_grad()
|
| 139 |
+
temperature = log_temperature.exp().clamp(0.05, 20.0)
|
| 140 |
+
loss = F.cross_entropy(all_logits / temperature, all_labels)
|
| 141 |
+
loss.backward()
|
| 142 |
+
return loss
|
| 143 |
+
|
| 144 |
+
optimizer.step(eval_fn)
|
| 145 |
+
return float(log_temperature.detach().exp().clamp(0.05, 20.0).item())
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
@torch.no_grad()
|
| 149 |
+
def predict_temperature(
|
| 150 |
+
model: nn.Module,
|
| 151 |
+
loader: DataLoader,
|
| 152 |
+
device: torch.device,
|
| 153 |
+
temperature: float,
|
| 154 |
+
) -> tuple[np.ndarray, np.ndarray]:
|
| 155 |
+
from milk10k_effb2_metadata.metrics import move_batch
|
| 156 |
+
|
| 157 |
+
model.eval()
|
| 158 |
+
labels_all: list[np.ndarray] = []
|
| 159 |
+
probs_all: list[np.ndarray] = []
|
| 160 |
+
for batch in loader:
|
| 161 |
+
clinical, dermoscopic, metadata, labels = move_batch(batch, device)
|
| 162 |
+
logits = model(clinical, dermoscopic, metadata) / temperature
|
| 163 |
+
labels_all.append(labels.cpu().numpy())
|
| 164 |
+
probs_all.append(torch.softmax(logits, dim=1).cpu().numpy())
|
| 165 |
+
return np.concatenate(labels_all), np.concatenate(probs_all)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def add_head_confidence_metrics(
|
| 169 |
+
metrics: dict[str, Any],
|
| 170 |
+
y_true: np.ndarray,
|
| 171 |
+
y_prob: np.ndarray,
|
| 172 |
+
class_names: list[str],
|
| 173 |
+
train_df: pd.DataFrame,
|
| 174 |
+
min_support: int = 100,
|
| 175 |
+
) -> None:
|
| 176 |
+
train_counts = train_df["label"].value_counts()
|
| 177 |
+
head_indices = [idx for idx, name in enumerate(class_names) if int(train_counts.get(name, 0)) >= min_support]
|
| 178 |
+
y_pred = y_prob.argmax(axis=1)
|
| 179 |
+
mask = np.isin(y_true, head_indices) & (y_pred == y_true)
|
| 180 |
+
metrics["head_class_names"] = [class_names[idx] for idx in head_indices]
|
| 181 |
+
metrics["mean_correct_confidence_head"] = (
|
| 182 |
+
float(y_prob[mask, y_true[mask]].mean()) if np.any(mask) else None
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
|
| 186 |
def build_tail_tracking_config(
|
| 187 |
train_df: pd.DataFrame,
|
|
|
|
| 212 |
return normalized[key]
|
| 213 |
|
| 214 |
|
| 215 |
+
def source_lesion_id(value: Any) -> str:
|
| 216 |
+
"""Return the original lesion ID for a generated paired lesion ID."""
|
| 217 |
+
return str(value).split("__sdpair_", 1)[0]
|
| 218 |
+
|
| 219 |
+
|
| 220 |
def load_augmented_subset(
|
| 221 |
base_df: pd.DataFrame,
|
| 222 |
class_names: list[str],
|
|
|
|
| 236 |
augmented_max_per_class = getattr(args, "augmented_max_per_class", 0)
|
| 237 |
if augmented_max_per_class < 0:
|
| 238 |
raise ValueError("--augmented-max-per-class must be >= 0.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
augmented_df["is_augmented"] = True
|
| 240 |
augmented_df["ignore_metadata"] = bool(getattr(args, "zero_augmented_metadata", False))
|
| 241 |
return augmented_df
|
|
|
|
| 244 |
def append_augmented_train_rows(
|
| 245 |
base_df: pd.DataFrame,
|
| 246 |
train_df: pd.DataFrame,
|
| 247 |
+
val_df: pd.DataFrame,
|
| 248 |
class_names: list[str],
|
| 249 |
args: argparse.Namespace,
|
| 250 |
) -> pd.DataFrame:
|
|
|
|
| 253 |
if getattr(args, "augmented_data_dir", None) is not None:
|
| 254 |
print("Augmented data: no extra rows selected.")
|
| 255 |
return train_df
|
| 256 |
+
train_source_ids = set(train_df["lesion_id"].astype(str).map(source_lesion_id))
|
| 257 |
+
val_source_ids = set(val_df["lesion_id"].astype(str).map(source_lesion_id))
|
| 258 |
+
augmented_df["source_lesion_id"] = augmented_df["lesion_id"].astype(str).map(source_lesion_id)
|
| 259 |
+
source_overlap = train_source_ids & val_source_ids
|
| 260 |
+
if source_overlap:
|
| 261 |
+
raise RuntimeError(
|
| 262 |
+
f"Source leakage already exists between train and validation: {len(source_overlap)} lesion IDs."
|
| 263 |
+
)
|
| 264 |
+
selected = augmented_df["source_lesion_id"].isin(train_source_ids)
|
| 265 |
+
excluded_validation = augmented_df["source_lesion_id"].isin(val_source_ids)
|
| 266 |
+
unknown = ~(selected | excluded_validation)
|
| 267 |
+
if unknown.any():
|
| 268 |
+
examples = augmented_df.loc[unknown, "lesion_id"].astype(str).head(5).tolist()
|
| 269 |
+
raise ValueError(
|
| 270 |
+
"Augmented lesions cannot be mapped to an original train/validation source. "
|
| 271 |
+
f"Examples: {examples}"
|
| 272 |
+
)
|
| 273 |
+
excluded_count = int(excluded_validation.sum())
|
| 274 |
+
augmented_df = augmented_df.loc[selected].copy()
|
| 275 |
+
augmented_max_per_class = getattr(args, "augmented_max_per_class", 0)
|
| 276 |
+
if augmented_max_per_class > 0 and not augmented_df.empty:
|
| 277 |
+
augmented_df = (
|
| 278 |
+
augmented_df.sample(frac=1.0, random_state=args.seed)
|
| 279 |
+
.groupby("label", group_keys=False)
|
| 280 |
+
.head(augmented_max_per_class)
|
| 281 |
+
.sort_values(["label", "lesion_id"])
|
| 282 |
+
.reset_index(drop=True)
|
| 283 |
+
)
|
| 284 |
counts = augmented_df["label"].value_counts().sort_index().to_dict()
|
| 285 |
print(
|
| 286 |
+
"Source-safe augmented train append: "
|
| 287 |
f"rows={len(augmented_df)}, counts={counts}, "
|
| 288 |
+
f"excluded_validation_sources={excluded_count}, "
|
| 289 |
f"zero_metadata={getattr(args, 'zero_augmented_metadata', False)}, "
|
| 290 |
f"source={getattr(args, 'augmented_data_dir', None)}"
|
| 291 |
)
|
|
|
|
| 311 |
train_df.to_csv(split_dir / "train.csv", index=False)
|
| 312 |
val_df.to_csv(split_dir / "val.csv", index=False)
|
| 313 |
data_summary = build_data_summary(df, train_df, val_df, class_names)
|
| 314 |
+
if args.balance_mode == "hybrid":
|
| 315 |
+
data_summary["balance"] = hybrid_balance_summary(
|
| 316 |
+
[label_to_idx[label] for label in train_df["label"].tolist()],
|
| 317 |
+
{idx: label for label, idx in label_to_idx.items()},
|
| 318 |
+
args,
|
| 319 |
+
)
|
| 320 |
save_data_summary(output_dir, data_summary)
|
| 321 |
|
| 322 |
metadata_spec = fit_metadata_spec(train_df)
|
|
|
|
| 342 |
clinical_backbone_backend,
|
| 343 |
dermoscopic_backbone_backend,
|
| 344 |
)
|
| 345 |
+
|
| 346 |
+
ema_model = None
|
| 347 |
+
if getattr(args, "ema", False):
|
| 348 |
+
from torch.optim.swa_utils import AveragedModel, get_ema_multi_avg_fn
|
| 349 |
+
ema_model = AveragedModel(model, multi_avg_fn=get_ema_multi_avg_fn(args.ema_decay))
|
| 350 |
+
|
| 351 |
+
resume_epoch, resume_best_val_f1, resume_phase = load_resume_checkpoint(args.resume_checkpoint, model, device, ema_model=ema_model)
|
| 352 |
train_loader, val_loader = make_loaders(train_df, val_df, label_to_idx, metadata_spec, args)
|
| 353 |
criterion = build_loss(train_df, label_to_idx, args, device)
|
| 354 |
tail_config = build_tail_tracking_config(train_df, class_names, label_to_idx, args)
|
|
|
|
| 365 |
f"metadata_fusion={args.metadata_fusion}, image_fusion={getattr(args, 'image_fusion', 'concat')}, "
|
| 366 |
f"gate_hidden_dim={args.metadata_gate_hidden_dim}"
|
| 367 |
)
|
| 368 |
+
print(
|
| 369 |
+
f"Loss: {args.loss}, class_weight={args.class_weight}, weighted_sampler={args.weighted_sampler}, "
|
| 370 |
+
f"balance_mode={args.balance_mode}"
|
| 371 |
+
)
|
| 372 |
+
if args.balance_mode == "hybrid":
|
| 373 |
+
print(f"Hybrid balance plan: {data_summary['balance']}")
|
| 374 |
if getattr(args, "image_fusion", "concat") == "moe" and args.logit_fusion_mode == "fixed":
|
| 375 |
print("Note: --image-fusion moe already mixes expert logits; --logit-fusion-mode fixed adds extra branch logits.")
|
| 376 |
if args.loss == "ce_f1":
|
|
|
|
| 395 |
if resume_phase == "finetune":
|
| 396 |
skip_freeze_until = args.freeze_epochs + 1
|
| 397 |
skip_finetune_until = resume_epoch if resume_phase == "finetune" else 1
|
| 398 |
+
variant_best = {"raw": float("-inf"), "ema": float("-inf")}
|
| 399 |
+
epoch, best_val_f1, best_val_tail_recall, variant_best = train_phase(
|
| 400 |
"freeze",
|
| 401 |
args.freeze_epochs,
|
| 402 |
1,
|
|
|
|
| 415 |
skip_freeze_until,
|
| 416 |
**(tail_config or {}),
|
| 417 |
best_val_tail_recall=best_tail_start,
|
| 418 |
+
ema_model=ema_model,
|
| 419 |
+
variant_best=variant_best,
|
| 420 |
)
|
| 421 |
+
epoch, best_val_f1, best_val_tail_recall, variant_best = train_phase(
|
| 422 |
"finetune",
|
| 423 |
args.finetune_epochs,
|
| 424 |
epoch,
|
|
|
|
| 437 |
skip_finetune_until,
|
| 438 |
**(tail_config or {}),
|
| 439 |
best_val_tail_recall=best_val_tail_recall,
|
| 440 |
+
ema_model=ema_model,
|
| 441 |
+
variant_best=variant_best,
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
raw_path = output_dir / "best_raw.pt"
|
| 445 |
+
ema_path = output_dir / "best_ema.pt"
|
| 446 |
+
if not raw_path.exists():
|
| 447 |
+
raise RuntimeError(f"Training did not produce {raw_path}")
|
| 448 |
+
source_path = ema_path if ema_path.exists() else raw_path
|
| 449 |
+
source_checkpoint = torch.load(source_path, map_location=device, weights_only=False)
|
| 450 |
+
load_model_state_compat(model, source_checkpoint["model_state"])
|
| 451 |
+
|
| 452 |
+
lws_path = output_dir / "best_lws.pt"
|
| 453 |
+
if args.lws_epochs > 0:
|
| 454 |
+
train_lws_post_training(
|
| 455 |
+
model,
|
| 456 |
+
train_loader,
|
| 457 |
+
val_loader,
|
| 458 |
+
device,
|
| 459 |
+
args,
|
| 460 |
+
source_checkpoint,
|
| 461 |
+
lws_path,
|
| 462 |
+
)
|
| 463 |
+
|
| 464 |
+
variant_paths = [raw_path]
|
| 465 |
+
if ema_path.exists():
|
| 466 |
+
variant_paths.append(ema_path)
|
| 467 |
+
if lws_path.exists():
|
| 468 |
+
variant_paths.append(lws_path)
|
| 469 |
+
|
| 470 |
+
variant_results: dict[str, dict[str, Any]] = {}
|
| 471 |
+
deployment: tuple[float, Path, dict[str, Any], np.ndarray] | None = None
|
| 472 |
+
y_true: np.ndarray | None = None
|
| 473 |
+
for variant_path in variant_paths:
|
| 474 |
+
checkpoint = torch.load(variant_path, map_location=device, weights_only=False)
|
| 475 |
+
load_model_state_compat(model, checkpoint["model_state"])
|
| 476 |
+
variant = str(checkpoint.get("checkpoint_variant", variant_path.stem.removeprefix("best_")))
|
| 477 |
+
uncalibrated_y_true, uncalibrated_prob = predict_temperature(model, val_loader, device, 1.0)
|
| 478 |
+
uncalibrated_metrics, _, _ = compute_metrics(uncalibrated_y_true, uncalibrated_prob, class_names)
|
| 479 |
+
add_head_confidence_metrics(
|
| 480 |
+
uncalibrated_metrics,
|
| 481 |
+
uncalibrated_y_true,
|
| 482 |
+
uncalibrated_prob,
|
| 483 |
+
class_names,
|
| 484 |
+
train_df,
|
| 485 |
+
)
|
| 486 |
+
temperature = fit_global_temperature(model, val_loader, device) if args.fit_temperature else 1.0
|
| 487 |
+
current_y_true, current_prob = predict_temperature(model, val_loader, device, temperature)
|
| 488 |
+
current_metrics, current_per_class, current_cm = compute_metrics(current_y_true, current_prob, class_names)
|
| 489 |
+
add_head_confidence_metrics(current_metrics, current_y_true, current_prob, class_names, train_df)
|
| 490 |
+
checkpoint["temperature"] = temperature
|
| 491 |
+
checkpoint["uncalibrated_metrics"] = json_safe(uncalibrated_metrics)
|
| 492 |
+
checkpoint["temperature_metrics"] = json_safe(current_metrics)
|
| 493 |
+
checkpoint["checkpoint_variant"] = variant
|
| 494 |
+
torch.save(checkpoint, variant_path)
|
| 495 |
+
current_per_class.to_csv(output_dir / f"per_class_metrics_{variant}.csv", index=False)
|
| 496 |
+
pd.DataFrame(current_cm, index=class_names, columns=class_names).to_csv(
|
| 497 |
+
output_dir / f"confusion_matrix_{variant}.csv"
|
| 498 |
+
)
|
| 499 |
+
variant_output = output_dir / variant
|
| 500 |
+
variant_output.mkdir(exist_ok=True)
|
| 501 |
+
save_predictions(val_df, current_y_true, current_prob, class_names, variant_output)
|
| 502 |
+
variant_results[variant] = {
|
| 503 |
+
"checkpoint": str(variant_path),
|
| 504 |
+
"temperature": temperature,
|
| 505 |
+
"uncalibrated_metrics": uncalibrated_metrics,
|
| 506 |
+
"metrics": current_metrics,
|
| 507 |
+
}
|
| 508 |
+
score = float(current_metrics[args.selection_metric])
|
| 509 |
+
if deployment is None or score > deployment[0]:
|
| 510 |
+
deployment = (score, variant_path, checkpoint, current_prob)
|
| 511 |
+
y_true = current_y_true
|
| 512 |
+
|
| 513 |
+
if deployment is None or y_true is None:
|
| 514 |
+
raise RuntimeError("No deployable raw/EMA/LWS checkpoint was produced.")
|
| 515 |
+
_, deployment_path, deployment_checkpoint, y_prob = deployment
|
| 516 |
+
torch.save(deployment_checkpoint, output_dir / "best.pt")
|
| 517 |
+
print(
|
| 518 |
+
f"Selected deployment variant={deployment_checkpoint['checkpoint_variant']} "
|
| 519 |
+
f"from {deployment_path.name}, temperature={deployment_checkpoint['temperature']:.4f}"
|
| 520 |
)
|
| 521 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 522 |
metrics, per_class_df, cm = compute_metrics(y_true, y_prob, class_names)
|
| 523 |
+
add_head_confidence_metrics(metrics, y_true, y_prob, class_names, train_df)
|
| 524 |
metrics = {
|
| 525 |
+
"best_selection_metric": float(metrics[args.selection_metric]),
|
| 526 |
"selection_metric_name": args.selection_metric,
|
| 527 |
+
"best_val_f1_macro": float(metrics["f1_macro"]),
|
| 528 |
+
"checkpoint_variant": deployment_checkpoint["checkpoint_variant"],
|
| 529 |
+
"temperature": deployment_checkpoint["temperature"],
|
| 530 |
+
"variants": variant_results,
|
| 531 |
**metrics,
|
| 532 |
}
|
| 533 |
if tail_config is not None:
|
|
|
|
| 576 |
fold,
|
| 577 |
)
|
| 578 |
print(
|
| 579 |
+
f"Done: best_val_f1_macro={metrics['f1_macro']:.4f}, "
|
| 580 |
f"val_acc={metrics['accuracy']:.4f}, balanced_acc={metrics['balanced_accuracy']:.4f}, "
|
| 581 |
f"f1_macro={metrics['f1_macro']:.4f}, top3={metrics['top3_accuracy']:.4f}, "
|
| 582 |
f"auc_macro={metrics['roc_auc_macro_ovr']}"
|
|
|
|
| 601 |
real_df = df[~synthetic_mask].copy()
|
| 602 |
synthetic_df = df[synthetic_mask].copy()
|
| 603 |
train_df, val_df = lesion_split(real_df, args.val_size, args.seed)
|
| 604 |
+
train_sources = set(train_df["lesion_id"].astype(str))
|
| 605 |
+
val_sources = set(val_df["lesion_id"].astype(str))
|
| 606 |
+
synthetic_df["source_lesion_id"] = synthetic_df["lesion_id"].astype(str).map(source_lesion_id)
|
| 607 |
+
unknown_sources = ~synthetic_df["source_lesion_id"].isin(train_sources | val_sources)
|
| 608 |
+
if unknown_sources.any():
|
| 609 |
+
examples = synthetic_df.loc[unknown_sources, "lesion_id"].astype(str).head(5).tolist()
|
| 610 |
+
raise ValueError(f"Synthetic lesions have unknown source IDs. Examples: {examples}")
|
| 611 |
+
safe_synthetic_df = synthetic_df[synthetic_df["source_lesion_id"].isin(train_sources)].copy()
|
| 612 |
+
excluded_count = int(synthetic_df["source_lesion_id"].isin(val_sources).sum())
|
| 613 |
+
train_df = pd.concat([train_df, safe_synthetic_df], ignore_index=True, sort=False)
|
| 614 |
print(
|
| 615 |
+
f"Source-safe synthetic train-only split: real_train={len(train_df) - len(safe_synthetic_df)}, "
|
| 616 |
+
f"synthetic_train={len(safe_synthetic_df)}, excluded_validation_sources={excluded_count}, "
|
| 617 |
+
f"val_real={len(val_df)}"
|
| 618 |
)
|
| 619 |
else:
|
| 620 |
train_df, val_df = lesion_split(df, args.val_size, args.seed)
|
| 621 |
+
train_df = append_augmented_train_rows(df, train_df, val_df, class_names, args)
|
| 622 |
return run_training_split(
|
| 623 |
df,
|
| 624 |
train_df,
|
|
|
|
| 648 |
fold_metrics = []
|
| 649 |
for fold_idx, (train_df, val_df) in enumerate(kfold_splits(df, args.k_folds, args.seed)):
|
| 650 |
print(f"\nK-fold {fold_idx + 1}/{args.k_folds}")
|
| 651 |
+
train_df = append_augmented_train_rows(df, train_df, val_df, class_names, args)
|
| 652 |
metrics = run_training_split(
|
| 653 |
df,
|
| 654 |
train_df,
|
milk10k_effb2_metadata/tests/__pycache__/test_fusion_and_f1_loss.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/tests/__pycache__/test_fusion_and_f1_loss.cpython-314.pyc and b/milk10k_effb2_metadata/tests/__pycache__/test_fusion_and_f1_loss.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/training.py
CHANGED
|
@@ -7,17 +7,58 @@ import argparse
|
|
| 7 |
from milk10k_effb2_metadata.training_utils import json_safe
|
| 8 |
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
def run(args: argparse.Namespace) -> None:
|
| 11 |
import torch
|
| 12 |
|
| 13 |
from datasets import resolve_data_dir, set_seed
|
| 14 |
-
from milk10k_effb2_metadata.data import
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
from milk10k_effb2_metadata.model_setup import resolve_training_backbone_backends
|
| 16 |
from milk10k_effb2_metadata.models import normalize_backbone_name, resolve_image_size
|
| 17 |
from milk10k_effb2_metadata.runner import train_kfold, train_single_run
|
| 18 |
|
| 19 |
if args.k_folds < 1:
|
| 20 |
raise ValueError("--k-folds must be at least 1.")
|
|
|
|
| 21 |
|
| 22 |
set_seed(args.seed)
|
| 23 |
data_dir = resolve_data_dir(args.data_dir)
|
|
@@ -31,6 +72,17 @@ def run(args: argparse.Namespace) -> None:
|
|
| 31 |
args.image_size = resolve_image_size(args.backbone, args.image_size)
|
| 32 |
|
| 33 |
df = load_paired_dataframe(data_dir)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
class_names = sorted(df["label"].unique())
|
| 35 |
label_to_idx = {label: idx for idx, label in enumerate(class_names)}
|
| 36 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
|
|
| 7 |
from milk10k_effb2_metadata.training_utils import json_safe
|
| 8 |
|
| 9 |
|
| 10 |
+
def validate_balance_args(args: argparse.Namespace) -> None:
|
| 11 |
+
if args.balance_mode == "hybrid" and args.weighted_sampler:
|
| 12 |
+
raise ValueError("--balance-mode hybrid cannot be combined with --weighted-sampler.")
|
| 13 |
+
if args.balance_head_ratio <= 0:
|
| 14 |
+
raise ValueError("--balance-head-ratio must be greater than 0.")
|
| 15 |
+
if args.balance_tail_floor < 0:
|
| 16 |
+
raise ValueError("--balance-tail-floor must be >= 0.")
|
| 17 |
+
if args.balance_min_source_count < 1:
|
| 18 |
+
raise ValueError("--balance-min-source-count must be at least 1.")
|
| 19 |
+
tau = float(getattr(args, "tau", 0.0))
|
| 20 |
+
class_weight = bool(getattr(args, "class_weight", False))
|
| 21 |
+
loss = str(getattr(args, "loss", "ce"))
|
| 22 |
+
lws_epochs = int(getattr(args, "lws_epochs", 0))
|
| 23 |
+
lws_lr = float(getattr(args, "lws_lr", 1e-2))
|
| 24 |
+
lws_sampler_power = float(getattr(args, "lws_sampler_power", 0.5))
|
| 25 |
+
lws_min_scale = float(getattr(args, "lws_min_scale", 0.75))
|
| 26 |
+
lws_max_scale = float(getattr(args, "lws_max_scale", 1.5))
|
| 27 |
+
ema_decay = float(getattr(args, "ema_decay", 0.999))
|
| 28 |
+
if not 0.0 <= tau <= 0.5:
|
| 29 |
+
raise ValueError("--tau must be between 0.0 and 0.5.")
|
| 30 |
+
if tau > 0.0 and class_weight:
|
| 31 |
+
raise ValueError("--tau > 0 cannot be combined with --class-weight.")
|
| 32 |
+
if tau > 0.0 and loss in {"focal", "ldam"}:
|
| 33 |
+
raise ValueError("--tau > 0 requires a CE-based loss (ce, ce_dice, or ce_f1).")
|
| 34 |
+
if lws_epochs < 0:
|
| 35 |
+
raise ValueError("--lws-epochs must be >= 0.")
|
| 36 |
+
if lws_lr <= 0.0:
|
| 37 |
+
raise ValueError("--lws-lr must be > 0.")
|
| 38 |
+
if not 0.0 <= lws_sampler_power <= 1.0:
|
| 39 |
+
raise ValueError("--lws-sampler-power must be between 0.0 and 1.0.")
|
| 40 |
+
if lws_min_scale <= 0.0 or lws_max_scale < lws_min_scale:
|
| 41 |
+
raise ValueError("LWS scale bounds must satisfy 0 < min <= max.")
|
| 42 |
+
if not 0.0 < ema_decay < 1.0:
|
| 43 |
+
raise ValueError("--ema-decay must be between 0 and 1.")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
def run(args: argparse.Namespace) -> None:
|
| 47 |
import torch
|
| 48 |
|
| 49 |
from datasets import resolve_data_dir, set_seed
|
| 50 |
+
from milk10k_effb2_metadata.data import (
|
| 51 |
+
audit_dermoscopic_masks,
|
| 52 |
+
load_paired_dataframe,
|
| 53 |
+
print_mask_audit_summary,
|
| 54 |
+
)
|
| 55 |
from milk10k_effb2_metadata.model_setup import resolve_training_backbone_backends
|
| 56 |
from milk10k_effb2_metadata.models import normalize_backbone_name, resolve_image_size
|
| 57 |
from milk10k_effb2_metadata.runner import train_kfold, train_single_run
|
| 58 |
|
| 59 |
if args.k_folds < 1:
|
| 60 |
raise ValueError("--k-folds must be at least 1.")
|
| 61 |
+
validate_balance_args(args)
|
| 62 |
|
| 63 |
set_seed(args.seed)
|
| 64 |
data_dir = resolve_data_dir(args.data_dir)
|
|
|
|
| 72 |
args.image_size = resolve_image_size(args.backbone, args.image_size)
|
| 73 |
|
| 74 |
df = load_paired_dataframe(data_dir)
|
| 75 |
+
if not 0.0 <= args.min_dermoscopic_mask_ratio <= 1.0:
|
| 76 |
+
raise ValueError("--min-dermoscopic-mask-ratio must be between 0 and 1.")
|
| 77 |
+
if args.dermoscopic_mask_dir is not None:
|
| 78 |
+
args.dermoscopic_mask_dir = args.dermoscopic_mask_dir.expanduser().resolve()
|
| 79 |
+
df, mask_audit = audit_dermoscopic_masks(
|
| 80 |
+
df,
|
| 81 |
+
args.dermoscopic_mask_dir,
|
| 82 |
+
args.min_dermoscopic_mask_ratio,
|
| 83 |
+
)
|
| 84 |
+
mask_audit.to_csv(args.output_dir / "dermoscopic_mask_audit.csv", index=False)
|
| 85 |
+
print_mask_audit_summary(mask_audit, args.min_dermoscopic_mask_ratio)
|
| 86 |
class_names = sorted(df["label"].unique())
|
| 87 |
label_to_idx = {label: idx for idx, label in enumerate(class_names)}
|
| 88 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
milk10k_effb2_metadata/training_utils.py
CHANGED
|
@@ -46,6 +46,7 @@ def save_run_config(
|
|
| 46 |
"paths": {
|
| 47 |
"output_dir": str(output_dir),
|
| 48 |
"data_dir": str(getattr(args, "data_dir", "")),
|
|
|
|
| 49 |
"clinical_checkpoint": str(getattr(args, "clinical_checkpoint", "")),
|
| 50 |
"dermoscopic_checkpoint": str(getattr(args, "dermoscopic_checkpoint", "")),
|
| 51 |
"resume_checkpoint": str(getattr(args, "resume_checkpoint", "")),
|
|
|
|
| 46 |
"paths": {
|
| 47 |
"output_dir": str(output_dir),
|
| 48 |
"data_dir": str(getattr(args, "data_dir", "")),
|
| 49 |
+
"dermoscopic_mask_dir": str(getattr(args, "dermoscopic_mask_dir", "")),
|
| 50 |
"clinical_checkpoint": str(getattr(args, "clinical_checkpoint", "")),
|
| 51 |
"dermoscopic_checkpoint": str(getattr(args, "dermoscopic_checkpoint", "")),
|
| 52 |
"resume_checkpoint": str(getattr(args, "resume_checkpoint", "")),
|