Upload 32 files
Browse files- 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__/engine.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/inference.cpython-314.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-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/cli.py +6 -0
- milk10k_effb2_metadata/engine.py +72 -23
- milk10k_effb2_metadata/runner.py +39 -2
- milk10k_effb2_metadata/training_utils.py +1 -0
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__/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-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-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__/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/cli.py
CHANGED
|
@@ -94,6 +94,12 @@ def parse_args() -> argparse.Namespace:
|
|
| 94 |
parser.add_argument("--ldam-max-margin", type=float, default=0.5)
|
| 95 |
parser.add_argument("--ldam-drw-start-epoch", type=int, default=0)
|
| 96 |
parser.add_argument("--ldam-alpha-max", type=float, default=10.0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
parser.add_argument("--k-folds", type=int, default=1)
|
| 98 |
parser.add_argument("--amp", action="store_true")
|
| 99 |
parser.add_argument(
|
|
|
|
| 94 |
parser.add_argument("--ldam-max-margin", type=float, default=0.5)
|
| 95 |
parser.add_argument("--ldam-drw-start-epoch", type=int, default=0)
|
| 96 |
parser.add_argument("--ldam-alpha-max", type=float, default=10.0)
|
| 97 |
+
parser.add_argument(
|
| 98 |
+
"--tail-num-classes",
|
| 99 |
+
type=int,
|
| 100 |
+
default=4,
|
| 101 |
+
help="Number of lowest-support train classes to track for LDAM tail_best.pt.",
|
| 102 |
+
)
|
| 103 |
parser.add_argument("--k-folds", type=int, default=1)
|
| 104 |
parser.add_argument("--amp", action="store_true")
|
| 105 |
parser.add_argument(
|
milk10k_effb2_metadata/engine.py
CHANGED
|
@@ -29,6 +29,7 @@ def run_epoch(
|
|
| 29 |
optimizer: torch.optim.Optimizer | None = None,
|
| 30 |
scaler: GradScaler | None = None,
|
| 31 |
use_amp: bool = False,
|
|
|
|
| 32 |
) -> dict[str, float]:
|
| 33 |
training = optimizer is not None
|
| 34 |
model.train(training)
|
|
@@ -72,13 +73,23 @@ def run_epoch(
|
|
| 72 |
y_pred = np.concatenate(preds_all) if preds_all else np.array([])
|
| 73 |
y_true = np.concatenate(labels_all) if labels_all else np.array([])
|
| 74 |
|
| 75 |
-
|
| 76 |
"loss": total_loss / max(total, 1),
|
| 77 |
"accuracy": correct / max(total, 1),
|
| 78 |
"balanced_accuracy": float(balanced_accuracy_score(y_true, y_pred)) if total else 0.0,
|
| 79 |
"f1_macro": float(precision_recall_fscore_support(y_true, y_pred, average="macro", zero_division=0)[2]) if total else 0.0,
|
| 80 |
"top3_accuracy": top3_correct / max(total, 1),
|
| 81 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
|
| 84 |
def save_checkpoint(
|
|
@@ -92,21 +103,22 @@ def save_checkpoint(
|
|
| 92 |
label_to_idx: dict[str, int],
|
| 93 |
metadata_spec: dict[str, Any],
|
| 94 |
args: argparse.Namespace,
|
|
|
|
| 95 |
) -> None:
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
)
|
| 110 |
|
| 111 |
|
| 112 |
def train_phase(
|
|
@@ -126,9 +138,13 @@ def train_phase(
|
|
| 126 |
history: list[dict[str, Any]],
|
| 127 |
best_val_f1: float,
|
| 128 |
skip_until_epoch: int = 1,
|
| 129 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
if num_epochs <= 0:
|
| 131 |
-
return start_epoch, best_val_f1
|
| 132 |
|
| 133 |
encoders_trainable = phase == "finetune"
|
| 134 |
set_encoder_trainable(model, encoders_trainable)
|
|
@@ -146,8 +162,8 @@ def train_phase(
|
|
| 146 |
continue
|
| 147 |
if hasattr(criterion, "set_epoch"):
|
| 148 |
criterion.set_epoch(epoch)
|
| 149 |
-
train_stats = run_epoch(model, train_loader, criterion, device, optimizer, scaler, use_amp)
|
| 150 |
-
val_stats = run_epoch(model, val_loader, criterion, device)
|
| 151 |
scheduler.step(val_stats["f1_macro"])
|
| 152 |
row = {
|
| 153 |
"phase": phase,
|
|
@@ -164,6 +180,12 @@ def train_phase(
|
|
| 164 |
f"val_acc={val_stats['accuracy']:.4f} val_bal_acc={val_stats['balanced_accuracy']:.4f} "
|
| 165 |
f"val_f1={val_stats['f1_macro']:.4f} val_top3={val_stats['top3_accuracy']:.4f}"
|
| 166 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
|
| 168 |
if val_stats["f1_macro"] > best_val_f1:
|
| 169 |
best_val_f1 = val_stats["f1_macro"]
|
|
@@ -186,8 +208,35 @@ def train_phase(
|
|
| 186 |
)
|
| 187 |
else:
|
| 188 |
patience_count += 1
|
| 189 |
-
if patience_count >= args.patience:
|
| 190 |
-
print(f"Early stopping {phase} at epoch {epoch}")
|
| 191 |
-
break
|
| 192 |
|
| 193 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
optimizer: torch.optim.Optimizer | None = None,
|
| 30 |
scaler: GradScaler | None = None,
|
| 31 |
use_amp: bool = False,
|
| 32 |
+
tail_class_indices: list[int] | None = None,
|
| 33 |
) -> dict[str, float]:
|
| 34 |
training = optimizer is not None
|
| 35 |
model.train(training)
|
|
|
|
| 73 |
y_pred = np.concatenate(preds_all) if preds_all else np.array([])
|
| 74 |
y_true = np.concatenate(labels_all) if labels_all else np.array([])
|
| 75 |
|
| 76 |
+
stats = {
|
| 77 |
"loss": total_loss / max(total, 1),
|
| 78 |
"accuracy": correct / max(total, 1),
|
| 79 |
"balanced_accuracy": float(balanced_accuracy_score(y_true, y_pred)) if total else 0.0,
|
| 80 |
"f1_macro": float(precision_recall_fscore_support(y_true, y_pred, average="macro", zero_division=0)[2]) if total else 0.0,
|
| 81 |
"top3_accuracy": top3_correct / max(total, 1),
|
| 82 |
}
|
| 83 |
+
if tail_class_indices:
|
| 84 |
+
recalls = precision_recall_fscore_support(
|
| 85 |
+
y_true,
|
| 86 |
+
y_pred,
|
| 87 |
+
labels=tail_class_indices,
|
| 88 |
+
average=None,
|
| 89 |
+
zero_division=0,
|
| 90 |
+
)[1]
|
| 91 |
+
stats["tail_recall_macro"] = float(np.mean(recalls)) if len(recalls) else 0.0
|
| 92 |
+
return stats
|
| 93 |
|
| 94 |
|
| 95 |
def save_checkpoint(
|
|
|
|
| 103 |
label_to_idx: dict[str, int],
|
| 104 |
metadata_spec: dict[str, Any],
|
| 105 |
args: argparse.Namespace,
|
| 106 |
+
extra: dict[str, Any] | None = None,
|
| 107 |
) -> None:
|
| 108 |
+
payload = {
|
| 109 |
+
"epoch": epoch,
|
| 110 |
+
"phase": phase,
|
| 111 |
+
"model_state": model.state_dict(),
|
| 112 |
+
"optimizer_state": optimizer.state_dict(),
|
| 113 |
+
"best_val_f1_macro": best_val_f1,
|
| 114 |
+
"class_names": class_names,
|
| 115 |
+
"label_to_idx": label_to_idx,
|
| 116 |
+
"metadata_spec": metadata_spec,
|
| 117 |
+
"args": json_safe(vars(args)),
|
| 118 |
+
}
|
| 119 |
+
if extra:
|
| 120 |
+
payload.update(json_safe(extra))
|
| 121 |
+
torch.save(payload, path)
|
| 122 |
|
| 123 |
|
| 124 |
def train_phase(
|
|
|
|
| 138 |
history: list[dict[str, Any]],
|
| 139 |
best_val_f1: float,
|
| 140 |
skip_until_epoch: int = 1,
|
| 141 |
+
tail_class_indices: list[int] | None = None,
|
| 142 |
+
tail_class_names: list[str] | None = None,
|
| 143 |
+
train_class_counts: dict[str, int] | None = None,
|
| 144 |
+
best_val_tail_recall: float = float("-inf"),
|
| 145 |
+
) -> tuple[int, float, float]:
|
| 146 |
if num_epochs <= 0:
|
| 147 |
+
return start_epoch, best_val_f1, best_val_tail_recall
|
| 148 |
|
| 149 |
encoders_trainable = phase == "finetune"
|
| 150 |
set_encoder_trainable(model, encoders_trainable)
|
|
|
|
| 162 |
continue
|
| 163 |
if hasattr(criterion, "set_epoch"):
|
| 164 |
criterion.set_epoch(epoch)
|
| 165 |
+
train_stats = run_epoch(model, train_loader, criterion, device, optimizer, scaler, use_amp, tail_class_indices)
|
| 166 |
+
val_stats = run_epoch(model, val_loader, criterion, device, tail_class_indices=tail_class_indices)
|
| 167 |
scheduler.step(val_stats["f1_macro"])
|
| 168 |
row = {
|
| 169 |
"phase": phase,
|
|
|
|
| 180 |
f"val_acc={val_stats['accuracy']:.4f} val_bal_acc={val_stats['balanced_accuracy']:.4f} "
|
| 181 |
f"val_f1={val_stats['f1_macro']:.4f} val_top3={val_stats['top3_accuracy']:.4f}"
|
| 182 |
)
|
| 183 |
+
if tail_class_indices:
|
| 184 |
+
print(
|
| 185 |
+
f"LDAM tail: classes={tail_class_names} "
|
| 186 |
+
f"train_tail_recall={train_stats['tail_recall_macro']:.4f} "
|
| 187 |
+
f"val_tail_recall={val_stats['tail_recall_macro']:.4f}"
|
| 188 |
+
)
|
| 189 |
|
| 190 |
if val_stats["f1_macro"] > best_val_f1:
|
| 191 |
best_val_f1 = val_stats["f1_macro"]
|
|
|
|
| 208 |
)
|
| 209 |
else:
|
| 210 |
patience_count += 1
|
|
|
|
|
|
|
|
|
|
| 211 |
|
| 212 |
+
if tail_class_indices and val_stats["tail_recall_macro"] > best_val_tail_recall:
|
| 213 |
+
best_val_tail_recall = val_stats["tail_recall_macro"]
|
| 214 |
+
save_checkpoint(
|
| 215 |
+
output_dir / "tail_best.pt",
|
| 216 |
+
model,
|
| 217 |
+
optimizer,
|
| 218 |
+
epoch,
|
| 219 |
+
phase,
|
| 220 |
+
best_val_f1,
|
| 221 |
+
class_names,
|
| 222 |
+
label_to_idx,
|
| 223 |
+
metadata_spec,
|
| 224 |
+
args,
|
| 225 |
+
{
|
| 226 |
+
"best_val_tail_recall_macro": best_val_tail_recall,
|
| 227 |
+
"tail_class_names": tail_class_names or [],
|
| 228 |
+
"tail_class_indices": tail_class_indices,
|
| 229 |
+
"train_class_counts": train_class_counts or {},
|
| 230 |
+
"selection_metric": "val_tail_recall_macro",
|
| 231 |
+
},
|
| 232 |
+
)
|
| 233 |
+
print(
|
| 234 |
+
f"Saved tail checkpoint: phase={phase} epoch={epoch:03d} "
|
| 235 |
+
f"best_val_tail_recall_macro={best_val_tail_recall:.4f} path={output_dir / 'tail_best.pt'}"
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
if patience_count >= args.patience:
|
| 239 |
+
print(f"Early stopping {phase} at epoch {epoch}")
|
| 240 |
+
break
|
| 241 |
+
|
| 242 |
+
return epoch + 1, best_val_f1, best_val_tail_recall
|
milk10k_effb2_metadata/runner.py
CHANGED
|
@@ -24,6 +24,27 @@ from milk10k_effb2_metadata.model_setup import build_model, load_resume_checkpoi
|
|
| 24 |
from milk10k_effb2_metadata.training_utils import json_safe, save_kfold_summary, save_run_config
|
| 25 |
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
def run_training_split(
|
| 28 |
df: pd.DataFrame,
|
| 29 |
train_df: pd.DataFrame,
|
|
@@ -68,6 +89,7 @@ def run_training_split(
|
|
| 68 |
resume_epoch, resume_best_val_f1, resume_phase = load_resume_checkpoint(args.resume_checkpoint, model, device)
|
| 69 |
train_loader, val_loader = make_loaders(train_df, val_df, label_to_idx, metadata_spec, args)
|
| 70 |
criterion = build_loss(train_df, label_to_idx, args, device)
|
|
|
|
| 71 |
|
| 72 |
print(f"Output dir: {output_dir}")
|
| 73 |
print(f"Device: {device}")
|
|
@@ -83,17 +105,25 @@ def run_training_split(
|
|
| 83 |
print(f"Loss: {args.loss}, class_weight={args.class_weight}, weighted_sampler={args.weighted_sampler}")
|
| 84 |
if args.loss == "ldam" and args.class_weight:
|
| 85 |
print("Note: --class-weight is ignored for --loss ldam because LDAM+DRW uses effective-number alpha.")
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
history: list[dict[str, Any]] = []
|
| 88 |
history_path = output_dir / "history.csv"
|
| 89 |
if args.resume_checkpoint is not None and history_path.exists():
|
| 90 |
history = pd.read_csv(history_path).to_dict("records")
|
| 91 |
best_start = resume_best_val_f1 if args.resume_checkpoint is not None else float("-inf")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
skip_freeze_until = resume_epoch if resume_phase == "freeze" else 1
|
| 93 |
if resume_phase == "finetune":
|
| 94 |
skip_freeze_until = args.freeze_epochs + 1
|
| 95 |
skip_finetune_until = resume_epoch if resume_phase == "finetune" else 1
|
| 96 |
-
epoch, best_val_f1 = train_phase(
|
| 97 |
"freeze",
|
| 98 |
args.freeze_epochs,
|
| 99 |
1,
|
|
@@ -110,8 +140,10 @@ def run_training_split(
|
|
| 110 |
history,
|
| 111 |
best_start,
|
| 112 |
skip_freeze_until,
|
|
|
|
|
|
|
| 113 |
)
|
| 114 |
-
epoch, best_val_f1 = train_phase(
|
| 115 |
"finetune",
|
| 116 |
args.finetune_epochs,
|
| 117 |
epoch,
|
|
@@ -128,6 +160,8 @@ def run_training_split(
|
|
| 128 |
history,
|
| 129 |
best_val_f1,
|
| 130 |
skip_finetune_until,
|
|
|
|
|
|
|
| 131 |
)
|
| 132 |
|
| 133 |
best_path = output_dir / "best.pt"
|
|
@@ -137,6 +171,9 @@ def run_training_split(
|
|
| 137 |
y_true, y_prob = predict(model, val_loader, device)
|
| 138 |
metrics, per_class_df, cm = compute_metrics(y_true, y_prob, class_names)
|
| 139 |
metrics = {"best_val_f1_macro": float(best_val_f1), **metrics}
|
|
|
|
|
|
|
|
|
|
| 140 |
with open(output_dir / "metrics.json", "w", encoding="utf-8") as f:
|
| 141 |
json.dump(json_safe(metrics), f, indent=2)
|
| 142 |
pd.DataFrame(cm, index=class_names, columns=class_names).to_csv(output_dir / "confusion_matrix.csv")
|
|
|
|
| 24 |
from milk10k_effb2_metadata.training_utils import json_safe, save_kfold_summary, save_run_config
|
| 25 |
|
| 26 |
|
| 27 |
+
def build_tail_tracking_config(
|
| 28 |
+
train_df: pd.DataFrame,
|
| 29 |
+
class_names: list[str],
|
| 30 |
+
label_to_idx: dict[str, int],
|
| 31 |
+
args: argparse.Namespace,
|
| 32 |
+
) -> dict[str, Any] | None:
|
| 33 |
+
if args.loss != "ldam" or args.tail_num_classes <= 0:
|
| 34 |
+
return None
|
| 35 |
+
|
| 36 |
+
counts_series = train_df["label"].value_counts().reindex(class_names, fill_value=0)
|
| 37 |
+
train_class_counts = {label: int(counts_series[label]) for label in class_names}
|
| 38 |
+
tail_class_names = sorted(class_names, key=lambda label: (train_class_counts[label], label))[
|
| 39 |
+
: min(args.tail_num_classes, len(class_names))
|
| 40 |
+
]
|
| 41 |
+
return {
|
| 42 |
+
"tail_class_names": tail_class_names,
|
| 43 |
+
"tail_class_indices": [label_to_idx[label] for label in tail_class_names],
|
| 44 |
+
"train_class_counts": train_class_counts,
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
def run_training_split(
|
| 49 |
df: pd.DataFrame,
|
| 50 |
train_df: pd.DataFrame,
|
|
|
|
| 89 |
resume_epoch, resume_best_val_f1, resume_phase = load_resume_checkpoint(args.resume_checkpoint, model, device)
|
| 90 |
train_loader, val_loader = make_loaders(train_df, val_df, label_to_idx, metadata_spec, args)
|
| 91 |
criterion = build_loss(train_df, label_to_idx, args, device)
|
| 92 |
+
tail_config = build_tail_tracking_config(train_df, class_names, label_to_idx, args)
|
| 93 |
|
| 94 |
print(f"Output dir: {output_dir}")
|
| 95 |
print(f"Device: {device}")
|
|
|
|
| 105 |
print(f"Loss: {args.loss}, class_weight={args.class_weight}, weighted_sampler={args.weighted_sampler}")
|
| 106 |
if args.loss == "ldam" and args.class_weight:
|
| 107 |
print("Note: --class-weight is ignored for --loss ldam because LDAM+DRW uses effective-number alpha.")
|
| 108 |
+
if tail_config is not None:
|
| 109 |
+
tail_counts = {label: tail_config["train_class_counts"][label] for label in tail_config["tail_class_names"]}
|
| 110 |
+
print(f"LDAM tail tracking: tail_num_classes={args.tail_num_classes}, tail_counts={tail_counts}")
|
| 111 |
|
| 112 |
history: list[dict[str, Any]] = []
|
| 113 |
history_path = output_dir / "history.csv"
|
| 114 |
if args.resume_checkpoint is not None and history_path.exists():
|
| 115 |
history = pd.read_csv(history_path).to_dict("records")
|
| 116 |
best_start = resume_best_val_f1 if args.resume_checkpoint is not None else float("-inf")
|
| 117 |
+
best_tail_start = float("-inf")
|
| 118 |
+
tail_best_path = output_dir / "tail_best.pt"
|
| 119 |
+
if args.resume_checkpoint is not None and tail_best_path.exists():
|
| 120 |
+
tail_checkpoint = torch.load(tail_best_path, map_location=device, weights_only=False)
|
| 121 |
+
best_tail_start = float(tail_checkpoint.get("best_val_tail_recall_macro", float("-inf")))
|
| 122 |
skip_freeze_until = resume_epoch if resume_phase == "freeze" else 1
|
| 123 |
if resume_phase == "finetune":
|
| 124 |
skip_freeze_until = args.freeze_epochs + 1
|
| 125 |
skip_finetune_until = resume_epoch if resume_phase == "finetune" else 1
|
| 126 |
+
epoch, best_val_f1, best_val_tail_recall = train_phase(
|
| 127 |
"freeze",
|
| 128 |
args.freeze_epochs,
|
| 129 |
1,
|
|
|
|
| 140 |
history,
|
| 141 |
best_start,
|
| 142 |
skip_freeze_until,
|
| 143 |
+
**(tail_config or {}),
|
| 144 |
+
best_val_tail_recall=best_tail_start,
|
| 145 |
)
|
| 146 |
+
epoch, best_val_f1, best_val_tail_recall = train_phase(
|
| 147 |
"finetune",
|
| 148 |
args.finetune_epochs,
|
| 149 |
epoch,
|
|
|
|
| 160 |
history,
|
| 161 |
best_val_f1,
|
| 162 |
skip_finetune_until,
|
| 163 |
+
**(tail_config or {}),
|
| 164 |
+
best_val_tail_recall=best_val_tail_recall,
|
| 165 |
)
|
| 166 |
|
| 167 |
best_path = output_dir / "best.pt"
|
|
|
|
| 171 |
y_true, y_prob = predict(model, val_loader, device)
|
| 172 |
metrics, per_class_df, cm = compute_metrics(y_true, y_prob, class_names)
|
| 173 |
metrics = {"best_val_f1_macro": float(best_val_f1), **metrics}
|
| 174 |
+
if tail_config is not None:
|
| 175 |
+
metrics["best_val_tail_recall_macro"] = float(best_val_tail_recall)
|
| 176 |
+
metrics["tail_class_names"] = tail_config["tail_class_names"]
|
| 177 |
with open(output_dir / "metrics.json", "w", encoding="utf-8") as f:
|
| 178 |
json.dump(json_safe(metrics), f, indent=2)
|
| 179 |
pd.DataFrame(cm, index=class_names, columns=class_names).to_csv(output_dir / "confusion_matrix.csv")
|
milk10k_effb2_metadata/training_utils.py
CHANGED
|
@@ -46,6 +46,7 @@ def save_kfold_summary(fold_metrics: list[dict[str, Any]], output_dir: Path) ->
|
|
| 46 |
|
| 47 |
summary_keys = [
|
| 48 |
"best_val_f1_macro",
|
|
|
|
| 49 |
"accuracy",
|
| 50 |
"balanced_accuracy",
|
| 51 |
"f1_macro",
|
|
|
|
| 46 |
|
| 47 |
summary_keys = [
|
| 48 |
"best_val_f1_macro",
|
| 49 |
+
"best_val_tail_recall_macro",
|
| 50 |
"accuracy",
|
| 51 |
"balanced_accuracy",
|
| 52 |
"f1_macro",
|