Upload 32 files
Browse files
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/engine.py
CHANGED
|
@@ -9,7 +9,7 @@ from typing import Any
|
|
| 9 |
import numpy as np
|
| 10 |
import pandas as pd
|
| 11 |
import torch
|
| 12 |
-
from sklearn.metrics import balanced_accuracy_score, precision_recall_fscore_support
|
| 13 |
from torch import nn
|
| 14 |
from torch.amp import GradScaler, autocast
|
| 15 |
from torch.utils.data import DataLoader
|
|
@@ -21,6 +21,10 @@ from milk10k_effb2_metadata.models import DualEffB2MetadataClassifier, set_encod
|
|
| 21 |
from milk10k_effb2_metadata.training_utils import json_safe
|
| 22 |
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
def run_epoch(
|
| 25 |
model: DualEffB2MetadataClassifier,
|
| 26 |
loader: DataLoader,
|
|
@@ -30,6 +34,7 @@ def run_epoch(
|
|
| 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)
|
|
@@ -80,6 +85,33 @@ def run_epoch(
|
|
| 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,
|
|
@@ -92,6 +124,30 @@ def run_epoch(
|
|
| 92 |
return stats
|
| 93 |
|
| 94 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
def save_checkpoint(
|
| 96 |
path: Path,
|
| 97 |
model: DualEffB2MetadataClassifier,
|
|
@@ -162,8 +218,25 @@ def train_phase(
|
|
| 162 |
continue
|
| 163 |
if hasattr(criterion, "set_epoch"):
|
| 164 |
criterion.set_epoch(epoch)
|
| 165 |
-
train_stats = run_epoch(
|
| 166 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
scheduler.step(val_stats["f1_macro"])
|
| 168 |
row = {
|
| 169 |
"phase": phase,
|
|
@@ -186,6 +259,9 @@ def train_phase(
|
|
| 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"]
|
|
|
|
| 9 |
import numpy as np
|
| 10 |
import pandas as pd
|
| 11 |
import torch
|
| 12 |
+
from sklearn.metrics import balanced_accuracy_score, confusion_matrix, precision_recall_fscore_support
|
| 13 |
from torch import nn
|
| 14 |
from torch.amp import GradScaler, autocast
|
| 15 |
from torch.utils.data import DataLoader
|
|
|
|
| 21 |
from milk10k_effb2_metadata.training_utils import json_safe
|
| 22 |
|
| 23 |
|
| 24 |
+
def metric_name(label: str) -> str:
|
| 25 |
+
return "".join(char if char.isalnum() else "_" for char in label).strip("_")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
def run_epoch(
|
| 29 |
model: DualEffB2MetadataClassifier,
|
| 30 |
loader: DataLoader,
|
|
|
|
| 34 |
scaler: GradScaler | None = None,
|
| 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)
|
|
|
|
| 85 |
"f1_macro": float(precision_recall_fscore_support(y_true, y_pred, average="macro", zero_division=0)[2]) if total else 0.0,
|
| 86 |
"top3_accuracy": top3_correct / max(total, 1),
|
| 87 |
}
|
| 88 |
+
if total and class_names:
|
| 89 |
+
labels = list(range(len(class_names)))
|
| 90 |
+
precision, recall, f1, support = precision_recall_fscore_support(
|
| 91 |
+
y_true,
|
| 92 |
+
y_pred,
|
| 93 |
+
labels=labels,
|
| 94 |
+
average=None,
|
| 95 |
+
zero_division=0,
|
| 96 |
+
)
|
| 97 |
+
cm = confusion_matrix(y_true, y_pred, labels=labels)
|
| 98 |
+
for idx, class_name in enumerate(class_names):
|
| 99 |
+
name = metric_name(class_name)
|
| 100 |
+
row_total = int(cm[idx, :].sum())
|
| 101 |
+
stats[f"support_{name}"] = float(support[idx])
|
| 102 |
+
stats[f"precision_{name}"] = float(precision[idx])
|
| 103 |
+
stats[f"recall_{name}"] = float(recall[idx])
|
| 104 |
+
stats[f"f1_{name}"] = float(f1[idx])
|
| 105 |
+
stats[f"correct_{name}"] = float(cm[idx, idx])
|
| 106 |
+
for pred_idx, pred_name in enumerate(class_names):
|
| 107 |
+
if pred_idx == idx:
|
| 108 |
+
continue
|
| 109 |
+
count = int(cm[idx, pred_idx])
|
| 110 |
+
if count <= 0:
|
| 111 |
+
continue
|
| 112 |
+
pred_metric = metric_name(pred_name)
|
| 113 |
+
stats[f"conf_{name}_to_{pred_metric}_count"] = float(count)
|
| 114 |
+
stats[f"conf_{name}_to_{pred_metric}_rate"] = count / row_total if row_total else 0.0
|
| 115 |
if tail_class_indices:
|
| 116 |
recalls = precision_recall_fscore_support(
|
| 117 |
y_true,
|
|
|
|
| 124 |
return stats
|
| 125 |
|
| 126 |
|
| 127 |
+
def format_class_diagnostics(stats: dict[str, float], class_name: str, class_names: list[str]) -> str:
|
| 128 |
+
name = metric_name(class_name)
|
| 129 |
+
support = int(stats.get(f"support_{name}", 0.0))
|
| 130 |
+
correct = int(stats.get(f"correct_{name}", 0.0))
|
| 131 |
+
recall = stats.get(f"recall_{name}", 0.0)
|
| 132 |
+
precision = stats.get(f"precision_{name}", 0.0)
|
| 133 |
+
f1 = stats.get(f"f1_{name}", 0.0)
|
| 134 |
+
wrongs = []
|
| 135 |
+
for pred_name in class_names:
|
| 136 |
+
if pred_name == class_name:
|
| 137 |
+
continue
|
| 138 |
+
pred_metric = metric_name(pred_name)
|
| 139 |
+
count = int(stats.get(f"conf_{name}_to_{pred_metric}_count", 0.0))
|
| 140 |
+
if count > 0:
|
| 141 |
+
rate = stats.get(f"conf_{name}_to_{pred_metric}_rate", 0.0)
|
| 142 |
+
wrongs.append((count, pred_name, rate))
|
| 143 |
+
wrongs.sort(reverse=True)
|
| 144 |
+
wrong_text = ", ".join(f"{pred}={count} ({rate:.0%})" for count, pred, rate in wrongs[:3]) or "none"
|
| 145 |
+
return (
|
| 146 |
+
f"{class_name}: n={support} correct={correct} recall={recall:.3f} "
|
| 147 |
+
f"precision={precision:.3f} f1={f1:.3f} wrong_to=[{wrong_text}]"
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
def save_checkpoint(
|
| 152 |
path: Path,
|
| 153 |
model: DualEffB2MetadataClassifier,
|
|
|
|
| 218 |
continue
|
| 219 |
if hasattr(criterion, "set_epoch"):
|
| 220 |
criterion.set_epoch(epoch)
|
| 221 |
+
train_stats = run_epoch(
|
| 222 |
+
model,
|
| 223 |
+
train_loader,
|
| 224 |
+
criterion,
|
| 225 |
+
device,
|
| 226 |
+
optimizer,
|
| 227 |
+
scaler,
|
| 228 |
+
use_amp,
|
| 229 |
+
tail_class_indices,
|
| 230 |
+
class_names,
|
| 231 |
+
)
|
| 232 |
+
val_stats = run_epoch(
|
| 233 |
+
model,
|
| 234 |
+
val_loader,
|
| 235 |
+
criterion,
|
| 236 |
+
device,
|
| 237 |
+
tail_class_indices=tail_class_indices,
|
| 238 |
+
class_names=class_names,
|
| 239 |
+
)
|
| 240 |
scheduler.step(val_stats["f1_macro"])
|
| 241 |
row = {
|
| 242 |
"phase": phase,
|
|
|
|
| 259 |
f"train_tail_recall={train_stats['tail_recall_macro']:.4f} "
|
| 260 |
f"val_tail_recall={val_stats['tail_recall_macro']:.4f}"
|
| 261 |
)
|
| 262 |
+
for class_name in tail_class_names or []:
|
| 263 |
+
print(f" train {format_class_diagnostics(train_stats, class_name, class_names)}")
|
| 264 |
+
print(f" val {format_class_diagnostics(val_stats, class_name, class_names)}")
|
| 265 |
|
| 266 |
if val_stats["f1_macro"] > best_val_f1:
|
| 267 |
best_val_f1 = val_stats["f1_macro"]
|