v802-classifier / src /experiment_v801_stage2.py
sneo's picture
Add v802 classifier head and source code
59839e3 verified
Raw History Blame Contribute Delete
5.49 kB
#!/usr/bin/env python3
"""Development-only second-stage probes for v801 generalization checks."""
from __future__ import annotations
import argparse
import csv
import json
import time
from pathlib import Path
import numpy as np
from iterstrat.ml_stratifiers import MultilabelStratifiedKFold
from sklearn.metrics import accuracy_score
from train_v801 import (
Spec,
crossfit_threshold_predictions,
make_variant,
oof_probabilities,
report_metrics,
spec_dict,
tune_structured_decoder,
)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--features", type=Path, required=True)
parser.add_argument("--development", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--seed", type=int, default=801208)
args = parser.parse_args()
started = time.time()
bundle = np.load(args.features)
names = bundle["file_names"].astype(str)
labels = bundle["labels"].astype(np.uint8)
name_to_index = {name: index for index, name in enumerate(names)}
with args.development.open(newline="", encoding="utf-8-sig") as handle:
rows = list(csv.DictReader(handle))
development_idx = np.asarray([name_to_index[row["file_name"]] for row in rows])
origins = np.full(len(names), "excluded", dtype="U32")
for row in rows:
origins[name_to_index[row["file_name"]]] = row["origin"]
anchor_idx = development_idx[origins[development_idx] == "old440"]
target_idx = development_idx[origins[development_idx] != "old440"]
if (len(development_idx), len(anchor_idx), len(target_idx)) != (736, 440, 296):
raise ValueError("expected development/anchor/target sizes 736/440/296")
folds = list(
MultilabelStratifiedKFold(n_splits=5, shuffle=True, random_state=args.seed).split(
np.zeros(len(target_idx)), labels[target_idx]
)
)
recent = origins[target_idx] == "incremental100"
features = {
variant: make_variant(bundle, variant)
for variant in ("legacy", "meanmax_clspatchmax")
}
specs = [
Spec(variant=variant, c=c, class_weight=class_weight, scale=False)
for variant in features
for c in (0.1, 0.3, 1.0, 3.0, 10.0, 30.0)
for class_weight in (None, "balanced")
]
# Refit the strongest standardized references in exactly the same folds.
specs.extend(
(
Spec("legacy", 0.003, class_weight=None, scale=True),
Spec("meanmax_clspatchmax", 0.003, class_weight=None, scale=True),
Spec("meanmax_clspatchmax", 0.003, class_weight="balanced", scale=True),
)
)
reports: list[dict[str, object]] = []
cache: dict[Spec, np.ndarray] = {}
for spec in specs:
probabilities = oof_probabilities(
features[spec.variant], labels, origins, anchor_idx, target_idx, folds, spec
)
cache[spec] = probabilities
predictions = crossfit_threshold_predictions(labels[target_idx], probabilities, folds)
metrics = report_metrics(labels[target_idx], probabilities, predictions)
metrics["incremental100_exact_match_accuracy"] = float(
accuracy_score(labels[target_idx][recent], predictions[recent])
)
reports.append({"spec": spec_dict(spec), "threshold_metrics": metrics})
print(
f"{spec.name}: exact={metrics['exact_match_accuracy']:.4f} "
f"recent={metrics['incremental100_exact_match_accuracy']:.4f} "
f"macro={metrics['macro_f1']:.4f}",
flush=True,
)
def key(report: dict[str, object]) -> tuple[float, ...]:
metrics = report["threshold_metrics"]
return (
float(metrics["exact_match_accuracy"]),
float(metrics["incremental100_exact_match_accuracy"]),
float(metrics["macro_f1"]),
float(metrics["mean_average_precision"]),
)
reports.sort(key=key, reverse=True)
by_name = {spec.name: spec for spec in specs}
structured: list[dict[str, object]] = []
for report in reports[:10]:
spec = by_name[str(report["spec"]["name"])]
decoder, _, metrics = tune_structured_decoder(
labels[target_idx], cache[spec], folds, origins[target_idx]
)
structured.append(
{"spec": spec_dict(spec), "decoder": decoder, "metrics": metrics}
)
print(
f"structured {spec.name}: exact={metrics['exact_match_accuracy']:.4f} "
f"recent={metrics['incremental100_exact_match_accuracy']:.4f}",
flush=True,
)
structured.sort(
key=lambda report: (
float(report["metrics"]["exact_match_accuracy"]),
float(report["metrics"]["incremental100_exact_match_accuracy"]),
float(report["metrics"]["macro_f1"]),
),
reverse=True,
)
output = {
"protocol": "development736 only; locked manifests are not read",
"seed": args.seed,
"samples": {"development": 736, "anchor": 440, "target_oof": 296},
"threshold_candidates": reports,
"structured_candidates": structured,
"seconds": time.time() - started,
}
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(output, indent=2) + "\n", encoding="utf-8")
print(json.dumps(structured[0], indent=2), flush=True)
if __name__ == "__main__":
main()