duyle2408 commited on
Commit
9fcbc4a
·
verified ·
1 Parent(s): 14bc616

Upload train_milk10k_effb2_dual_metadata.py

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