Upload 35 files
Browse files- milk10k_effb2_metadata/__pycache__/reporting.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/runner.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/training_utils.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/reporting.py +498 -0
- milk10k_effb2_metadata/runner.py +16 -0
- milk10k_effb2_metadata/training_utils.py +13 -0
milk10k_effb2_metadata/__pycache__/reporting.cpython-314.pyc
ADDED
|
Binary file (32.4 kB). View file
|
|
|
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__/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/reporting.py
ADDED
|
@@ -0,0 +1,498 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run reporting helpers for MILK10k training outputs."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
import platform
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
from datetime import datetime, timezone
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Any
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
import pandas as pd
|
| 16 |
+
|
| 17 |
+
from milk10k_effb2_metadata.training_utils import json_safe
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
WATCHED_CONFUSIONS = {
|
| 21 |
+
"INF": ["BEN_OTH", "NV", "BCC"],
|
| 22 |
+
"BCC": ["AKIEC", "BKL", "SCCKA"],
|
| 23 |
+
"SCCKA": ["AKIEC", "BKL"],
|
| 24 |
+
"AKIEC": ["SCCKA"],
|
| 25 |
+
"BKL": ["SCCKA"],
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def collect_environment_info() -> dict[str, Any]:
|
| 30 |
+
payload: dict[str, Any] = {
|
| 31 |
+
"timestamp_utc": datetime.now(timezone.utc).isoformat(),
|
| 32 |
+
"cwd": str(Path.cwd()),
|
| 33 |
+
"command": sys.argv,
|
| 34 |
+
"python": sys.version.replace("\n", " "),
|
| 35 |
+
"platform": platform.platform(),
|
| 36 |
+
"executable": sys.executable,
|
| 37 |
+
}
|
| 38 |
+
try:
|
| 39 |
+
import torch
|
| 40 |
+
|
| 41 |
+
payload["torch"] = {
|
| 42 |
+
"version": torch.__version__,
|
| 43 |
+
"cuda_available": torch.cuda.is_available(),
|
| 44 |
+
"cuda_device_count": torch.cuda.device_count(),
|
| 45 |
+
"cuda_device_name": torch.cuda.get_device_name(0) if torch.cuda.is_available() else None,
|
| 46 |
+
}
|
| 47 |
+
except Exception as exc: # pragma: no cover - defensive only.
|
| 48 |
+
payload["torch"] = {"error": repr(exc)}
|
| 49 |
+
|
| 50 |
+
payload["git"] = git_info(Path.cwd())
|
| 51 |
+
return payload
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def git_info(cwd: Path) -> dict[str, Any]:
|
| 55 |
+
def run_git(args: list[str]) -> str | None:
|
| 56 |
+
try:
|
| 57 |
+
result = subprocess.run(
|
| 58 |
+
["git", *args],
|
| 59 |
+
cwd=cwd,
|
| 60 |
+
check=False,
|
| 61 |
+
capture_output=True,
|
| 62 |
+
text=True,
|
| 63 |
+
timeout=5,
|
| 64 |
+
)
|
| 65 |
+
except Exception:
|
| 66 |
+
return None
|
| 67 |
+
if result.returncode != 0:
|
| 68 |
+
return None
|
| 69 |
+
return result.stdout.strip()
|
| 70 |
+
|
| 71 |
+
commit = run_git(["rev-parse", "HEAD"])
|
| 72 |
+
if commit is None:
|
| 73 |
+
return {"available": False}
|
| 74 |
+
status = run_git(["status", "--short"]) or ""
|
| 75 |
+
branch = run_git(["rev-parse", "--abbrev-ref", "HEAD"])
|
| 76 |
+
return {
|
| 77 |
+
"available": True,
|
| 78 |
+
"commit": commit,
|
| 79 |
+
"branch": branch,
|
| 80 |
+
"dirty": bool(status),
|
| 81 |
+
"status_short": status.splitlines(),
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def class_distribution(df: pd.DataFrame, class_names: list[str]) -> dict[str, Any]:
|
| 86 |
+
counts = df["label"].value_counts().reindex(class_names, fill_value=0).astype(int).to_dict()
|
| 87 |
+
is_augmented = synthetic_mask(df)
|
| 88 |
+
ignore_metadata = (
|
| 89 |
+
df["ignore_metadata"].fillna(False).astype(bool).to_numpy()
|
| 90 |
+
if "ignore_metadata" in df.columns
|
| 91 |
+
else np.zeros(len(df), dtype=bool)
|
| 92 |
+
)
|
| 93 |
+
augmented_counts = (
|
| 94 |
+
df.loc[is_augmented, "label"].value_counts().reindex(class_names, fill_value=0).astype(int).to_dict()
|
| 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,
|
| 101 |
+
"real_rows": int((~is_augmented).sum()),
|
| 102 |
+
"synthetic_rows": int(is_augmented.sum()),
|
| 103 |
+
"synthetic_class_counts": augmented_counts,
|
| 104 |
+
"ignore_metadata_rows": int(ignore_metadata.sum()),
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def synthetic_mask(df: pd.DataFrame) -> np.ndarray:
|
| 109 |
+
mask = np.zeros(len(df), dtype=bool)
|
| 110 |
+
if "is_augmented" in df.columns:
|
| 111 |
+
mask |= df["is_augmented"].fillna(False).astype(bool).to_numpy()
|
| 112 |
+
if "lesion_id" in df.columns:
|
| 113 |
+
mask |= df["lesion_id"].astype(str).str.contains("__sdpair_", regex=False).to_numpy()
|
| 114 |
+
return mask
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def build_data_summary(
|
| 118 |
+
full_df: pd.DataFrame,
|
| 119 |
+
train_df: pd.DataFrame,
|
| 120 |
+
val_df: pd.DataFrame,
|
| 121 |
+
class_names: list[str],
|
| 122 |
+
) -> dict[str, Any]:
|
| 123 |
+
return {
|
| 124 |
+
"full": class_distribution(full_df, class_names),
|
| 125 |
+
"train": class_distribution(train_df, class_names),
|
| 126 |
+
"val": class_distribution(val_df, class_names),
|
| 127 |
+
"synthetic_train_only": bool(synthetic_mask(train_df).sum() and not synthetic_mask(val_df).sum()),
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def build_prediction_summary(y_prob: np.ndarray, class_names: list[str], low_confidence_threshold: float = 0.5) -> dict[str, Any]:
|
| 132 |
+
if y_prob.size == 0:
|
| 133 |
+
return {
|
| 134 |
+
"rows": 0,
|
| 135 |
+
"predicted_class_counts": {name: 0 for name in class_names},
|
| 136 |
+
"mean_probability": {name: 0.0 for name in class_names},
|
| 137 |
+
}
|
| 138 |
+
y_pred = y_prob.argmax(axis=1)
|
| 139 |
+
counts = np.bincount(y_pred, minlength=len(class_names))
|
| 140 |
+
sorted_prob = np.sort(y_prob, axis=1)
|
| 141 |
+
confidence = sorted_prob[:, -1]
|
| 142 |
+
second = sorted_prob[:, -2] if y_prob.shape[1] > 1 else np.zeros_like(confidence)
|
| 143 |
+
entropy = -np.sum(y_prob * np.log(np.clip(y_prob, 1e-12, 1.0)), axis=1)
|
| 144 |
+
return {
|
| 145 |
+
"rows": int(y_prob.shape[0]),
|
| 146 |
+
"predicted_class_counts": {name: int(counts[idx]) for idx, name in enumerate(class_names)},
|
| 147 |
+
"mean_probability": {name: float(y_prob[:, idx].mean()) for idx, name in enumerate(class_names)},
|
| 148 |
+
"median_probability": {name: float(np.median(y_prob[:, idx])) for idx, name in enumerate(class_names)},
|
| 149 |
+
"mean_confidence": float(confidence.mean()),
|
| 150 |
+
"median_confidence": float(np.median(confidence)),
|
| 151 |
+
"mean_top1_top2_gap": float((confidence - second).mean()),
|
| 152 |
+
"median_top1_top2_gap": float(np.median(confidence - second)),
|
| 153 |
+
"mean_entropy": float(entropy.mean()),
|
| 154 |
+
"median_entropy": float(np.median(entropy)),
|
| 155 |
+
"low_confidence_threshold": float(low_confidence_threshold),
|
| 156 |
+
"low_confidence_rows": int((confidence < low_confidence_threshold).sum()),
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def build_confusion_analysis(cm: np.ndarray, class_names: list[str], top_k: int = 20) -> dict[str, Any]:
|
| 161 |
+
false_negatives: dict[str, list[dict[str, Any]]] = {}
|
| 162 |
+
false_positives: dict[str, list[dict[str, Any]]] = {}
|
| 163 |
+
pairs = []
|
| 164 |
+
watched = []
|
| 165 |
+
|
| 166 |
+
for true_idx, true_name in enumerate(class_names):
|
| 167 |
+
row_total = int(cm[true_idx, :].sum())
|
| 168 |
+
entries = []
|
| 169 |
+
for pred_idx, pred_name in enumerate(class_names):
|
| 170 |
+
if pred_idx == true_idx:
|
| 171 |
+
continue
|
| 172 |
+
count = int(cm[true_idx, pred_idx])
|
| 173 |
+
if count <= 0:
|
| 174 |
+
continue
|
| 175 |
+
entry = {
|
| 176 |
+
"true": true_name,
|
| 177 |
+
"predicted": pred_name,
|
| 178 |
+
"count": count,
|
| 179 |
+
"rate_of_true": count / row_total if row_total else 0.0,
|
| 180 |
+
}
|
| 181 |
+
entries.append(entry)
|
| 182 |
+
pairs.append(entry)
|
| 183 |
+
if pred_name in WATCHED_CONFUSIONS.get(true_name, []):
|
| 184 |
+
watched.append(entry)
|
| 185 |
+
false_negatives[true_name] = sorted(entries, key=lambda item: item["count"], reverse=True)
|
| 186 |
+
|
| 187 |
+
for pred_idx, pred_name in enumerate(class_names):
|
| 188 |
+
col_total = int(cm[:, pred_idx].sum())
|
| 189 |
+
entries = []
|
| 190 |
+
for true_idx, true_name in enumerate(class_names):
|
| 191 |
+
if pred_idx == true_idx:
|
| 192 |
+
continue
|
| 193 |
+
count = int(cm[true_idx, pred_idx])
|
| 194 |
+
if count <= 0:
|
| 195 |
+
continue
|
| 196 |
+
entries.append(
|
| 197 |
+
{
|
| 198 |
+
"predicted": pred_name,
|
| 199 |
+
"true": true_name,
|
| 200 |
+
"count": count,
|
| 201 |
+
"rate_of_predicted": count / col_total if col_total else 0.0,
|
| 202 |
+
}
|
| 203 |
+
)
|
| 204 |
+
false_positives[pred_name] = sorted(entries, key=lambda item: item["count"], reverse=True)
|
| 205 |
+
|
| 206 |
+
pairs = sorted(pairs, key=lambda item: item["count"], reverse=True)
|
| 207 |
+
watched = sorted(watched, key=lambda item: item["count"], reverse=True)
|
| 208 |
+
return {
|
| 209 |
+
"false_negatives_by_true_class": false_negatives,
|
| 210 |
+
"false_positives_by_predicted_class": false_positives,
|
| 211 |
+
"top_confusion_pairs": pairs[:top_k],
|
| 212 |
+
"watched_confusion_patterns": watched,
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def build_run_warnings(
|
| 217 |
+
metrics: dict[str, Any],
|
| 218 |
+
per_class_df: pd.DataFrame,
|
| 219 |
+
cm: np.ndarray,
|
| 220 |
+
prediction_summary: dict[str, Any],
|
| 221 |
+
) -> list[dict[str, Any]]:
|
| 222 |
+
del metrics
|
| 223 |
+
class_names = per_class_df["class"].tolist()
|
| 224 |
+
warnings: list[dict[str, Any]] = []
|
| 225 |
+
pred_counts = prediction_summary.get("predicted_class_counts", {})
|
| 226 |
+
total_pred = max(int(prediction_summary.get("rows", 0)), 1)
|
| 227 |
+
|
| 228 |
+
for class_name in ("INF", "BEN_OTH"):
|
| 229 |
+
if class_name in pred_counts and int(pred_counts[class_name]) == 0:
|
| 230 |
+
warnings.append(warning("tail_predicted_zero", "high", f"{class_name} has zero predicted rows.", class_name))
|
| 231 |
+
|
| 232 |
+
mal_count = int(pred_counts.get("MAL_OTH", 0))
|
| 233 |
+
if mal_count > max(2, math.ceil(total_pred * 0.01)):
|
| 234 |
+
warnings.append(warning("mal_oth_many_predictions", "medium", f"MAL_OTH predicted {mal_count} times.", "MAL_OTH"))
|
| 235 |
+
|
| 236 |
+
if "BCC" in class_names:
|
| 237 |
+
bcc_idx = class_names.index("BCC")
|
| 238 |
+
bcc_support = int(cm[bcc_idx, :].sum())
|
| 239 |
+
bcc_pred = int(cm[:, bcc_idx].sum())
|
| 240 |
+
if bcc_support and bcc_pred < max(1, int(bcc_support * 0.65)):
|
| 241 |
+
warnings.append(
|
| 242 |
+
warning("bcc_predicted_low", "high", f"BCC predicted {bcc_pred} times for {bcc_support} validation BCC rows.", "BCC")
|
| 243 |
+
)
|
| 244 |
+
drift_targets = [name for name in ("AKIEC", "BKL", "SCCKA") if name in class_names]
|
| 245 |
+
drift_count = sum(int(cm[bcc_idx, class_names.index(name)]) for name in drift_targets)
|
| 246 |
+
if bcc_support and drift_count >= max(3, int(bcc_support * 0.08)):
|
| 247 |
+
warnings.append(
|
| 248 |
+
warning("bcc_boundary_drift", "high", f"BCC -> AKIEC/BKL/SCCKA count is {drift_count}.", "BCC")
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
for row in per_class_df.to_dict("records"):
|
| 252 |
+
class_name = str(row["class"])
|
| 253 |
+
support = int(row.get("support", 0))
|
| 254 |
+
precision = float(row.get("precision", 0.0))
|
| 255 |
+
recall = float(row.get("recall_sensitivity", 0.0))
|
| 256 |
+
if support <= 5:
|
| 257 |
+
warnings.append(
|
| 258 |
+
warning("tiny_validation_support", "medium", f"{class_name} validation support is only {support}.", class_name)
|
| 259 |
+
)
|
| 260 |
+
if class_name in {"BEN_OTH", "DF", "INF", "MAL_OTH", "VASC"} and recall >= 0.2 and precision < 0.2:
|
| 261 |
+
warnings.append(
|
| 262 |
+
warning(
|
| 263 |
+
"tail_precision_low",
|
| 264 |
+
"high",
|
| 265 |
+
f"{class_name} recall={recall:.3f} but precision={precision:.3f}.",
|
| 266 |
+
class_name,
|
| 267 |
+
)
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
mean_conf = float(prediction_summary.get("mean_confidence", 0.0))
|
| 271 |
+
mean_entropy = float(prediction_summary.get("mean_entropy", 0.0))
|
| 272 |
+
if mean_conf > 0.9 and mean_entropy < 0.35:
|
| 273 |
+
warnings.append(
|
| 274 |
+
warning("high_confidence_low_entropy", "medium", f"mean_confidence={mean_conf:.3f}, mean_entropy={mean_entropy:.3f}.")
|
| 275 |
+
)
|
| 276 |
+
return warnings
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def warning(code: str, severity: str, message: str, class_name: str | None = None) -> dict[str, Any]:
|
| 280 |
+
payload = {"code": code, "severity": severity, "message": message}
|
| 281 |
+
if class_name is not None:
|
| 282 |
+
payload["class"] = class_name
|
| 283 |
+
return payload
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def save_data_summary(output_dir: Path, data_summary: dict[str, Any]) -> None:
|
| 287 |
+
with open(output_dir / "data_summary.json", "w", encoding="utf-8") as f:
|
| 288 |
+
json.dump(json_safe(data_summary), f, indent=2)
|
| 289 |
+
(output_dir / "split_summary.md").write_text(render_split_summary(data_summary), encoding="utf-8")
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def save_run_diagnostics(
|
| 293 |
+
output_dir: Path,
|
| 294 |
+
args: Any,
|
| 295 |
+
data_summary: dict[str, Any],
|
| 296 |
+
metrics: dict[str, Any],
|
| 297 |
+
per_class_df: pd.DataFrame,
|
| 298 |
+
cm: np.ndarray,
|
| 299 |
+
y_prob: np.ndarray,
|
| 300 |
+
class_names: list[str],
|
| 301 |
+
fold: int | None = None,
|
| 302 |
+
) -> dict[str, Any]:
|
| 303 |
+
prediction_summary = build_prediction_summary(y_prob, class_names)
|
| 304 |
+
confusion_analysis = build_confusion_analysis(cm, class_names)
|
| 305 |
+
warnings = build_run_warnings(metrics, per_class_df, cm, prediction_summary)
|
| 306 |
+
diagnostics = {
|
| 307 |
+
"fold": fold,
|
| 308 |
+
"warnings": warnings,
|
| 309 |
+
"prediction_summary": prediction_summary,
|
| 310 |
+
"confusion_analysis": confusion_analysis,
|
| 311 |
+
}
|
| 312 |
+
with open(output_dir / "prediction_summary.json", "w", encoding="utf-8") as f:
|
| 313 |
+
json.dump(json_safe(prediction_summary), f, indent=2)
|
| 314 |
+
with open(output_dir / "confusion_analysis.json", "w", encoding="utf-8") as f:
|
| 315 |
+
json.dump(json_safe(confusion_analysis), f, indent=2)
|
| 316 |
+
with open(output_dir / "run_diagnostics.json", "w", encoding="utf-8") as f:
|
| 317 |
+
json.dump(json_safe(diagnostics), f, indent=2)
|
| 318 |
+
(output_dir / "run_report.md").write_text(
|
| 319 |
+
render_run_report(args, data_summary, metrics, per_class_df, prediction_summary, confusion_analysis, warnings, fold),
|
| 320 |
+
encoding="utf-8",
|
| 321 |
+
)
|
| 322 |
+
return diagnostics
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def save_kfold_report(fold_metrics: list[dict[str, Any]], output_dir: Path) -> None:
|
| 326 |
+
diagnostics = []
|
| 327 |
+
for fold_dir in sorted(output_dir.glob("fold_*/run_diagnostics.json")):
|
| 328 |
+
with open(fold_dir, encoding="utf-8") as f:
|
| 329 |
+
payload = json.load(f)
|
| 330 |
+
payload["path"] = str(fold_dir)
|
| 331 |
+
diagnostics.append(payload)
|
| 332 |
+
(output_dir / "kfold_report.md").write_text(render_kfold_report(fold_metrics, diagnostics), encoding="utf-8")
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def render_split_summary(data_summary: dict[str, Any]) -> str:
|
| 336 |
+
lines = ["# Split Summary", ""]
|
| 337 |
+
for split in ("full", "train", "val"):
|
| 338 |
+
summary = data_summary[split]
|
| 339 |
+
lines.extend(
|
| 340 |
+
[
|
| 341 |
+
f"## {split.title()}",
|
| 342 |
+
"",
|
| 343 |
+
f"- rows: {summary['rows']}",
|
| 344 |
+
f"- real_rows: {summary['real_rows']}",
|
| 345 |
+
f"- synthetic_rows: {summary['synthetic_rows']}",
|
| 346 |
+
f"- ignore_metadata_rows: {summary['ignore_metadata_rows']}",
|
| 347 |
+
"",
|
| 348 |
+
"| class | count | synthetic |",
|
| 349 |
+
"|---|---:|---:|",
|
| 350 |
+
]
|
| 351 |
+
)
|
| 352 |
+
for class_name, count in summary["class_counts"].items():
|
| 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 |
+
|
| 359 |
+
|
| 360 |
+
def render_run_report(
|
| 361 |
+
args: Any,
|
| 362 |
+
data_summary: dict[str, Any],
|
| 363 |
+
metrics: dict[str, Any],
|
| 364 |
+
per_class_df: pd.DataFrame,
|
| 365 |
+
prediction_summary: dict[str, Any],
|
| 366 |
+
confusion_analysis: dict[str, Any],
|
| 367 |
+
warnings: list[dict[str, Any]],
|
| 368 |
+
fold: int | None,
|
| 369 |
+
) -> str:
|
| 370 |
+
lines = ["# MILK10k Run Report", ""]
|
| 371 |
+
lines.extend(
|
| 372 |
+
[
|
| 373 |
+
"## Config Summary",
|
| 374 |
+
"",
|
| 375 |
+
f"- fold: {fold}",
|
| 376 |
+
f"- output_dir: {getattr(args, 'output_dir', None)}",
|
| 377 |
+
f"- backbone: {getattr(args, 'backbone', None)}",
|
| 378 |
+
f"- metadata_fusion: {getattr(args, 'metadata_fusion', None)}",
|
| 379 |
+
f"- image_fusion: {getattr(args, 'image_fusion', None)}",
|
| 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)}",
|
| 387 |
+
f"- zero_augmented_metadata: {getattr(args, 'zero_augmented_metadata', None)}",
|
| 388 |
+
"",
|
| 389 |
+
"## Final Metrics",
|
| 390 |
+
"",
|
| 391 |
+
]
|
| 392 |
+
)
|
| 393 |
+
for key in ("accuracy", "balanced_accuracy", "dice_macro", "f1_macro", "roc_auc_macro_ovr", "top2_accuracy", "top3_accuracy"):
|
| 394 |
+
lines.append(f"- {key}: {metrics.get(key)}")
|
| 395 |
+
lines.extend(["", "## Data Distribution", "", render_distribution_table(data_summary["train"], "Train"), ""])
|
| 396 |
+
lines.extend([render_distribution_table(data_summary["val"], "Validation"), ""])
|
| 397 |
+
lines.extend(["## Per-Class Metrics", "", dataframe_to_markdown(per_class_df), ""])
|
| 398 |
+
weak = per_class_df.sort_values(["f1", "support"], ascending=[True, True]).head(5)
|
| 399 |
+
lines.extend(["## Weak Classes", "", dataframe_to_markdown(weak), ""])
|
| 400 |
+
lines.extend(["## Prediction Distribution", "", "| class | pred_count | mean_prob |", "|---|---:|---:|"])
|
| 401 |
+
for class_name, count in prediction_summary.get("predicted_class_counts", {}).items():
|
| 402 |
+
mean_prob = prediction_summary.get("mean_probability", {}).get(class_name, 0.0)
|
| 403 |
+
lines.append(f"| {class_name} | {count} | {mean_prob:.4f} |")
|
| 404 |
+
lines.extend(
|
| 405 |
+
[
|
| 406 |
+
"",
|
| 407 |
+
f"- mean_confidence: {prediction_summary.get('mean_confidence')}",
|
| 408 |
+
f"- median_confidence: {prediction_summary.get('median_confidence')}",
|
| 409 |
+
f"- mean_top1_top2_gap: {prediction_summary.get('mean_top1_top2_gap')}",
|
| 410 |
+
f"- mean_entropy: {prediction_summary.get('mean_entropy')}",
|
| 411 |
+
f"- low_confidence_rows: {prediction_summary.get('low_confidence_rows')}",
|
| 412 |
+
"",
|
| 413 |
+
"## Top Confusion Pairs",
|
| 414 |
+
"",
|
| 415 |
+
"| true | predicted | count | rate_of_true |",
|
| 416 |
+
"|---|---|---:|---:|",
|
| 417 |
+
]
|
| 418 |
+
)
|
| 419 |
+
for item in confusion_analysis.get("top_confusion_pairs", [])[:12]:
|
| 420 |
+
lines.append(f"| {item['true']} | {item['predicted']} | {item['count']} | {item['rate_of_true']:.3f} |")
|
| 421 |
+
lines.extend(["", "## Watched Confusion Patterns", "", "| true | predicted | count | rate_of_true |", "|---|---|---:|---:|"])
|
| 422 |
+
for item in confusion_analysis.get("watched_confusion_patterns", [])[:12]:
|
| 423 |
+
lines.append(f"| {item['true']} | {item['predicted']} | {item['count']} | {item['rate_of_true']:.3f} |")
|
| 424 |
+
lines.extend(["", "## Warnings", ""])
|
| 425 |
+
if warnings:
|
| 426 |
+
for item in warnings:
|
| 427 |
+
lines.append(f"- [{item['severity']}] {item['code']}: {item['message']}")
|
| 428 |
+
else:
|
| 429 |
+
lines.append("- none")
|
| 430 |
+
lines.append("")
|
| 431 |
+
return "\n".join(lines)
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
def render_distribution_table(summary: dict[str, Any], title: str) -> str:
|
| 435 |
+
lines = [
|
| 436 |
+
f"### {title}",
|
| 437 |
+
"",
|
| 438 |
+
f"- rows: {summary['rows']}",
|
| 439 |
+
f"- real_rows: {summary['real_rows']}",
|
| 440 |
+
f"- synthetic_rows: {summary['synthetic_rows']}",
|
| 441 |
+
f"- ignore_metadata_rows: {summary['ignore_metadata_rows']}",
|
| 442 |
+
"",
|
| 443 |
+
"| class | count | synthetic |",
|
| 444 |
+
"|---|---:|---:|",
|
| 445 |
+
]
|
| 446 |
+
for class_name, count in summary["class_counts"].items():
|
| 447 |
+
lines.append(f"| {class_name} | {count} | {summary['synthetic_class_counts'].get(class_name, 0)} |")
|
| 448 |
+
return "\n".join(lines)
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def render_kfold_report(fold_metrics: list[dict[str, Any]], diagnostics: list[dict[str, Any]]) -> str:
|
| 452 |
+
lines = ["# MILK10k K-Fold Report", ""]
|
| 453 |
+
if fold_metrics:
|
| 454 |
+
df = pd.DataFrame(fold_metrics)
|
| 455 |
+
metric_cols = [
|
| 456 |
+
col
|
| 457 |
+
for col in ("accuracy", "balanced_accuracy", "dice_macro", "f1_macro", "roc_auc_macro_ovr", "top3_accuracy")
|
| 458 |
+
if col in df.columns
|
| 459 |
+
]
|
| 460 |
+
lines.extend(["## Fold Metrics", "", dataframe_to_markdown(df[["fold", *metric_cols]]), ""])
|
| 461 |
+
rows = []
|
| 462 |
+
for col in metric_cols:
|
| 463 |
+
values = pd.to_numeric(df[col], errors="coerce").dropna()
|
| 464 |
+
rows.append({"metric": col, "mean": values.mean() if len(values) else None, "std": values.std(ddof=0) if len(values) else None})
|
| 465 |
+
lines.extend(["## Aggregate", "", dataframe_to_markdown(pd.DataFrame(rows)), ""])
|
| 466 |
+
lines.extend(["## Fold Warnings", ""])
|
| 467 |
+
any_warning = False
|
| 468 |
+
for payload in diagnostics:
|
| 469 |
+
fold = payload.get("fold")
|
| 470 |
+
for item in payload.get("warnings", []):
|
| 471 |
+
any_warning = True
|
| 472 |
+
lines.append(f"- fold={fold} [{item['severity']}] {item['code']}: {item['message']}")
|
| 473 |
+
if not any_warning:
|
| 474 |
+
lines.append("- none")
|
| 475 |
+
lines.append("")
|
| 476 |
+
return "\n".join(lines)
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
def dataframe_to_markdown(df: pd.DataFrame) -> str:
|
| 480 |
+
if df.empty:
|
| 481 |
+
return "_empty_"
|
| 482 |
+
columns = [str(col) for col in df.columns]
|
| 483 |
+
lines = [
|
| 484 |
+
"| " + " | ".join(columns) + " |",
|
| 485 |
+
"| " + " | ".join("---" for _ in columns) + " |",
|
| 486 |
+
]
|
| 487 |
+
for _, row in df.iterrows():
|
| 488 |
+
values = [format_markdown_value(row[col]) for col in df.columns]
|
| 489 |
+
lines.append("| " + " | ".join(values) + " |")
|
| 490 |
+
return "\n".join(lines)
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
def format_markdown_value(value: Any) -> str:
|
| 494 |
+
if pd.isna(value):
|
| 495 |
+
return ""
|
| 496 |
+
if isinstance(value, float):
|
| 497 |
+
return f"{value:.6g}"
|
| 498 |
+
return str(value)
|
milk10k_effb2_metadata/runner.py
CHANGED
|
@@ -22,6 +22,7 @@ from milk10k_effb2_metadata.engine import train_phase
|
|
| 22 |
from milk10k_effb2_metadata.losses import build_loss
|
| 23 |
from milk10k_effb2_metadata.metrics import apply_class_bias, compute_metrics, optimize_class_bias, predict, save_predictions
|
| 24 |
from milk10k_effb2_metadata.model_setup import build_model, load_resume_checkpoint
|
|
|
|
| 25 |
from milk10k_effb2_metadata.training_utils import json_safe, save_kfold_summary, save_run_config
|
| 26 |
|
| 27 |
|
|
@@ -125,6 +126,8 @@ def run_training_split(
|
|
| 125 |
split_dir.mkdir(exist_ok=True)
|
| 126 |
train_df.to_csv(split_dir / "train.csv", index=False)
|
| 127 |
val_df.to_csv(split_dir / "val.csv", index=False)
|
|
|
|
|
|
|
| 128 |
|
| 129 |
metadata_spec = fit_metadata_spec(train_df)
|
| 130 |
metadata_dim = len(metadata_vector(train_df.iloc[0], metadata_spec))
|
|
@@ -132,6 +135,7 @@ def run_training_split(
|
|
| 132 |
output_dir,
|
| 133 |
args,
|
| 134 |
class_names,
|
|
|
|
| 135 |
metadata_spec,
|
| 136 |
train_df,
|
| 137 |
val_df,
|
|
@@ -277,6 +281,17 @@ def run_training_split(
|
|
| 277 |
pd.DataFrame(cm, index=class_names, columns=class_names).to_csv(output_dir / "confusion_matrix.csv")
|
| 278 |
per_class_df.to_csv(output_dir / "per_class_metrics.csv", index=False)
|
| 279 |
save_predictions(val_df, y_true, y_prob, class_names, output_dir)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
print(
|
| 281 |
f"Done: best_val_f1_macro={best_val_f1:.4f}, "
|
| 282 |
f"val_acc={metrics['accuracy']:.4f}, balanced_acc={metrics['balanced_accuracy']:.4f}, "
|
|
@@ -356,4 +371,5 @@ def train_kfold(
|
|
| 356 |
)
|
| 357 |
fold_metrics.append({"fold": fold_idx, **metrics})
|
| 358 |
save_kfold_summary(fold_metrics, args.output_dir)
|
|
|
|
| 359 |
return fold_metrics
|
|
|
|
| 22 |
from milk10k_effb2_metadata.losses import build_loss
|
| 23 |
from milk10k_effb2_metadata.metrics import apply_class_bias, compute_metrics, optimize_class_bias, predict, save_predictions
|
| 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 |
|
|
|
|
| 126 |
split_dir.mkdir(exist_ok=True)
|
| 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)
|
| 133 |
metadata_dim = len(metadata_vector(train_df.iloc[0], metadata_spec))
|
|
|
|
| 135 |
output_dir,
|
| 136 |
args,
|
| 137 |
class_names,
|
| 138 |
+
label_to_idx,
|
| 139 |
metadata_spec,
|
| 140 |
train_df,
|
| 141 |
val_df,
|
|
|
|
| 281 |
pd.DataFrame(cm, index=class_names, columns=class_names).to_csv(output_dir / "confusion_matrix.csv")
|
| 282 |
per_class_df.to_csv(output_dir / "per_class_metrics.csv", index=False)
|
| 283 |
save_predictions(val_df, y_true, y_prob, class_names, output_dir)
|
| 284 |
+
save_run_diagnostics(
|
| 285 |
+
output_dir,
|
| 286 |
+
args,
|
| 287 |
+
data_summary,
|
| 288 |
+
metrics,
|
| 289 |
+
per_class_df,
|
| 290 |
+
cm,
|
| 291 |
+
y_prob,
|
| 292 |
+
class_names,
|
| 293 |
+
fold,
|
| 294 |
+
)
|
| 295 |
print(
|
| 296 |
f"Done: best_val_f1_macro={best_val_f1:.4f}, "
|
| 297 |
f"val_acc={metrics['accuracy']:.4f}, balanced_acc={metrics['balanced_accuracy']:.4f}, "
|
|
|
|
| 371 |
)
|
| 372 |
fold_metrics.append({"fold": fold_idx, **metrics})
|
| 373 |
save_kfold_summary(fold_metrics, args.output_dir)
|
| 374 |
+
save_kfold_report(fold_metrics, args.output_dir)
|
| 375 |
return fold_metrics
|
milk10k_effb2_metadata/training_utils.py
CHANGED
|
@@ -17,6 +17,7 @@ def save_run_config(
|
|
| 17 |
output_dir: Path,
|
| 18 |
args: argparse.Namespace,
|
| 19 |
class_names: list[str],
|
|
|
|
| 20 |
metadata_spec: dict[str, Any],
|
| 21 |
train_df: pd.DataFrame,
|
| 22 |
val_df: pd.DataFrame,
|
|
@@ -26,9 +27,13 @@ def save_run_config(
|
|
| 26 |
) -> None:
|
| 27 |
import pandas as pd
|
| 28 |
|
|
|
|
|
|
|
| 29 |
payload = {
|
| 30 |
"args": json_safe(vars(args)),
|
|
|
|
| 31 |
"class_names": class_names,
|
|
|
|
| 32 |
"metadata_spec": json_safe(metadata_spec),
|
| 33 |
"train_size": len(train_df),
|
| 34 |
"val_size": len(val_df),
|
|
@@ -37,6 +42,14 @@ def save_run_config(
|
|
| 37 |
"image_fusion": getattr(args, "image_fusion", "concat"),
|
| 38 |
"clinical_backbone": f"{clinical_backbone_backend} {args.backbone}",
|
| 39 |
"dermoscopic_backbone": f"{dermoscopic_backbone_backend} {args.backbone}",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
}
|
| 41 |
with open(output_dir / "run_config.json", "w", encoding="utf-8") as f:
|
| 42 |
json.dump(payload, f, indent=2)
|
|
|
|
| 17 |
output_dir: Path,
|
| 18 |
args: argparse.Namespace,
|
| 19 |
class_names: list[str],
|
| 20 |
+
label_to_idx: dict[str, int],
|
| 21 |
metadata_spec: dict[str, Any],
|
| 22 |
train_df: pd.DataFrame,
|
| 23 |
val_df: pd.DataFrame,
|
|
|
|
| 27 |
) -> None:
|
| 28 |
import pandas as pd
|
| 29 |
|
| 30 |
+
from milk10k_effb2_metadata.reporting import collect_environment_info
|
| 31 |
+
|
| 32 |
payload = {
|
| 33 |
"args": json_safe(vars(args)),
|
| 34 |
+
"environment": collect_environment_info(),
|
| 35 |
"class_names": class_names,
|
| 36 |
+
"label_to_idx": label_to_idx,
|
| 37 |
"metadata_spec": json_safe(metadata_spec),
|
| 38 |
"train_size": len(train_df),
|
| 39 |
"val_size": len(val_df),
|
|
|
|
| 42 |
"image_fusion": getattr(args, "image_fusion", "concat"),
|
| 43 |
"clinical_backbone": f"{clinical_backbone_backend} {args.backbone}",
|
| 44 |
"dermoscopic_backbone": f"{dermoscopic_backbone_backend} {args.backbone}",
|
| 45 |
+
"paths": {
|
| 46 |
+
"output_dir": str(output_dir),
|
| 47 |
+
"data_dir": str(getattr(args, "data_dir", "")),
|
| 48 |
+
"clinical_checkpoint": str(getattr(args, "clinical_checkpoint", "")),
|
| 49 |
+
"dermoscopic_checkpoint": str(getattr(args, "dermoscopic_checkpoint", "")),
|
| 50 |
+
"resume_checkpoint": str(getattr(args, "resume_checkpoint", "")),
|
| 51 |
+
"augmented_data_dir": str(getattr(args, "augmented_data_dir", "")),
|
| 52 |
+
},
|
| 53 |
}
|
| 54 |
with open(output_dir / "run_config.json", "w", encoding="utf-8") as f:
|
| 55 |
json.dump(payload, f, indent=2)
|