Upload 114 files
Browse files- milk10k_effb2_metadata/MILK10K_EFFB2_METADATA_CLI.md +1 -28
- 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 +3 -2
- milk10k_effb2_metadata/cli.py +1 -53
- milk10k_effb2_metadata/data.py +10 -253
- milk10k_effb2_metadata/engine.py +1 -39
- milk10k_effb2_metadata/inference.py +4 -44
- milk10k_effb2_metadata/losses.py +1 -28
- milk10k_effb2_metadata/model_setup.py +0 -4
- milk10k_effb2_metadata/models.py +4 -33
- milk10k_effb2_metadata/reporting.py +0 -27
- milk10k_effb2_metadata/runner.py +17 -174
- milk10k_effb2_metadata/tests/__pycache__/test_fusion_and_f1_loss.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/training.py +1 -28
- milk10k_effb2_metadata/training_utils.py +0 -1
milk10k_effb2_metadata/MILK10K_EFFB2_METADATA_CLI.md
CHANGED
|
@@ -20,16 +20,11 @@ Training code is split by responsibility:
|
|
| 20 |
```text
|
| 21 |
training.py Thin entry facade: normalize args, load dataframe, choose single run vs k-fold.
|
| 22 |
runner.py Full split runner: split CSVs, loaders, loss, train phases, final metrics/files.
|
| 23 |
-
engine.py Epoch/phase loop: run_epoch, train_phase, save best
|
| 24 |
model_setup.py Backend detection, model construction, resume checkpoint, optimizer param groups.
|
| 25 |
training_utils.py JSON-safe serialization, run_config.json, kfold_summary.csv/json.
|
| 26 |
```
|
| 27 |
|
| 28 |
-
Training always writes both checkpoint types to the run directory:
|
| 29 |
-
|
| 30 |
-
- `best.pt`: epoch with the best configured validation selection metric.
|
| 31 |
-
- `last.pt`: most recently completed epoch, updated after every epoch and also available when early stopping triggers.
|
| 32 |
-
|
| 33 |
Common places to edit:
|
| 34 |
|
| 35 |
```text
|
|
@@ -184,28 +179,6 @@ python train_milk10k_effb2_dual_metadata.py \
|
|
| 184 |
--output-dir milk10k_effb2_sampler_p05
|
| 185 |
```
|
| 186 |
|
| 187 |
-
## Hybrid epoch balancing
|
| 188 |
-
|
| 189 |
-
Use hybrid balancing when the largest class dominates training but inverse-frequency
|
| 190 |
-
loss weights make predictions too soft:
|
| 191 |
-
|
| 192 |
-
```bash
|
| 193 |
-
python train_milk10k_effb2_dual_metadata.py \
|
| 194 |
-
--data-dir /path/to/milk10k \
|
| 195 |
-
--balance-mode hybrid \
|
| 196 |
-
--balance-head-ratio 2.0 \
|
| 197 |
-
--balance-tail-floor 100 \
|
| 198 |
-
--balance-min-source-count 20 \
|
| 199 |
-
--loss ce \
|
| 200 |
-
--output-dir milk10k_effb2_hybrid_balance
|
| 201 |
-
```
|
| 202 |
-
|
| 203 |
-
The largest class is sampled without replacement up to twice the second-largest
|
| 204 |
-
class. Eligible classes below 100 rows are sampled with replacement to 100 rows
|
| 205 |
-
and receive the stronger train transform. Classes with fewer than 20 source rows
|
| 206 |
-
are left unchanged. Sampling changes by epoch and is reproducible from `--seed`.
|
| 207 |
-
Validation is never resampled. Do not combine this mode with `--weighted-sampler`.
|
| 208 |
-
|
| 209 |
Stronger sampling:
|
| 210 |
|
| 211 |
```bash
|
|
|
|
| 20 |
```text
|
| 21 |
training.py Thin entry facade: normalize args, load dataframe, choose single run vs k-fold.
|
| 22 |
runner.py Full split runner: split CSVs, loaders, loss, train phases, final metrics/files.
|
| 23 |
+
engine.py Epoch/phase loop: run_epoch, train_phase, save best checkpoint.
|
| 24 |
model_setup.py Backend detection, model construction, resume checkpoint, optimizer param groups.
|
| 25 |
training_utils.py JSON-safe serialization, run_config.json, kfold_summary.csv/json.
|
| 26 |
```
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
Common places to edit:
|
| 29 |
|
| 30 |
```text
|
|
|
|
| 179 |
--output-dir milk10k_effb2_sampler_p05
|
| 180 |
```
|
| 181 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
Stronger sampling:
|
| 183 |
|
| 184 |
```bash
|
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 = ("
|
| 13 |
-
PREFIXES_TO_STRIP = ("module.", "model.", "
|
| 14 |
|
| 15 |
|
| 16 |
def extract_state_dict(checkpoint: Any) -> dict[str, torch.Tensor]:
|
|
@@ -91,3 +91,4 @@ 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")
|
|
|
|
|
|
| 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 |
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 |
+
|
milk10k_effb2_metadata/cli.py
CHANGED
|
@@ -9,18 +9,6 @@ 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 |
-
"--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,10 +35,7 @@ def parse_args() -> argparse.Namespace:
|
|
| 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,15 +122,6 @@ def parse_args() -> argparse.Namespace:
|
|
| 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,30 +135,6 @@ def parse_args() -> argparse.Namespace:
|
|
| 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,8 +195,4 @@ def parse_args() -> argparse.Namespace:
|
|
| 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="Logit adjustment parameter for Generalized Balanced Softmax")
|
| 247 |
-
parser.add_argument("--lws-epochs", type=int, default=0, help="Number of epochs to train Learnable Weight Scaling (LWS) post-training")
|
| 248 |
-
parser.add_argument("--ema", action="store_true", help="Enable Exponential Moving Average (EMA) for model weights")
|
| 249 |
-
parser.add_argument("--ema-decay", type=float, default=0.999, help="Decay rate for EMA")
|
| 250 |
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 |
"--clinical-checkpoint",
|
| 14 |
type=Path,
|
|
|
|
| 35 |
parser.add_argument(
|
| 36 |
"--backbone",
|
| 37 |
default="efficientnet_b2",
|
| 38 |
+
help="Backbone model architecture (efficientnet_b2, efficientnet_b1, resnet50, convnext_base).",
|
|
|
|
|
|
|
|
|
|
| 39 |
)
|
| 40 |
parser.add_argument(
|
| 41 |
"--num-workers",
|
|
|
|
| 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 |
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 |
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()
|
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,
|
| 15 |
from torchvision import transforms
|
| 16 |
|
| 17 |
from datasets import LABEL_COLUMNS, normalize_image_type
|
|
@@ -19,110 +19,6 @@ 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,8 +28,6 @@ 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,87 +36,24 @@ class PairedMilk10kMetadataDataset(Dataset):
|
|
| 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 =
|
| 159 |
-
|
| 160 |
-
|
| 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"]
|
| 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(
|
| 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,62 +229,6 @@ def make_transforms(image_size: int):
|
|
| 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,24 +237,7 @@ def make_loaders(
|
|
| 462 |
args: argparse.Namespace,
|
| 463 |
) -> tuple[DataLoader, DataLoader]:
|
| 464 |
train_transform, eval_transform = make_transforms(args.image_size)
|
| 465 |
-
|
| 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,8 +245,7 @@ def make_loaders(
|
|
| 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
|
|
|
|
| 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 |
ImageFile.LOAD_TRUNCATED_IMAGES = True
|
| 20 |
|
| 21 |
METADATA_COLUMNS = ("age_approx", "sex", "skin_tone_class", "site")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
|
| 24 |
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 |
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(self, path: str) -> torch.Tensor:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
with Image.open(path) as img:
|
| 45 |
+
image = img.convert("RGB")
|
| 46 |
+
if self.transform is not None:
|
| 47 |
+
image = self.transform(image)
|
|
|
|
| 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(row["dermoscopic_path"]),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
"metadata": torch.from_numpy(self.metadata[idx]),
|
| 56 |
+
"label": torch.tensor(self.labels[idx], dtype=torch.long),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
}
|
| 58 |
|
| 59 |
|
|
|
|
| 229 |
return train_transform, eval_transform
|
| 230 |
|
| 231 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
def make_loaders(
|
| 233 |
train_df: pd.DataFrame,
|
| 234 |
val_df: pd.DataFrame,
|
|
|
|
| 237 |
args: argparse.Namespace,
|
| 238 |
) -> tuple[DataLoader, DataLoader]:
|
| 239 |
train_transform, eval_transform = make_transforms(args.image_size)
|
| 240 |
+
train_ds = PairedMilk10kMetadataDataset(train_df, label_to_idx, metadata_spec, train_transform)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
val_ds = PairedMilk10kMetadataDataset(val_df, label_to_idx, metadata_spec, eval_transform)
|
| 242 |
common = dict(
|
| 243 |
batch_size=args.batch_size,
|
|
|
|
| 245 |
pin_memory=torch.cuda.is_available(),
|
| 246 |
drop_last=False,
|
| 247 |
)
|
| 248 |
+
sampler = build_weighted_sampler(train_ds, args) if args.weighted_sampler else None
|
|
|
|
| 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
|
milk10k_effb2_metadata/engine.py
CHANGED
|
@@ -35,7 +35,6 @@ def run_epoch(
|
|
| 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)
|
|
@@ -66,8 +65,6 @@ def run_epoch(
|
|
| 66 |
loss.backward()
|
| 67 |
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
|
| 68 |
optimizer.step()
|
| 69 |
-
if ema_model is not None:
|
| 70 |
-
ema_model.update_parameters(model)
|
| 71 |
|
| 72 |
batch_size = labels.size(0)
|
| 73 |
total_loss += float(loss.detach().item()) * batch_size
|
|
@@ -164,7 +161,6 @@ def save_checkpoint(
|
|
| 164 |
metadata_spec: dict[str, Any],
|
| 165 |
args: argparse.Namespace,
|
| 166 |
extra: dict[str, Any] | None = None,
|
| 167 |
-
ema_model: nn.Module | None = None,
|
| 168 |
) -> None:
|
| 169 |
payload = {
|
| 170 |
"epoch": epoch,
|
|
@@ -180,8 +176,6 @@ def save_checkpoint(
|
|
| 180 |
"metadata_spec": metadata_spec,
|
| 181 |
"args": json_safe(vars(args)),
|
| 182 |
}
|
| 183 |
-
if ema_model is not None:
|
| 184 |
-
payload["ema_model_state"] = ema_model.state_dict()
|
| 185 |
if extra:
|
| 186 |
payload.update(json_safe(extra))
|
| 187 |
torch.save(payload, path)
|
|
@@ -208,7 +202,6 @@ def train_phase(
|
|
| 208 |
tail_class_names: list[str] | None = None,
|
| 209 |
train_class_counts: dict[str, int] | None = None,
|
| 210 |
best_val_tail_recall: float = float("-inf"),
|
| 211 |
-
ema_model: nn.Module | None = None,
|
| 212 |
) -> tuple[int, float, float]:
|
| 213 |
if num_epochs <= 0:
|
| 214 |
return start_epoch, best_val_f1, best_val_tail_recall
|
|
@@ -229,11 +222,6 @@ def train_phase(
|
|
| 229 |
continue
|
| 230 |
if hasattr(criterion, "set_epoch"):
|
| 231 |
criterion.set_epoch(epoch)
|
| 232 |
-
sampler = getattr(train_loader, "sampler", None)
|
| 233 |
-
if hasattr(sampler, "set_epoch"):
|
| 234 |
-
sampler.set_epoch(epoch)
|
| 235 |
-
if hasattr(sampler, "exposure_summary"):
|
| 236 |
-
print(f"Hybrid balance epoch {epoch:03d}: effective_class_counts={sampler.exposure_summary()}")
|
| 237 |
train_stats = run_epoch(
|
| 238 |
model,
|
| 239 |
train_loader,
|
|
@@ -244,11 +232,9 @@ def train_phase(
|
|
| 244 |
use_amp,
|
| 245 |
tail_class_indices,
|
| 246 |
class_names,
|
| 247 |
-
ema_model=ema_model,
|
| 248 |
)
|
| 249 |
-
eval_model = ema_model if ema_model is not None else model
|
| 250 |
val_stats = run_epoch(
|
| 251 |
-
|
| 252 |
val_loader,
|
| 253 |
criterion,
|
| 254 |
device,
|
|
@@ -297,7 +283,6 @@ def train_phase(
|
|
| 297 |
label_to_idx,
|
| 298 |
metadata_spec,
|
| 299 |
args,
|
| 300 |
-
ema_model=ema_model,
|
| 301 |
)
|
| 302 |
print(
|
| 303 |
f"Saved best checkpoint: phase={phase} epoch={epoch:03d} "
|
|
@@ -326,35 +311,12 @@ def train_phase(
|
|
| 326 |
"train_class_counts": train_class_counts or {},
|
| 327 |
"selection_metric": "val_tail_recall_macro",
|
| 328 |
},
|
| 329 |
-
ema_model=ema_model,
|
| 330 |
)
|
| 331 |
print(
|
| 332 |
f"Saved tail checkpoint: phase={phase} epoch={epoch:03d} "
|
| 333 |
f"best_val_tail_recall_macro={best_val_tail_recall:.4f} path={output_dir / 'tail_best.pt'}"
|
| 334 |
)
|
| 335 |
|
| 336 |
-
save_checkpoint(
|
| 337 |
-
output_dir / "last.pt",
|
| 338 |
-
model,
|
| 339 |
-
optimizer,
|
| 340 |
-
epoch,
|
| 341 |
-
phase,
|
| 342 |
-
best_val_f1,
|
| 343 |
-
class_names,
|
| 344 |
-
label_to_idx,
|
| 345 |
-
metadata_spec,
|
| 346 |
-
args,
|
| 347 |
-
{
|
| 348 |
-
"last_selection_metric": float(val_stats[selection_metric]),
|
| 349 |
-
"last_val_stats": val_stats,
|
| 350 |
-
},
|
| 351 |
-
ema_model=ema_model,
|
| 352 |
-
)
|
| 353 |
-
print(
|
| 354 |
-
f"Saved last checkpoint: phase={phase} epoch={epoch:03d} "
|
| 355 |
-
f"{selection_metric}={val_stats[selection_metric]:.4f} path={output_dir / 'last.pt'}"
|
| 356 |
-
)
|
| 357 |
-
|
| 358 |
if patience_count >= args.patience:
|
| 359 |
print(f"Early stopping {phase} at epoch {epoch}")
|
| 360 |
break
|
|
|
|
| 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)
|
|
|
|
| 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 |
metadata_spec: dict[str, Any],
|
| 162 |
args: argparse.Namespace,
|
| 163 |
extra: dict[str, Any] | None = None,
|
|
|
|
| 164 |
) -> None:
|
| 165 |
payload = {
|
| 166 |
"epoch": epoch,
|
|
|
|
| 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 |
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 |
) -> tuple[int, float, float]:
|
| 206 |
if num_epochs <= 0:
|
| 207 |
return start_epoch, best_val_f1, best_val_tail_recall
|
|
|
|
| 222 |
continue
|
| 223 |
if hasattr(criterion, "set_epoch"):
|
| 224 |
criterion.set_epoch(epoch)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
train_stats = run_epoch(
|
| 226 |
model,
|
| 227 |
train_loader,
|
|
|
|
| 232 |
use_amp,
|
| 233 |
tail_class_indices,
|
| 234 |
class_names,
|
|
|
|
| 235 |
)
|
|
|
|
| 236 |
val_stats = run_epoch(
|
| 237 |
+
model,
|
| 238 |
val_loader,
|
| 239 |
criterion,
|
| 240 |
device,
|
|
|
|
| 283 |
label_to_idx,
|
| 284 |
metadata_spec,
|
| 285 |
args,
|
|
|
|
| 286 |
)
|
| 287 |
print(
|
| 288 |
f"Saved best checkpoint: phase={phase} epoch={epoch:03d} "
|
|
|
|
| 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
|
milk10k_effb2_metadata/inference.py
CHANGED
|
@@ -15,16 +15,7 @@ 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 |
-
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.models import (
|
| 30 |
DualEffB2MetadataClassifier,
|
|
@@ -44,9 +35,9 @@ class InferencePairedDataset(Dataset):
|
|
| 44 |
def __len__(self) -> int:
|
| 45 |
return len(self.df)
|
| 46 |
|
| 47 |
-
def _load_image(self, path: str
|
| 48 |
with Image.open(path) as img:
|
| 49 |
-
image =
|
| 50 |
if self.transform is not None:
|
| 51 |
image = self.transform(image)
|
| 52 |
return image
|
|
@@ -55,10 +46,7 @@ class InferencePairedDataset(Dataset):
|
|
| 55 |
row = self.df.iloc[idx]
|
| 56 |
return {
|
| 57 |
"clinical": self._load_image(row["clinical_path"]),
|
| 58 |
-
"dermoscopic": self._load_image(
|
| 59 |
-
row["dermoscopic_path"],
|
| 60 |
-
row.get(DERMOSCOPIC_MASK_PATH_COLUMN),
|
| 61 |
-
),
|
| 62 |
"metadata": torch.from_numpy(self.metadata[idx]),
|
| 63 |
}
|
| 64 |
|
|
@@ -75,18 +63,6 @@ def parse_args() -> argparse.Namespace:
|
|
| 75 |
parser.add_argument("--data-dir", type=Path, default=None, help="Directory containing MILK10k input/metadata files.")
|
| 76 |
parser.add_argument("--input-dir", type=Path, default=None, help="Image root. Overrides --data-dir/MILK10k_Training_Input.")
|
| 77 |
parser.add_argument("--metadata-csv", type=Path, default=None, help="Metadata CSV. Overrides --data-dir/MILK10k_Training_Metadata.csv.")
|
| 78 |
-
parser.add_argument(
|
| 79 |
-
"--dermoscopic-mask-dir",
|
| 80 |
-
type=Path,
|
| 81 |
-
default=None,
|
| 82 |
-
help="Optional directory containing <lesion_id>_dermoscopic_mask.png files.",
|
| 83 |
-
)
|
| 84 |
-
parser.add_argument(
|
| 85 |
-
"--min-dermoscopic-mask-ratio",
|
| 86 |
-
type=float,
|
| 87 |
-
default=0.01,
|
| 88 |
-
help="Fallback to the original dermoscopic image when mask foreground ratio is below this value.",
|
| 89 |
-
)
|
| 90 |
parser.add_argument("--groundtruth-csv", type=Path, default=None, help="Optional ground-truth CSV for metrics.")
|
| 91 |
parser.add_argument("--output", type=Path, default=Path("test_predictions.csv"))
|
| 92 |
parser.add_argument("--batch-size", type=int, default=16)
|
|
@@ -222,7 +198,6 @@ def build_model_from_checkpoint(checkpoint: dict[str, Any], metadata_dim: int, d
|
|
| 222 |
metadata_fusion=checkpoint_arg(checkpoint_args, "metadata_fusion", "concat"),
|
| 223 |
image_fusion=checkpoint_arg(checkpoint_args, "image_fusion", "concat"),
|
| 224 |
metadata_gate_hidden_dim=checkpoint_args.get("metadata_gate_hidden_dim"),
|
| 225 |
-
classifier_style=checkpoint_arg(checkpoint_args, "classifier_style", "legacy"),
|
| 226 |
logit_fusion_mode=checkpoint_arg(checkpoint_args, "logit_fusion_mode", "single"),
|
| 227 |
fusion_logit_weight=checkpoint_arg(checkpoint_args, "fusion_logit_weight", 0.6),
|
| 228 |
clinical_logit_weight=checkpoint_arg(checkpoint_args, "clinical_logit_weight", 0.2),
|
|
@@ -319,21 +294,6 @@ def main() -> None:
|
|
| 319 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 320 |
input_dir, metadata_csv, groundtruth_csv = resolve_input_paths(args)
|
| 321 |
df = load_inference_dataframe(input_dir, metadata_csv, groundtruth_csv)
|
| 322 |
-
if not 0.0 <= args.min_dermoscopic_mask_ratio <= 1.0:
|
| 323 |
-
raise ValueError("--min-dermoscopic-mask-ratio must be between 0 and 1.")
|
| 324 |
-
if args.dermoscopic_mask_dir is not None:
|
| 325 |
-
args.dermoscopic_mask_dir = args.dermoscopic_mask_dir.expanduser().resolve()
|
| 326 |
-
df, mask_audit = audit_dermoscopic_masks(
|
| 327 |
-
df,
|
| 328 |
-
args.dermoscopic_mask_dir,
|
| 329 |
-
args.min_dermoscopic_mask_ratio,
|
| 330 |
-
mask_id_column="dermoscopic_isic_id",
|
| 331 |
-
mask_suffix="_mask.png",
|
| 332 |
-
)
|
| 333 |
-
audit_output = args.output.with_name(f"{args.output.stem}.mask_audit.csv")
|
| 334 |
-
audit_output.parent.mkdir(parents=True, exist_ok=True)
|
| 335 |
-
mask_audit.to_csv(audit_output, index=False)
|
| 336 |
-
print_mask_audit_summary(mask_audit, args.min_dermoscopic_mask_ratio)
|
| 337 |
checkpoint_paths = resolve_checkpoint_paths(args)
|
| 338 |
ensemble_probs = []
|
| 339 |
class_names: list[str] | None = None
|
|
|
|
| 15 |
from tqdm.auto import tqdm
|
| 16 |
|
| 17 |
from datasets import LABEL_COLUMNS, normalize_image_type
|
| 18 |
+
from milk10k_effb2_metadata.data import METADATA_COLUMNS, make_transforms, metadata_vector, resolve_monet_columns
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
from milk10k_effb2_metadata.metrics import apply_class_bias, compute_metrics
|
| 20 |
from milk10k_effb2_metadata.models import (
|
| 21 |
DualEffB2MetadataClassifier,
|
|
|
|
| 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 = img.convert("RGB")
|
| 41 |
if self.transform is not None:
|
| 42 |
image = self.transform(image)
|
| 43 |
return image
|
|
|
|
| 46 |
row = self.df.iloc[idx]
|
| 47 |
return {
|
| 48 |
"clinical": self._load_image(row["clinical_path"]),
|
| 49 |
+
"dermoscopic": self._load_image(row["dermoscopic_path"]),
|
|
|
|
|
|
|
|
|
|
| 50 |
"metadata": torch.from_numpy(self.metadata[idx]),
|
| 51 |
}
|
| 52 |
|
|
|
|
| 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 |
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),
|
|
|
|
| 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
|
milk10k_effb2_metadata/losses.py
CHANGED
|
@@ -27,28 +27,6 @@ class FocalLoss(nn.Module):
|
|
| 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 |
-
self.tau = tau
|
| 39 |
-
self.weight = weight
|
| 40 |
-
counts = class_counts.float().clamp_min(1.0)
|
| 41 |
-
self.register_buffer("log_counts", torch.log(counts))
|
| 42 |
-
|
| 43 |
-
def forward(self, logits: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
|
| 44 |
-
if self.training and self.tau > 0.0:
|
| 45 |
-
log_counts = self.log_counts.to(device=logits.device, dtype=logits.dtype)
|
| 46 |
-
adjusted_logits = logits + self.tau * log_counts
|
| 47 |
-
else:
|
| 48 |
-
adjusted_logits = logits
|
| 49 |
-
return F.cross_entropy(adjusted_logits, labels, weight=self.weight)
|
| 50 |
-
|
| 51 |
-
|
| 52 |
class LDAMLoss(nn.Module):
|
| 53 |
"""LDAM with deferred effective-number reweighting."""
|
| 54 |
|
|
@@ -201,12 +179,7 @@ def build_loss(train_df: pd.DataFrame, label_to_idx: dict[str, int], args: argpa
|
|
| 201 |
y = np.array([label_to_idx[label] for label in train_df["label"]])
|
| 202 |
weights = compute_class_weight(class_weight="balanced", classes=np.arange(len(label_to_idx)), y=y)
|
| 203 |
weight = torch.tensor(weights, dtype=torch.float32, device=device)
|
| 204 |
-
|
| 205 |
-
if getattr(args, "tau", 0.0) > 0.0:
|
| 206 |
-
counts = class_count_tensor(train_df, label_to_idx, device)
|
| 207 |
-
ce_loss: nn.Module = GeneralizedBalancedSoftmaxLoss(counts, tau=args.tau, weight=weight)
|
| 208 |
-
else:
|
| 209 |
-
ce_loss: nn.Module = nn.CrossEntropyLoss(weight=weight)
|
| 210 |
if args.loss == "focal":
|
| 211 |
return FocalLoss(weight=weight, gamma=args.focal_gamma)
|
| 212 |
if args.loss == "ce_dice":
|
|
|
|
| 27 |
return loss.mean()
|
| 28 |
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
class LDAMLoss(nn.Module):
|
| 31 |
"""LDAM with deferred effective-number reweighting."""
|
| 32 |
|
|
|
|
| 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 |
+
ce_loss: nn.Module = nn.CrossEntropyLoss(weight=weight)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
if args.loss == "focal":
|
| 184 |
return FocalLoss(weight=weight, gamma=args.focal_gamma)
|
| 185 |
if args.loss == "ce_dice":
|
milk10k_effb2_metadata/model_setup.py
CHANGED
|
@@ -103,7 +103,6 @@ def load_resume_checkpoint(
|
|
| 103 |
checkpoint_path: Path | None,
|
| 104 |
model: DualEffB2MetadataClassifier,
|
| 105 |
device: torch.device,
|
| 106 |
-
ema_model: torch.nn.Module | None = None,
|
| 107 |
) -> tuple[int, float, str | None]:
|
| 108 |
if checkpoint_path is None:
|
| 109 |
return 1, float("-inf"), None
|
|
@@ -112,8 +111,6 @@ def load_resume_checkpoint(
|
|
| 112 |
raise FileNotFoundError(f"Resume checkpoint not found: {checkpoint_path}")
|
| 113 |
checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=False)
|
| 114 |
model.load_state_dict(checkpoint["model_state"])
|
| 115 |
-
if ema_model is not None and "ema_model_state" in checkpoint:
|
| 116 |
-
ema_model.load_state_dict(checkpoint["ema_model_state"])
|
| 117 |
next_epoch = int(checkpoint.get("epoch", 0)) + 1
|
| 118 |
best_val_f1 = float(
|
| 119 |
checkpoint.get(
|
|
@@ -155,7 +152,6 @@ def build_model(
|
|
| 155 |
metadata_fusion=args.metadata_fusion,
|
| 156 |
image_fusion=getattr(args, "image_fusion", "concat"),
|
| 157 |
metadata_gate_hidden_dim=args.metadata_gate_hidden_dim,
|
| 158 |
-
classifier_style=getattr(args, "classifier_style", "legacy"),
|
| 159 |
logit_fusion_mode=args.logit_fusion_mode,
|
| 160 |
fusion_logit_weight=args.fusion_logit_weight,
|
| 161 |
clinical_logit_weight=args.clinical_logit_weight,
|
|
|
|
| 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
|
|
|
|
| 111 |
raise FileNotFoundError(f"Resume checkpoint not found: {checkpoint_path}")
|
| 112 |
checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=False)
|
| 113 |
model.load_state_dict(checkpoint["model_state"])
|
|
|
|
|
|
|
| 114 |
next_epoch = int(checkpoint.get("epoch", 0)) + 1
|
| 115 |
best_val_f1 = float(
|
| 116 |
checkpoint.get(
|
|
|
|
| 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,
|
milk10k_effb2_metadata/models.py
CHANGED
|
@@ -107,7 +107,6 @@ class DualEffB2MetadataClassifier(nn.Module):
|
|
| 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,8 +128,6 @@ class DualEffB2MetadataClassifier(nn.Module):
|
|
| 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,7 +135,6 @@ class DualEffB2MetadataClassifier(nn.Module):
|
|
| 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,35 +212,16 @@ class DualEffB2MetadataClassifier(nn.Module):
|
|
| 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 |
-
self.class_scales = nn.Parameter(torch.ones(num_classes))
|
| 232 |
|
| 233 |
@staticmethod
|
| 234 |
-
def _classifier(
|
| 235 |
-
in_dim: int,
|
| 236 |
-
hidden_dim: int,
|
| 237 |
-
num_classes: int,
|
| 238 |
-
dropout: float,
|
| 239 |
-
classifier_style: str,
|
| 240 |
-
) -> nn.Sequential:
|
| 241 |
-
if classifier_style == "simple":
|
| 242 |
-
return nn.Sequential(
|
| 243 |
-
nn.Linear(in_dim, hidden_dim),
|
| 244 |
-
nn.ReLU(),
|
| 245 |
-
nn.Dropout(dropout),
|
| 246 |
-
nn.Linear(hidden_dim, num_classes),
|
| 247 |
-
)
|
| 248 |
return nn.Sequential(
|
| 249 |
nn.LayerNorm(in_dim),
|
| 250 |
nn.Dropout(dropout),
|
|
@@ -310,14 +287,14 @@ class DualEffB2MetadataClassifier(nn.Module):
|
|
| 310 |
fused = self._fused_features(clinical_features, dermoscopic_features, clinical_repr, dermoscopic_repr, metadata_repr)
|
| 311 |
fusion_logits = self.classifier(fused)
|
| 312 |
if self.logit_fusion_mode != "fixed":
|
| 313 |
-
return fusion_logits
|
| 314 |
clinical_logits = self.clinical_classifier(clinical_repr)
|
| 315 |
dermoscopic_logits = self.dermoscopic_classifier(dermoscopic_repr)
|
| 316 |
return (
|
| 317 |
self.fusion_logit_weight * fusion_logits
|
| 318 |
+ self.clinical_logit_weight * clinical_logits
|
| 319 |
+ self.dermoscopic_logit_weight * dermoscopic_logits
|
| 320 |
-
)
|
| 321 |
|
| 322 |
def _append_metadata(self, features: torch.Tensor, metadata_repr: torch.Tensor | None) -> torch.Tensor:
|
| 323 |
if metadata_repr is None:
|
|
@@ -424,8 +401,6 @@ class DualConvNeXtMetadataClassifier(DualEffB2MetadataClassifier):
|
|
| 424 |
|
| 425 |
def normalize_backbone_name(name: str) -> str:
|
| 426 |
name = name.lower().replace(" ", "").replace("_", "").replace("-", "")
|
| 427 |
-
if name in ("tfefficientnetv2b2", "efficientnetv2b2", "effnetv2b2", "effv2b2"):
|
| 428 |
-
return "tf_efficientnetv2_b2"
|
| 429 |
if name in ("efficientnetb2", "effnetb2", "effb2"):
|
| 430 |
return "efficientnet_b2"
|
| 431 |
if name in ("efficientnetb1", "effnetb1", "effb1"):
|
|
@@ -450,8 +425,6 @@ def default_image_size(backbone: str) -> int:
|
|
| 450 |
backbone = normalize_backbone_name(backbone)
|
| 451 |
if backbone == "efficientnet_b2":
|
| 452 |
return 260
|
| 453 |
-
if backbone == "tf_efficientnetv2_b2":
|
| 454 |
-
return 384
|
| 455 |
if backbone == "efficientnet_b1":
|
| 456 |
return 240
|
| 457 |
if backbone == "convnext_base":
|
|
@@ -505,8 +478,6 @@ def build_feature_encoder(backbone: str, backbone_backend: str, imagenet_pretrai
|
|
| 505 |
return model, int(model.num_features)
|
| 506 |
|
| 507 |
if backbone_backend == "torchvision":
|
| 508 |
-
if backbone == "tf_efficientnetv2_b2":
|
| 509 |
-
raise ValueError("tf_efficientnetv2_b2 is only available with --backbone-backend timm.")
|
| 510 |
if backbone == "efficientnet_b2":
|
| 511 |
from torchvision.models import efficientnet_b2, EfficientNet_B2_Weights
|
| 512 |
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 |
logit_fusion_mode: str = "single",
|
| 111 |
fusion_logit_weight: float = 0.6,
|
| 112 |
clinical_logit_weight: float = 0.2,
|
|
|
|
| 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 |
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 |
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 = None if image_fusion == "moe" else self._classifier(fused_dim, classifier_hidden_dim, num_classes, dropout)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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(in_dim: int, hidden_dim: int, num_classes: int, dropout: float) -> nn.Sequential:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
return nn.Sequential(
|
| 226 |
nn.LayerNorm(in_dim),
|
| 227 |
nn.Dropout(dropout),
|
|
|
|
| 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 |
|
| 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 |
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 |
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
|
milk10k_effb2_metadata/reporting.py
CHANGED
|
@@ -95,11 +95,6 @@ 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 |
-
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,7 +102,6 @@ def class_distribution(df: pd.DataFrame, class_names: list[str]) -> dict[str, An
|
|
| 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,21 +353,6 @@ def render_split_summary(data_summary: dict[str, Any]) -> str:
|
|
| 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,13 +380,7 @@ def render_run_report(
|
|
| 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)}",
|
|
|
|
| 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 |
"synthetic_rows": int(is_augmented.sum()),
|
| 103 |
"synthetic_class_counts": augmented_counts,
|
| 104 |
"ignore_metadata_rows": int(ignore_metadata.sum()),
|
|
|
|
| 105 |
}
|
| 106 |
|
| 107 |
|
|
|
|
| 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 |
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)}",
|
milk10k_effb2_metadata/runner.py
CHANGED
|
@@ -12,7 +12,6 @@ import torch
|
|
| 12 |
|
| 13 |
from milk10k_effb2_metadata.data import (
|
| 14 |
fit_metadata_spec,
|
| 15 |
-
hybrid_balance_summary,
|
| 16 |
kfold_splits,
|
| 17 |
lesion_split,
|
| 18 |
load_paired_dataframe,
|
|
@@ -25,89 +24,6 @@ from milk10k_effb2_metadata.metrics import apply_class_bias, compute_metrics, op
|
|
| 25 |
from milk10k_effb2_metadata.model_setup import build_model, load_resume_checkpoint
|
| 26 |
from milk10k_effb2_metadata.reporting import build_data_summary, save_data_summary, save_kfold_report, save_run_diagnostics
|
| 27 |
from milk10k_effb2_metadata.training_utils import json_safe, save_kfold_summary, save_run_config
|
| 28 |
-
import torch.nn.functional as F
|
| 29 |
-
|
| 30 |
-
def train_lws_post_training(
|
| 31 |
-
model: DualEffB2MetadataClassifier,
|
| 32 |
-
train_loader: DataLoader,
|
| 33 |
-
criterion: nn.Module,
|
| 34 |
-
device: torch.device,
|
| 35 |
-
args: argparse.Namespace,
|
| 36 |
-
ema_model: nn.Module | None = None,
|
| 37 |
-
) -> None:
|
| 38 |
-
if args.lws_epochs <= 0:
|
| 39 |
-
return
|
| 40 |
-
|
| 41 |
-
print(f"\nStarting LWS Post-Training for {args.lws_epochs} epochs...")
|
| 42 |
-
model.requires_grad_(False)
|
| 43 |
-
model.class_scales.requires_grad_(True)
|
| 44 |
-
|
| 45 |
-
optimizer = torch.optim.Adam([model.class_scales], lr=args.head_lr)
|
| 46 |
-
|
| 47 |
-
from milk10k_effb2_metadata.data import build_weighted_sampler
|
| 48 |
-
dataset = train_loader.dataset
|
| 49 |
-
# Force weighted sampler for LWS
|
| 50 |
-
lws_sampler = build_weighted_sampler(dataset, args)
|
| 51 |
-
lws_loader = DataLoader(
|
| 52 |
-
dataset,
|
| 53 |
-
batch_size=args.batch_size,
|
| 54 |
-
num_workers=args.num_workers,
|
| 55 |
-
pin_memory=torch.cuda.is_available(),
|
| 56 |
-
sampler=lws_sampler,
|
| 57 |
-
)
|
| 58 |
-
|
| 59 |
-
model.train()
|
| 60 |
-
from milk10k_effb2_metadata.metrics import move_batch
|
| 61 |
-
for epoch in range(1, args.lws_epochs + 1):
|
| 62 |
-
total_loss = 0.0
|
| 63 |
-
for batch in lws_loader:
|
| 64 |
-
clinical, dermoscopic, metadata, labels = move_batch(batch, device)
|
| 65 |
-
optimizer.zero_grad()
|
| 66 |
-
logits = model(clinical, dermoscopic, metadata)
|
| 67 |
-
loss = criterion(logits, labels)
|
| 68 |
-
loss.backward()
|
| 69 |
-
optimizer.step()
|
| 70 |
-
|
| 71 |
-
model.class_scales.data.clamp_(0.75, 1.5)
|
| 72 |
-
|
| 73 |
-
if ema_model is not None:
|
| 74 |
-
ema_model.update_parameters(model)
|
| 75 |
-
|
| 76 |
-
total_loss += loss.item()
|
| 77 |
-
|
| 78 |
-
scales_str = np.array2string(model.class_scales.detach().cpu().numpy(), precision=3, separator=',')
|
| 79 |
-
print(f"LWS Epoch {epoch}/{args.lws_epochs} - Loss: {total_loss / len(lws_loader):.4f} - Scales: {scales_str}")
|
| 80 |
-
|
| 81 |
-
def fit_global_temperature(
|
| 82 |
-
model: nn.Module,
|
| 83 |
-
val_loader: DataLoader,
|
| 84 |
-
device: torch.device,
|
| 85 |
-
) -> float:
|
| 86 |
-
model.eval()
|
| 87 |
-
all_logits = []
|
| 88 |
-
all_labels = []
|
| 89 |
-
from milk10k_effb2_metadata.metrics import move_batch
|
| 90 |
-
with torch.no_grad():
|
| 91 |
-
for batch in val_loader:
|
| 92 |
-
clinical, dermoscopic, metadata, labels = move_batch(batch, device)
|
| 93 |
-
logits = model(clinical, dermoscopic, metadata)
|
| 94 |
-
all_logits.append(logits)
|
| 95 |
-
all_labels.append(labels)
|
| 96 |
-
|
| 97 |
-
all_logits = torch.cat(all_logits)
|
| 98 |
-
all_labels = torch.cat(all_labels)
|
| 99 |
-
|
| 100 |
-
temperature = torch.nn.Parameter(torch.ones(1, device=device))
|
| 101 |
-
optimizer = torch.optim.LBFGS([temperature], lr=0.01, max_iter=50)
|
| 102 |
-
|
| 103 |
-
def eval_fn():
|
| 104 |
-
optimizer.zero_grad()
|
| 105 |
-
loss = F.cross_entropy(all_logits / temperature, all_labels)
|
| 106 |
-
loss.backward()
|
| 107 |
-
return loss
|
| 108 |
-
|
| 109 |
-
optimizer.step(eval_fn)
|
| 110 |
-
return float(temperature.item())
|
| 111 |
|
| 112 |
|
| 113 |
def build_tail_tracking_config(
|
|
@@ -139,11 +55,6 @@ def resolve_label_name(class_names: list[str], name: str) -> str:
|
|
| 139 |
return normalized[key]
|
| 140 |
|
| 141 |
|
| 142 |
-
def source_lesion_id(value: Any) -> str:
|
| 143 |
-
"""Return the original lesion ID for a generated paired lesion ID."""
|
| 144 |
-
return str(value).split("__sdpair_", 1)[0]
|
| 145 |
-
|
| 146 |
-
|
| 147 |
def load_augmented_subset(
|
| 148 |
base_df: pd.DataFrame,
|
| 149 |
class_names: list[str],
|
|
@@ -163,6 +74,14 @@ def load_augmented_subset(
|
|
| 163 |
augmented_max_per_class = getattr(args, "augmented_max_per_class", 0)
|
| 164 |
if augmented_max_per_class < 0:
|
| 165 |
raise ValueError("--augmented-max-per-class must be >= 0.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
augmented_df["is_augmented"] = True
|
| 167 |
augmented_df["ignore_metadata"] = bool(getattr(args, "zero_augmented_metadata", False))
|
| 168 |
return augmented_df
|
|
@@ -171,7 +90,6 @@ def load_augmented_subset(
|
|
| 171 |
def append_augmented_train_rows(
|
| 172 |
base_df: pd.DataFrame,
|
| 173 |
train_df: pd.DataFrame,
|
| 174 |
-
val_df: pd.DataFrame,
|
| 175 |
class_names: list[str],
|
| 176 |
args: argparse.Namespace,
|
| 177 |
) -> pd.DataFrame:
|
|
@@ -180,39 +98,10 @@ def append_augmented_train_rows(
|
|
| 180 |
if getattr(args, "augmented_data_dir", None) is not None:
|
| 181 |
print("Augmented data: no extra rows selected.")
|
| 182 |
return train_df
|
| 183 |
-
train_source_ids = set(train_df["lesion_id"].astype(str).map(source_lesion_id))
|
| 184 |
-
val_source_ids = set(val_df["lesion_id"].astype(str).map(source_lesion_id))
|
| 185 |
-
augmented_df["source_lesion_id"] = augmented_df["lesion_id"].astype(str).map(source_lesion_id)
|
| 186 |
-
source_overlap = train_source_ids & val_source_ids
|
| 187 |
-
if source_overlap:
|
| 188 |
-
raise RuntimeError(
|
| 189 |
-
f"Source leakage already exists between train and validation: {len(source_overlap)} lesion IDs."
|
| 190 |
-
)
|
| 191 |
-
selected = augmented_df["source_lesion_id"].isin(train_source_ids)
|
| 192 |
-
excluded_validation = augmented_df["source_lesion_id"].isin(val_source_ids)
|
| 193 |
-
unknown = ~(selected | excluded_validation)
|
| 194 |
-
if unknown.any():
|
| 195 |
-
examples = augmented_df.loc[unknown, "lesion_id"].astype(str).head(5).tolist()
|
| 196 |
-
raise ValueError(
|
| 197 |
-
"Augmented lesions cannot be mapped to an original train/validation source. "
|
| 198 |
-
f"Examples: {examples}"
|
| 199 |
-
)
|
| 200 |
-
excluded_count = int(excluded_validation.sum())
|
| 201 |
-
augmented_df = augmented_df.loc[selected].copy()
|
| 202 |
-
augmented_max_per_class = getattr(args, "augmented_max_per_class", 0)
|
| 203 |
-
if augmented_max_per_class > 0 and not augmented_df.empty:
|
| 204 |
-
augmented_df = (
|
| 205 |
-
augmented_df.sample(frac=1.0, random_state=args.seed)
|
| 206 |
-
.groupby("label", group_keys=False)
|
| 207 |
-
.head(augmented_max_per_class)
|
| 208 |
-
.sort_values(["label", "lesion_id"])
|
| 209 |
-
.reset_index(drop=True)
|
| 210 |
-
)
|
| 211 |
counts = augmented_df["label"].value_counts().sort_index().to_dict()
|
| 212 |
print(
|
| 213 |
-
"
|
| 214 |
f"rows={len(augmented_df)}, counts={counts}, "
|
| 215 |
-
f"excluded_validation_sources={excluded_count}, "
|
| 216 |
f"zero_metadata={getattr(args, 'zero_augmented_metadata', False)}, "
|
| 217 |
f"source={getattr(args, 'augmented_data_dir', None)}"
|
| 218 |
)
|
|
@@ -238,12 +127,6 @@ def run_training_split(
|
|
| 238 |
train_df.to_csv(split_dir / "train.csv", index=False)
|
| 239 |
val_df.to_csv(split_dir / "val.csv", index=False)
|
| 240 |
data_summary = build_data_summary(df, train_df, val_df, class_names)
|
| 241 |
-
if args.balance_mode == "hybrid":
|
| 242 |
-
data_summary["balance"] = hybrid_balance_summary(
|
| 243 |
-
[label_to_idx[label] for label in train_df["label"].tolist()],
|
| 244 |
-
{idx: label for label, idx in label_to_idx.items()},
|
| 245 |
-
args,
|
| 246 |
-
)
|
| 247 |
save_data_summary(output_dir, data_summary)
|
| 248 |
|
| 249 |
metadata_spec = fit_metadata_spec(train_df)
|
|
@@ -269,13 +152,7 @@ def run_training_split(
|
|
| 269 |
clinical_backbone_backend,
|
| 270 |
dermoscopic_backbone_backend,
|
| 271 |
)
|
| 272 |
-
|
| 273 |
-
ema_model = None
|
| 274 |
-
if getattr(args, "ema", False):
|
| 275 |
-
from torch.optim.swa_utils import AveragedModel, get_ema_multi_avg_fn
|
| 276 |
-
ema_model = AveragedModel(model, multi_avg_fn=get_ema_multi_avg_fn(args.ema_decay))
|
| 277 |
-
|
| 278 |
-
resume_epoch, resume_best_val_f1, resume_phase = load_resume_checkpoint(args.resume_checkpoint, model, device, ema_model=ema_model)
|
| 279 |
train_loader, val_loader = make_loaders(train_df, val_df, label_to_idx, metadata_spec, args)
|
| 280 |
criterion = build_loss(train_df, label_to_idx, args, device)
|
| 281 |
tail_config = build_tail_tracking_config(train_df, class_names, label_to_idx, args)
|
|
@@ -292,12 +169,7 @@ def run_training_split(
|
|
| 292 |
f"metadata_fusion={args.metadata_fusion}, image_fusion={getattr(args, 'image_fusion', 'concat')}, "
|
| 293 |
f"gate_hidden_dim={args.metadata_gate_hidden_dim}"
|
| 294 |
)
|
| 295 |
-
print(
|
| 296 |
-
f"Loss: {args.loss}, class_weight={args.class_weight}, weighted_sampler={args.weighted_sampler}, "
|
| 297 |
-
f"balance_mode={args.balance_mode}"
|
| 298 |
-
)
|
| 299 |
-
if args.balance_mode == "hybrid":
|
| 300 |
-
print(f"Hybrid balance plan: {data_summary['balance']}")
|
| 301 |
if getattr(args, "image_fusion", "concat") == "moe" and args.logit_fusion_mode == "fixed":
|
| 302 |
print("Note: --image-fusion moe already mixes expert logits; --logit-fusion-mode fixed adds extra branch logits.")
|
| 303 |
if args.loss == "ce_f1":
|
|
@@ -341,7 +213,6 @@ def run_training_split(
|
|
| 341 |
skip_freeze_until,
|
| 342 |
**(tail_config or {}),
|
| 343 |
best_val_tail_recall=best_tail_start,
|
| 344 |
-
ema_model=ema_model,
|
| 345 |
)
|
| 346 |
epoch, best_val_f1, best_val_tail_recall = train_phase(
|
| 347 |
"finetune",
|
|
@@ -362,36 +233,18 @@ def run_training_split(
|
|
| 362 |
skip_finetune_until,
|
| 363 |
**(tail_config or {}),
|
| 364 |
best_val_tail_recall=best_val_tail_recall,
|
| 365 |
-
ema_model=ema_model,
|
| 366 |
)
|
| 367 |
|
| 368 |
best_path = output_dir / "best.pt"
|
| 369 |
if best_path.exists():
|
| 370 |
checkpoint = torch.load(best_path, map_location=device, weights_only=False)
|
| 371 |
model.load_state_dict(checkpoint["model_state"])
|
| 372 |
-
|
| 373 |
-
ema_model.load_state_dict(checkpoint["ema_model_state"])
|
| 374 |
-
|
| 375 |
-
eval_model = ema_model if ema_model is not None else model
|
| 376 |
-
|
| 377 |
-
if args.lws_epochs > 0:
|
| 378 |
-
train_lws_post_training(model, train_loader, criterion, device, args, ema_model=ema_model)
|
| 379 |
-
# Re-save best checkpoint to include LWS scales
|
| 380 |
-
checkpoint["model_state"] = model.state_dict()
|
| 381 |
-
if ema_model is not None:
|
| 382 |
-
checkpoint["ema_model_state"] = ema_model.state_dict()
|
| 383 |
-
torch.save(checkpoint, best_path)
|
| 384 |
-
|
| 385 |
-
opt_temp = fit_global_temperature(eval_model, val_loader, device)
|
| 386 |
-
print(f"Optimal Global Temperature (T) = {opt_temp:.4f}")
|
| 387 |
-
|
| 388 |
-
y_true, y_prob = predict(eval_model, val_loader, device)
|
| 389 |
metrics, per_class_df, cm = compute_metrics(y_true, y_prob, class_names)
|
| 390 |
metrics = {
|
| 391 |
"best_selection_metric": float(best_val_f1),
|
| 392 |
"selection_metric_name": args.selection_metric,
|
| 393 |
"best_val_f1_macro": float(best_val_f1) if args.selection_metric == "f1_macro" else None,
|
| 394 |
-
"global_temperature": opt_temp,
|
| 395 |
**metrics,
|
| 396 |
}
|
| 397 |
if tail_config is not None:
|
|
@@ -465,24 +318,14 @@ def train_single_run(
|
|
| 465 |
real_df = df[~synthetic_mask].copy()
|
| 466 |
synthetic_df = df[synthetic_mask].copy()
|
| 467 |
train_df, val_df = lesion_split(real_df, args.val_size, args.seed)
|
| 468 |
-
|
| 469 |
-
val_sources = set(val_df["lesion_id"].astype(str))
|
| 470 |
-
synthetic_df["source_lesion_id"] = synthetic_df["lesion_id"].astype(str).map(source_lesion_id)
|
| 471 |
-
unknown_sources = ~synthetic_df["source_lesion_id"].isin(train_sources | val_sources)
|
| 472 |
-
if unknown_sources.any():
|
| 473 |
-
examples = synthetic_df.loc[unknown_sources, "lesion_id"].astype(str).head(5).tolist()
|
| 474 |
-
raise ValueError(f"Synthetic lesions have unknown source IDs. Examples: {examples}")
|
| 475 |
-
safe_synthetic_df = synthetic_df[synthetic_df["source_lesion_id"].isin(train_sources)].copy()
|
| 476 |
-
excluded_count = int(synthetic_df["source_lesion_id"].isin(val_sources).sum())
|
| 477 |
-
train_df = pd.concat([train_df, safe_synthetic_df], ignore_index=True, sort=False)
|
| 478 |
print(
|
| 479 |
-
f"
|
| 480 |
-
f"synthetic_train={len(
|
| 481 |
-
f"val_real={len(val_df)}"
|
| 482 |
)
|
| 483 |
else:
|
| 484 |
train_df, val_df = lesion_split(df, args.val_size, args.seed)
|
| 485 |
-
train_df = append_augmented_train_rows(df, train_df,
|
| 486 |
return run_training_split(
|
| 487 |
df,
|
| 488 |
train_df,
|
|
@@ -512,7 +355,7 @@ def train_kfold(
|
|
| 512 |
fold_metrics = []
|
| 513 |
for fold_idx, (train_df, val_df) in enumerate(kfold_splits(df, args.k_folds, args.seed)):
|
| 514 |
print(f"\nK-fold {fold_idx + 1}/{args.k_folds}")
|
| 515 |
-
train_df = append_augmented_train_rows(df, train_df,
|
| 516 |
metrics = run_training_split(
|
| 517 |
df,
|
| 518 |
train_df,
|
|
|
|
| 12 |
|
| 13 |
from milk10k_effb2_metadata.data import (
|
| 14 |
fit_metadata_spec,
|
|
|
|
| 15 |
kfold_splits,
|
| 16 |
lesion_split,
|
| 17 |
load_paired_dataframe,
|
|
|
|
| 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(
|
|
|
|
| 55 |
return normalized[key]
|
| 56 |
|
| 57 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
def load_augmented_subset(
|
| 59 |
base_df: pd.DataFrame,
|
| 60 |
class_names: list[str],
|
|
|
|
| 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 |
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 |
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 |
+
"Augmented train append: "
|
| 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 |
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 |
clinical_backbone_backend,
|
| 153 |
dermoscopic_backbone_backend,
|
| 154 |
)
|
| 155 |
+
resume_epoch, resume_best_val_f1, resume_phase = load_resume_checkpoint(args.resume_checkpoint, model, device)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
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(f"Loss: {args.loss}, class_weight={args.class_weight}, weighted_sampler={args.weighted_sampler}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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":
|
|
|
|
| 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",
|
|
|
|
| 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(best_val_f1),
|
| 246 |
"selection_metric_name": args.selection_metric,
|
| 247 |
"best_val_f1_macro": float(best_val_f1) if args.selection_metric == "f1_macro" else None,
|
|
|
|
| 248 |
**metrics,
|
| 249 |
}
|
| 250 |
if tail_config is not None:
|
|
|
|
| 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 |
+
train_df = pd.concat([train_df, synthetic_df], ignore_index=True, sort=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 322 |
print(
|
| 323 |
+
f"Synthetic train-only split: real_train={len(train_df) - len(synthetic_df)}, "
|
| 324 |
+
f"synthetic_train={len(synthetic_df)}, val_real={len(val_df)}"
|
|
|
|
| 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 |
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,
|
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,33 +7,17 @@ import argparse
|
|
| 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 |
-
|
| 20 |
-
|
| 21 |
def run(args: argparse.Namespace) -> None:
|
| 22 |
import torch
|
| 23 |
|
| 24 |
from datasets import resolve_data_dir, set_seed
|
| 25 |
-
from milk10k_effb2_metadata.data import
|
| 26 |
-
audit_dermoscopic_masks,
|
| 27 |
-
load_paired_dataframe,
|
| 28 |
-
print_mask_audit_summary,
|
| 29 |
-
)
|
| 30 |
from milk10k_effb2_metadata.model_setup import resolve_training_backbone_backends
|
| 31 |
from milk10k_effb2_metadata.models import normalize_backbone_name, resolve_image_size
|
| 32 |
from milk10k_effb2_metadata.runner import train_kfold, train_single_run
|
| 33 |
|
| 34 |
if args.k_folds < 1:
|
| 35 |
raise ValueError("--k-folds must be at least 1.")
|
| 36 |
-
validate_balance_args(args)
|
| 37 |
|
| 38 |
set_seed(args.seed)
|
| 39 |
data_dir = resolve_data_dir(args.data_dir)
|
|
@@ -47,17 +31,6 @@ def run(args: argparse.Namespace) -> None:
|
|
| 47 |
args.image_size = resolve_image_size(args.backbone, args.image_size)
|
| 48 |
|
| 49 |
df = load_paired_dataframe(data_dir)
|
| 50 |
-
if not 0.0 <= args.min_dermoscopic_mask_ratio <= 1.0:
|
| 51 |
-
raise ValueError("--min-dermoscopic-mask-ratio must be between 0 and 1.")
|
| 52 |
-
if args.dermoscopic_mask_dir is not None:
|
| 53 |
-
args.dermoscopic_mask_dir = args.dermoscopic_mask_dir.expanduser().resolve()
|
| 54 |
-
df, mask_audit = audit_dermoscopic_masks(
|
| 55 |
-
df,
|
| 56 |
-
args.dermoscopic_mask_dir,
|
| 57 |
-
args.min_dermoscopic_mask_ratio,
|
| 58 |
-
)
|
| 59 |
-
mask_audit.to_csv(args.output_dir / "dermoscopic_mask_audit.csv", index=False)
|
| 60 |
-
print_mask_audit_summary(mask_audit, args.min_dermoscopic_mask_ratio)
|
| 61 |
class_names = sorted(df["label"].unique())
|
| 62 |
label_to_idx = {label: idx for idx, label in enumerate(class_names)}
|
| 63 |
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 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 load_paired_dataframe
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
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")
|
milk10k_effb2_metadata/training_utils.py
CHANGED
|
@@ -46,7 +46,6 @@ def save_run_config(
|
|
| 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", "")),
|
|
|
|
| 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", "")),
|