Upload milk10k code
Browse files
milk10k_effb2_metadata/engine.py
CHANGED
|
@@ -9,7 +9,13 @@ from typing import Any
|
|
| 9 |
import numpy as np
|
| 10 |
import pandas as pd
|
| 11 |
import torch
|
| 12 |
-
from sklearn.metrics import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
from torch import nn
|
| 14 |
from torch.amp import GradScaler, autocast
|
| 15 |
from torch.utils.data import DataLoader
|
|
@@ -47,6 +53,14 @@ def run_epoch(
|
|
| 47 |
total = 0
|
| 48 |
preds_all = []
|
| 49 |
labels_all = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
for batch in tqdm(loader, leave=False):
|
| 52 |
clinical, dermoscopic, metadata, labels = move_batch(batch, device)
|
|
@@ -58,6 +72,7 @@ def run_epoch(
|
|
| 58 |
output = model(clinical, dermoscopic, metadata)
|
| 59 |
loss = criterion(output, labels)
|
| 60 |
logits = main_logits(output)
|
|
|
|
| 61 |
if training:
|
| 62 |
if scaler is not None and use_amp:
|
| 63 |
scaler.scale(loss).backward()
|
|
@@ -80,6 +95,15 @@ def run_epoch(
|
|
| 80 |
total += batch_size
|
| 81 |
preds_all.append(logits.argmax(dim=1).detach().cpu().numpy())
|
| 82 |
labels_all.append(labels.detach().cpu().numpy())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
y_pred = np.concatenate(preds_all) if preds_all else np.array([])
|
| 85 |
y_true = np.concatenate(labels_all) if labels_all else np.array([])
|
|
@@ -128,6 +152,23 @@ def run_epoch(
|
|
| 128 |
zero_division=0,
|
| 129 |
)[1]
|
| 130 |
stats["tail_recall_macro"] = float(np.mean(recalls)) if len(recalls) else 0.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
return stats
|
| 132 |
|
| 133 |
|
|
@@ -287,13 +328,21 @@ def train_phase(
|
|
| 287 |
row["selected_variant"] = epoch_variant
|
| 288 |
history.append(row)
|
| 289 |
pd.DataFrame(history).to_csv(output_dir / "history.csv", index=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
print(
|
| 291 |
f"{phase} epoch {epoch:03d}: "
|
| 292 |
f"train_loss={train_stats['loss']:.4f} val_loss={val_stats['loss']:.4f} "
|
| 293 |
f"train_bal_acc={train_stats['balanced_accuracy']:.4f} train_f1={train_stats['f1_macro']:.4f} "
|
| 294 |
f"val_acc={val_stats['accuracy']:.4f} val_bal_acc={val_stats['balanced_accuracy']:.4f} "
|
| 295 |
f"val_f1={val_stats['f1_macro']:.4f} val_dice={val_stats.get('dice_macro', 0.0):.4f} "
|
| 296 |
-
f"val_top3={val_stats['top3_accuracy']:.4f} selected={epoch_variant}"
|
| 297 |
)
|
| 298 |
for variant, stats, variant_model in candidates:
|
| 299 |
if stats[selection_metric] <= variant_best.get(variant, float("-inf")):
|
|
|
|
| 9 |
import numpy as np
|
| 10 |
import pandas as pd
|
| 11 |
import torch
|
| 12 |
+
from sklearn.metrics import (
|
| 13 |
+
average_precision_score,
|
| 14 |
+
balanced_accuracy_score,
|
| 15 |
+
confusion_matrix,
|
| 16 |
+
precision_recall_fscore_support,
|
| 17 |
+
roc_auc_score,
|
| 18 |
+
)
|
| 19 |
from torch import nn
|
| 20 |
from torch.amp import GradScaler, autocast
|
| 21 |
from torch.utils.data import DataLoader
|
|
|
|
| 53 |
total = 0
|
| 54 |
preds_all = []
|
| 55 |
labels_all = []
|
| 56 |
+
aux_probs_all = []
|
| 57 |
+
aux_preds_all = []
|
| 58 |
+
aux_targets_all = []
|
| 59 |
+
aux_class_indices = None
|
| 60 |
+
aux_inf_idx = None
|
| 61 |
+
if class_names and all(name in class_names for name in ("INF", "BCC", "DF", "AKIEC")):
|
| 62 |
+
aux_inf_idx = class_names.index("INF")
|
| 63 |
+
aux_class_indices = [class_names.index(name) for name in ("INF", "BCC", "DF", "AKIEC")]
|
| 64 |
|
| 65 |
for batch in tqdm(loader, leave=False):
|
| 66 |
clinical, dermoscopic, metadata, labels = move_batch(batch, device)
|
|
|
|
| 72 |
output = model(clinical, dermoscopic, metadata)
|
| 73 |
loss = criterion(output, labels)
|
| 74 |
logits = main_logits(output)
|
| 75 |
+
aux_logits = output.get("inf_aux_logits") if isinstance(output, dict) else None
|
| 76 |
if training:
|
| 77 |
if scaler is not None and use_amp:
|
| 78 |
scaler.scale(loss).backward()
|
|
|
|
| 95 |
total += batch_size
|
| 96 |
preds_all.append(logits.argmax(dim=1).detach().cpu().numpy())
|
| 97 |
labels_all.append(labels.detach().cpu().numpy())
|
| 98 |
+
if aux_logits is not None and aux_class_indices is not None and aux_inf_idx is not None:
|
| 99 |
+
aux_mask = torch.isin(labels, torch.tensor(aux_class_indices, device=labels.device))
|
| 100 |
+
if bool(aux_mask.any()):
|
| 101 |
+
aux_targets = (labels[aux_mask] == aux_inf_idx).long()
|
| 102 |
+
aux_probs = torch.softmax(aux_logits[aux_mask], dim=1)[:, 1]
|
| 103 |
+
aux_preds = aux_logits[aux_mask].argmax(dim=1)
|
| 104 |
+
aux_targets_all.append(aux_targets.detach().cpu().numpy())
|
| 105 |
+
aux_probs_all.append(aux_probs.detach().cpu().numpy())
|
| 106 |
+
aux_preds_all.append(aux_preds.detach().cpu().numpy())
|
| 107 |
|
| 108 |
y_pred = np.concatenate(preds_all) if preds_all else np.array([])
|
| 109 |
y_true = np.concatenate(labels_all) if labels_all else np.array([])
|
|
|
|
| 152 |
zero_division=0,
|
| 153 |
)[1]
|
| 154 |
stats["tail_recall_macro"] = float(np.mean(recalls)) if len(recalls) else 0.0
|
| 155 |
+
if aux_targets_all:
|
| 156 |
+
aux_true = np.concatenate(aux_targets_all)
|
| 157 |
+
aux_prob = np.concatenate(aux_probs_all)
|
| 158 |
+
aux_pred = np.concatenate(aux_preds_all)
|
| 159 |
+
aux_precision, aux_recall = precision_recall_fscore_support(
|
| 160 |
+
aux_true,
|
| 161 |
+
aux_pred,
|
| 162 |
+
labels=[1],
|
| 163 |
+
average=None,
|
| 164 |
+
zero_division=0,
|
| 165 |
+
)[:2]
|
| 166 |
+
stats["aux_INF_precision"] = float(aux_precision[0])
|
| 167 |
+
stats["aux_INF_recall"] = float(aux_recall[0])
|
| 168 |
+
stats["aux_INF_AP"] = float(average_precision_score(aux_true, aux_prob)) if aux_true.sum() else 0.0
|
| 169 |
+
stats["aux_INF_vs_confusers_AUC"] = float(roc_auc_score(aux_true, aux_prob)) if len(np.unique(aux_true)) == 2 else 0.0
|
| 170 |
+
stats["aux_INF_vs_confusers_support"] = float(len(aux_true))
|
| 171 |
+
stats["aux_INF_support"] = float(aux_true.sum())
|
| 172 |
return stats
|
| 173 |
|
| 174 |
|
|
|
|
| 328 |
row["selected_variant"] = epoch_variant
|
| 329 |
history.append(row)
|
| 330 |
pd.DataFrame(history).to_csv(output_dir / "history.csv", index=False)
|
| 331 |
+
aux_text = ""
|
| 332 |
+
if "aux_INF_vs_confusers_AUC" in val_stats:
|
| 333 |
+
aux_text = (
|
| 334 |
+
f" val_aux_auc={val_stats['aux_INF_vs_confusers_AUC']:.4f}"
|
| 335 |
+
f" val_aux_ap={val_stats['aux_INF_AP']:.4f}"
|
| 336 |
+
f" val_aux_recall={val_stats['aux_INF_recall']:.4f}"
|
| 337 |
+
f" val_aux_precision={val_stats['aux_INF_precision']:.4f}"
|
| 338 |
+
)
|
| 339 |
print(
|
| 340 |
f"{phase} epoch {epoch:03d}: "
|
| 341 |
f"train_loss={train_stats['loss']:.4f} val_loss={val_stats['loss']:.4f} "
|
| 342 |
f"train_bal_acc={train_stats['balanced_accuracy']:.4f} train_f1={train_stats['f1_macro']:.4f} "
|
| 343 |
f"val_acc={val_stats['accuracy']:.4f} val_bal_acc={val_stats['balanced_accuracy']:.4f} "
|
| 344 |
f"val_f1={val_stats['f1_macro']:.4f} val_dice={val_stats.get('dice_macro', 0.0):.4f} "
|
| 345 |
+
f"val_top3={val_stats['top3_accuracy']:.4f}{aux_text} selected={epoch_variant}"
|
| 346 |
)
|
| 347 |
for variant, stats, variant_model in candidates:
|
| 348 |
if stats[selection_metric] <= variant_best.get(variant, float("-inf")):
|
milk10k_effb2_metadata/inference.py
CHANGED
|
@@ -25,7 +25,7 @@ from milk10k_effb2_metadata.data import (
|
|
| 25 |
print_mask_audit_summary,
|
| 26 |
resolve_monet_columns,
|
| 27 |
)
|
| 28 |
-
from milk10k_effb2_metadata.losses import main_logits
|
| 29 |
from milk10k_effb2_metadata.metrics import apply_class_bias, compute_metrics
|
| 30 |
from milk10k_effb2_metadata.model_setup import load_model_state_compat
|
| 31 |
from milk10k_effb2_metadata.models import (
|
|
@@ -236,7 +236,7 @@ def build_model_from_checkpoint(checkpoint: dict[str, Any], metadata_dim: int, d
|
|
| 236 |
fusion_logit_weight=checkpoint_arg(checkpoint_args, "fusion_logit_weight", 0.6),
|
| 237 |
clinical_logit_weight=checkpoint_arg(checkpoint_args, "clinical_logit_weight", 0.2),
|
| 238 |
dermoscopic_logit_weight=checkpoint_arg(checkpoint_args, "dermoscopic_logit_weight", 0.2),
|
| 239 |
-
inf_aux=
|
| 240 |
).to(device)
|
| 241 |
load_model_state_compat(model, state)
|
| 242 |
model.eval()
|
|
|
|
| 25 |
print_mask_audit_summary,
|
| 26 |
resolve_monet_columns,
|
| 27 |
)
|
| 28 |
+
from milk10k_effb2_metadata.losses import inf_aux_enabled, main_logits
|
| 29 |
from milk10k_effb2_metadata.metrics import apply_class_bias, compute_metrics
|
| 30 |
from milk10k_effb2_metadata.model_setup import load_model_state_compat
|
| 31 |
from milk10k_effb2_metadata.models import (
|
|
|
|
| 236 |
fusion_logit_weight=checkpoint_arg(checkpoint_args, "fusion_logit_weight", 0.6),
|
| 237 |
clinical_logit_weight=checkpoint_arg(checkpoint_args, "clinical_logit_weight", 0.2),
|
| 238 |
dermoscopic_logit_weight=checkpoint_arg(checkpoint_args, "dermoscopic_logit_weight", 0.2),
|
| 239 |
+
inf_aux=inf_aux_enabled(checkpoint_args),
|
| 240 |
).to(device)
|
| 241 |
load_model_state_compat(model, state)
|
| 242 |
model.eval()
|
milk10k_effb2_metadata/losses.py
CHANGED
|
@@ -147,6 +147,11 @@ def main_logits(output: torch.Tensor | dict[str, torch.Tensor]) -> torch.Tensor:
|
|
| 147 |
return output
|
| 148 |
|
| 149 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
class InfAuxLossWrapper(nn.Module):
|
| 151 |
def __init__(
|
| 152 |
self,
|
|
@@ -167,6 +172,10 @@ class InfAuxLossWrapper(nn.Module):
|
|
| 167 |
self.main_loss.train(mode)
|
| 168 |
return super().train(mode)
|
| 169 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
def forward(self, output: torch.Tensor | dict[str, torch.Tensor], labels: torch.Tensor) -> torch.Tensor:
|
| 171 |
logits = main_logits(output)
|
| 172 |
loss = self.main_loss(logits, labels)
|
|
@@ -232,37 +241,37 @@ def f1_class_weight_tensor(label_to_idx: dict[str, int], args: argparse.Namespac
|
|
| 232 |
def build_loss(train_df: pd.DataFrame, label_to_idx: dict[str, int], args: argparse.Namespace, device: torch.device) -> nn.Module:
|
| 233 |
if args.loss == "ldam":
|
| 234 |
counts = class_count_tensor(train_df, label_to_idx, device)
|
| 235 |
-
|
| 236 |
class_counts=counts,
|
| 237 |
beta=args.ldam_beta,
|
| 238 |
max_margin=args.ldam_max_margin,
|
| 239 |
deferred_start_epoch=args.ldam_drw_start_epoch,
|
| 240 |
alpha_max=args.ldam_alpha_max,
|
| 241 |
)
|
| 242 |
-
|
| 243 |
-
weight = None
|
| 244 |
-
if args.class_weight:
|
| 245 |
-
y = np.array([label_to_idx[label] for label in train_df["label"]])
|
| 246 |
-
weights = compute_class_weight(class_weight="balanced", classes=np.arange(len(label_to_idx)), y=y)
|
| 247 |
-
weight = torch.tensor(weights, dtype=torch.float32, device=device)
|
| 248 |
-
|
| 249 |
-
if getattr(args, "tau", 0.0) > 0.0:
|
| 250 |
-
if args.class_weight:
|
| 251 |
-
raise ValueError("--tau > 0 cannot be combined with --class-weight.")
|
| 252 |
-
counts = class_count_tensor(train_df, label_to_idx, device)
|
| 253 |
-
ce_loss: nn.Module = GeneralizedBalancedSoftmaxLoss(counts, tau=args.tau)
|
| 254 |
-
else:
|
| 255 |
-
ce_loss: nn.Module = nn.CrossEntropyLoss(weight=weight)
|
| 256 |
-
if args.loss == "focal":
|
| 257 |
-
main_loss: nn.Module = FocalLoss(weight=weight, gamma=args.focal_gamma)
|
| 258 |
-
elif args.loss == "ce_dice":
|
| 259 |
-
main_loss = CompositeClassificationLoss(ce_loss, SoftMacroDiceLoss(), args.dice_weight)
|
| 260 |
-
elif args.loss == "ce_f1":
|
| 261 |
-
main_loss = CompositeClassificationLoss(ce_loss, SoftMacroF1Loss(f1_class_weight_tensor(label_to_idx, args, device)), args.f1_weight)
|
| 262 |
else:
|
| 263 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
|
| 265 |
-
if
|
| 266 |
if "INF" not in label_to_idx:
|
| 267 |
raise ValueError("--inf-aux requires class INF.")
|
| 268 |
confusers = [label_to_idx[resolve_label_name(label_to_idx, name)] for name in args.inf_aux_confusers]
|
|
|
|
| 147 |
return output
|
| 148 |
|
| 149 |
|
| 150 |
+
def inf_aux_enabled(args: argparse.Namespace | dict) -> bool:
|
| 151 |
+
getter = args.get if isinstance(args, dict) else lambda key, default=None: getattr(args, key, default)
|
| 152 |
+
return bool(getter("inf_aux", False) and float(getter("inf_aux_weight", 0.0)) > 0.0)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
class InfAuxLossWrapper(nn.Module):
|
| 156 |
def __init__(
|
| 157 |
self,
|
|
|
|
| 172 |
self.main_loss.train(mode)
|
| 173 |
return super().train(mode)
|
| 174 |
|
| 175 |
+
def set_epoch(self, epoch: int) -> None:
|
| 176 |
+
if hasattr(self.main_loss, "set_epoch"):
|
| 177 |
+
self.main_loss.set_epoch(epoch)
|
| 178 |
+
|
| 179 |
def forward(self, output: torch.Tensor | dict[str, torch.Tensor], labels: torch.Tensor) -> torch.Tensor:
|
| 180 |
logits = main_logits(output)
|
| 181 |
loss = self.main_loss(logits, labels)
|
|
|
|
| 241 |
def build_loss(train_df: pd.DataFrame, label_to_idx: dict[str, int], args: argparse.Namespace, device: torch.device) -> nn.Module:
|
| 242 |
if args.loss == "ldam":
|
| 243 |
counts = class_count_tensor(train_df, label_to_idx, device)
|
| 244 |
+
main_loss: nn.Module = LDAMLoss(
|
| 245 |
class_counts=counts,
|
| 246 |
beta=args.ldam_beta,
|
| 247 |
max_margin=args.ldam_max_margin,
|
| 248 |
deferred_start_epoch=args.ldam_drw_start_epoch,
|
| 249 |
alpha_max=args.ldam_alpha_max,
|
| 250 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
else:
|
| 252 |
+
weight = None
|
| 253 |
+
if args.class_weight:
|
| 254 |
+
y = np.array([label_to_idx[label] for label in train_df["label"]])
|
| 255 |
+
weights = compute_class_weight(class_weight="balanced", classes=np.arange(len(label_to_idx)), y=y)
|
| 256 |
+
weight = torch.tensor(weights, dtype=torch.float32, device=device)
|
| 257 |
+
|
| 258 |
+
if getattr(args, "tau", 0.0) > 0.0:
|
| 259 |
+
if args.class_weight:
|
| 260 |
+
raise ValueError("--tau > 0 cannot be combined with --class-weight.")
|
| 261 |
+
counts = class_count_tensor(train_df, label_to_idx, device)
|
| 262 |
+
ce_loss: nn.Module = GeneralizedBalancedSoftmaxLoss(counts, tau=args.tau)
|
| 263 |
+
else:
|
| 264 |
+
ce_loss: nn.Module = nn.CrossEntropyLoss(weight=weight)
|
| 265 |
+
if args.loss == "focal":
|
| 266 |
+
main_loss = FocalLoss(weight=weight, gamma=args.focal_gamma)
|
| 267 |
+
elif args.loss == "ce_dice":
|
| 268 |
+
main_loss = CompositeClassificationLoss(ce_loss, SoftMacroDiceLoss(), args.dice_weight)
|
| 269 |
+
elif args.loss == "ce_f1":
|
| 270 |
+
main_loss = CompositeClassificationLoss(ce_loss, SoftMacroF1Loss(f1_class_weight_tensor(label_to_idx, args, device)), args.f1_weight)
|
| 271 |
+
else:
|
| 272 |
+
main_loss = ce_loss
|
| 273 |
|
| 274 |
+
if inf_aux_enabled(args):
|
| 275 |
if "INF" not in label_to_idx:
|
| 276 |
raise ValueError("--inf-aux requires class INF.")
|
| 277 |
confusers = [label_to_idx[resolve_label_name(label_to_idx, name)] for name in args.inf_aux_confusers]
|
milk10k_effb2_metadata/model_setup.py
CHANGED
|
@@ -12,6 +12,7 @@ from milk10k_effb2_metadata.checkpoints import (
|
|
| 12 |
load_encoder_checkpoint,
|
| 13 |
resolve_backbone_backends,
|
| 14 |
)
|
|
|
|
| 15 |
from milk10k_effb2_metadata.models import (
|
| 16 |
DualEffB2MetadataClassifier,
|
| 17 |
is_one_encoder_image_fusion,
|
|
@@ -200,7 +201,7 @@ def build_model(
|
|
| 200 |
fusion_logit_weight=args.fusion_logit_weight,
|
| 201 |
clinical_logit_weight=args.clinical_logit_weight,
|
| 202 |
dermoscopic_logit_weight=args.dermoscopic_logit_weight,
|
| 203 |
-
inf_aux=
|
| 204 |
).to(device)
|
| 205 |
if args.resume_checkpoint is None and not is_one_encoder_image_fusion(getattr(args, "image_fusion", "concat")):
|
| 206 |
if args.clinical_checkpoint is not None:
|
|
|
|
| 12 |
load_encoder_checkpoint,
|
| 13 |
resolve_backbone_backends,
|
| 14 |
)
|
| 15 |
+
from milk10k_effb2_metadata.losses import inf_aux_enabled
|
| 16 |
from milk10k_effb2_metadata.models import (
|
| 17 |
DualEffB2MetadataClassifier,
|
| 18 |
is_one_encoder_image_fusion,
|
|
|
|
| 201 |
fusion_logit_weight=args.fusion_logit_weight,
|
| 202 |
clinical_logit_weight=args.clinical_logit_weight,
|
| 203 |
dermoscopic_logit_weight=args.dermoscopic_logit_weight,
|
| 204 |
+
inf_aux=inf_aux_enabled(args),
|
| 205 |
).to(device)
|
| 206 |
if args.resume_checkpoint is None and not is_one_encoder_image_fusion(getattr(args, "image_fusion", "concat")):
|
| 207 |
if args.clinical_checkpoint is not None:
|
milk10k_effb2_metadata/runner.py
CHANGED
|
@@ -24,7 +24,7 @@ from milk10k_effb2_metadata.data import (
|
|
| 24 |
metadata_vector,
|
| 25 |
)
|
| 26 |
from milk10k_effb2_metadata.engine import train_phase
|
| 27 |
-
from milk10k_effb2_metadata.losses import build_loss, main_logits
|
| 28 |
from milk10k_effb2_metadata.metrics import apply_class_bias, compute_metrics, optimize_class_bias, predict, save_predictions
|
| 29 |
from milk10k_effb2_metadata.model_setup import build_model, load_model_state_compat, load_resume_checkpoint
|
| 30 |
from milk10k_effb2_metadata.models import DualEffB2MetadataClassifier
|
|
@@ -371,7 +371,7 @@ def run_training_split(
|
|
| 371 |
)
|
| 372 |
if args.inf_aux:
|
| 373 |
print(
|
| 374 |
-
f"INF aux: weight={args.inf_aux_weight}, confusers={args.inf_aux_confusers}, "
|
| 375 |
f"pos_weight={args.inf_aux_pos_weight}"
|
| 376 |
)
|
| 377 |
if args.balance_mode == "hybrid":
|
|
|
|
| 24 |
metadata_vector,
|
| 25 |
)
|
| 26 |
from milk10k_effb2_metadata.engine import train_phase
|
| 27 |
+
from milk10k_effb2_metadata.losses import build_loss, inf_aux_enabled, main_logits
|
| 28 |
from milk10k_effb2_metadata.metrics import apply_class_bias, compute_metrics, optimize_class_bias, predict, save_predictions
|
| 29 |
from milk10k_effb2_metadata.model_setup import build_model, load_model_state_compat, load_resume_checkpoint
|
| 30 |
from milk10k_effb2_metadata.models import DualEffB2MetadataClassifier
|
|
|
|
| 371 |
)
|
| 372 |
if args.inf_aux:
|
| 373 |
print(
|
| 374 |
+
f"INF aux: active={inf_aux_enabled(args)}, weight={args.inf_aux_weight}, confusers={args.inf_aux_confusers}, "
|
| 375 |
f"pos_weight={args.inf_aux_pos_weight}"
|
| 376 |
)
|
| 377 |
if args.balance_mode == "hybrid":
|
tests/test_fusion_and_f1_loss.py
CHANGED
|
@@ -19,9 +19,18 @@ if MISSING_DEPENDENCY is None:
|
|
| 19 |
import numpy as np
|
| 20 |
import pandas as pd
|
| 21 |
from PIL import Image
|
|
|
|
| 22 |
from milk10k_effb2_metadata.data import PairedMilk10kMetadataDataset
|
|
|
|
| 23 |
from milk10k_effb2_metadata.inference import build_model_from_checkpoint
|
| 24 |
-
from milk10k_effb2_metadata.losses import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
from milk10k_effb2_metadata.models import DualEffB2MetadataClassifier
|
| 26 |
except ModuleNotFoundError as exc: # pragma: no cover - local minimal env may omit ML deps.
|
| 27 |
MISSING_DEPENDENCY = exc.name
|
|
@@ -54,6 +63,21 @@ if MISSING_DEPENDENCY is None:
|
|
| 54 |
return FakeEncoder(feature_dim), feature_dim
|
| 55 |
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
class FusionSmokeTest(unittest.TestCase):
|
| 58 |
def test_all_image_and_metadata_fusions_forward(self) -> None:
|
| 59 |
modes = [
|
|
@@ -202,6 +226,42 @@ if MISSING_DEPENDENCY is None:
|
|
| 202 |
self.assertEqual(tuple(output["inf_aux_logits"].shape), (2, 2))
|
| 203 |
self.assertEqual(tuple(main_logits(output).shape), (2, 11))
|
| 204 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
|
| 206 |
class MetadataAugmentationTest(unittest.TestCase):
|
| 207 |
def test_image_transform_does_not_change_metadata(self) -> None:
|
|
@@ -274,6 +334,33 @@ if MISSING_DEPENDENCY is None:
|
|
| 274 |
with_aux.backward()
|
| 275 |
self.assertIsNotNone(output["inf_aux_logits"].grad)
|
| 276 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 277 |
|
| 278 |
if __name__ == "__main__":
|
| 279 |
unittest.main()
|
|
|
|
| 19 |
import numpy as np
|
| 20 |
import pandas as pd
|
| 21 |
from PIL import Image
|
| 22 |
+
from torch.utils.data import DataLoader, Dataset
|
| 23 |
from milk10k_effb2_metadata.data import PairedMilk10kMetadataDataset
|
| 24 |
+
from milk10k_effb2_metadata.engine import run_epoch
|
| 25 |
from milk10k_effb2_metadata.inference import build_model_from_checkpoint
|
| 26 |
+
from milk10k_effb2_metadata.losses import (
|
| 27 |
+
InfAuxLossWrapper,
|
| 28 |
+
SoftMacroF1Loss,
|
| 29 |
+
build_loss,
|
| 30 |
+
f1_class_weight_tensor,
|
| 31 |
+
inf_aux_enabled,
|
| 32 |
+
main_logits,
|
| 33 |
+
)
|
| 34 |
from milk10k_effb2_metadata.models import DualEffB2MetadataClassifier
|
| 35 |
except ModuleNotFoundError as exc: # pragma: no cover - local minimal env may omit ML deps.
|
| 36 |
MISSING_DEPENDENCY = exc.name
|
|
|
|
| 63 |
return FakeEncoder(feature_dim), feature_dim
|
| 64 |
|
| 65 |
|
| 66 |
+
class TinyAuxDataset(Dataset):
|
| 67 |
+
labels = [5, 1, 4, 0]
|
| 68 |
+
|
| 69 |
+
def __len__(self) -> int:
|
| 70 |
+
return len(self.labels)
|
| 71 |
+
|
| 72 |
+
def __getitem__(self, idx: int):
|
| 73 |
+
return {
|
| 74 |
+
"clinical": torch.randn(3, 8, 8),
|
| 75 |
+
"dermoscopic": torch.randn(3, 8, 8),
|
| 76 |
+
"metadata": torch.randn(5),
|
| 77 |
+
"label": torch.tensor(self.labels[idx]),
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
|
| 81 |
class FusionSmokeTest(unittest.TestCase):
|
| 82 |
def test_all_image_and_metadata_fusions_forward(self) -> None:
|
| 83 |
modes = [
|
|
|
|
| 226 |
self.assertEqual(tuple(output["inf_aux_logits"].shape), (2, 2))
|
| 227 |
self.assertEqual(tuple(main_logits(output).shape), (2, 11))
|
| 228 |
|
| 229 |
+
def test_epoch_logs_inf_aux_metrics(self) -> None:
|
| 230 |
+
class_names = ["AKIEC", "BCC", "BEN_OTH", "BKL", "DF", "INF", "MAL_OTH", "MEL", "NV", "SCCKA", "VASC"]
|
| 231 |
+
with patch("milk10k_effb2_metadata.models.build_feature_encoder", side_effect=fake_build_feature_encoder):
|
| 232 |
+
model = DualEffB2MetadataClassifier(
|
| 233 |
+
num_classes=11,
|
| 234 |
+
metadata_input_dim=5,
|
| 235 |
+
branch_dim=8,
|
| 236 |
+
metadata_dim=6,
|
| 237 |
+
classifier_hidden_dim=12,
|
| 238 |
+
dropout=0.0,
|
| 239 |
+
imagenet_pretrained=False,
|
| 240 |
+
clinical_backbone_backend="torchvision",
|
| 241 |
+
dermoscopic_backbone_backend="torchvision",
|
| 242 |
+
backbone="efficientnet_b2",
|
| 243 |
+
image_fusion="concat",
|
| 244 |
+
inf_aux=True,
|
| 245 |
+
)
|
| 246 |
+
criterion = InfAuxLossWrapper(
|
| 247 |
+
torch.nn.CrossEntropyLoss(),
|
| 248 |
+
inf_idx=5,
|
| 249 |
+
confuser_indices=[0, 1, 4],
|
| 250 |
+
aux_weight=0.05,
|
| 251 |
+
aux_pos_weight=2.0,
|
| 252 |
+
)
|
| 253 |
+
stats = run_epoch(
|
| 254 |
+
model,
|
| 255 |
+
DataLoader(TinyAuxDataset(), batch_size=4),
|
| 256 |
+
criterion,
|
| 257 |
+
torch.device("cpu"),
|
| 258 |
+
class_names=class_names,
|
| 259 |
+
)
|
| 260 |
+
for key in ("aux_INF_vs_confusers_AUC", "aux_INF_recall", "aux_INF_precision", "aux_INF_AP"):
|
| 261 |
+
self.assertIn(key, stats)
|
| 262 |
+
self.assertTrue(np.isfinite(stats[key]))
|
| 263 |
+
self.assertEqual(stats["aux_INF_vs_confusers_support"], 4.0)
|
| 264 |
+
|
| 265 |
|
| 266 |
class MetadataAugmentationTest(unittest.TestCase):
|
| 267 |
def test_image_transform_does_not_change_metadata(self) -> None:
|
|
|
|
| 334 |
with_aux.backward()
|
| 335 |
self.assertIsNotNone(output["inf_aux_logits"].grad)
|
| 336 |
|
| 337 |
+
def test_inf_aux_disabled_when_weight_zero(self) -> None:
|
| 338 |
+
args = argparse.Namespace(inf_aux=True, inf_aux_weight=0.0)
|
| 339 |
+
self.assertFalse(inf_aux_enabled(args))
|
| 340 |
+
|
| 341 |
+
def test_ldam_can_be_wrapped_with_inf_aux(self) -> None:
|
| 342 |
+
label_to_idx = {"AKIEC": 0, "BCC": 1, "DF": 2, "INF": 3}
|
| 343 |
+
train_df = pd.DataFrame({"label": ["AKIEC", "BCC", "DF", "INF"]})
|
| 344 |
+
args = argparse.Namespace(
|
| 345 |
+
loss="ldam",
|
| 346 |
+
ldam_beta=0.9999,
|
| 347 |
+
ldam_max_margin=0.5,
|
| 348 |
+
ldam_drw_start_epoch=1,
|
| 349 |
+
ldam_alpha_max=10.0,
|
| 350 |
+
inf_aux=True,
|
| 351 |
+
inf_aux_weight=0.05,
|
| 352 |
+
inf_aux_confusers=["BCC", "DF", "AKIEC"],
|
| 353 |
+
inf_aux_pos_weight=2.0,
|
| 354 |
+
)
|
| 355 |
+
loss = build_loss(train_df, label_to_idx, args, torch.device("cpu"))
|
| 356 |
+
loss.set_epoch(2)
|
| 357 |
+
output = {
|
| 358 |
+
"logits": torch.randn(4, 4, requires_grad=True),
|
| 359 |
+
"inf_aux_logits": torch.randn(4, 2, requires_grad=True),
|
| 360 |
+
}
|
| 361 |
+
value = loss(output, torch.tensor([0, 1, 2, 3]))
|
| 362 |
+
self.assertTrue(torch.isfinite(value))
|
| 363 |
+
|
| 364 |
|
| 365 |
if __name__ == "__main__":
|
| 366 |
unittest.main()
|