Scores par evenement, seuils valides sur le passe et intervalles par blocs

This commit is contained in:
root
2026-09-13 09:22:06 +02:00
parent 4e8c6caa2c
commit 3bee9a40d9
80 changed files with 99461 additions and 93253 deletions

View File

@@ -25,20 +25,24 @@ def fake_predictions(n=200, threshold=0.30, signal_from=60, hits_from=60, label=
out = []
for index in range(n):
hit = index >= hits_from and index % 2 == 0
value = (
score_value if score_value is not None else (threshold + 0.01 if index >= signal_from else 0.1)
)
out.append(
dict(
t=f"{index:04d}",
score=score_value
if score_value is not None
else (threshold + 0.01 if index >= signal_from else 0.1),
score={key: value for key in KEYS},
thresholds={
label: dict(
value=threshold,
calibrated_as="quantile 95% des scores de validation",
source_from="2025-01-01",
source_to="2025-12-31",
source_n=300,
)
key: {
label: dict(
value=threshold,
calibrated_as="quantile 95% des scores de validation",
source_from="2025-01-01",
source_to="2025-12-31",
source_n=300,
)
}
for key in KEYS
},
threshold_source=dict(window_from="2025-01-01", window_to="2025-12-31", frozen=True),
target=dict(
@@ -60,39 +64,28 @@ def fake_predictions(n=200, threshold=0.30, signal_from=60, hits_from=60, label=
def test_thresholds_come_only_from_past_scores_and_report_real_coverage():
past = [0.10] * 95 + [0.50] * 5
past = {key: [0.10] * 95 + [0.50] * 5 for key in KEYS}
table, source = threshold_table(past, "2025-01-01", "2025-12-31")
assert table["q95"]["value"] == pytest.approx(0.50)
assert table["q50"]["value"] == pytest.approx(0.10)
# Une distribution de test différente n'entre jamais dans le seuil.
# Un test qui monte à 0,11 ne déclenche pas un seuil de 0,50 appris dans le passé.
high = fake_predictions(n=100, threshold=table["q95"]["value"], score_value=0.11, label="q95")
assert not any(signal_flags(high, "q95")), "le seuil passé ne doit pas s'adapter au test"
low = fake_predictions(n=100, threshold=table["q50"]["value"], score_value=0.11, label="q50")
assert all(signal_flags(low, "q50")), "0,11 >= 0,10 : signal partout"
assert table["q95"]["source_from"] == "2025-01-01" and table["q95"]["source_n"] == 100
# Rang supérieur : q95 = 0,50 (les 5 % les plus hauts), q50 = 0,10.
assert table["up_3"]["q95"]["value"] == pytest.approx(0.50)
assert table["up_3"]["q50"]["value"] == pytest.approx(0.10)
assert table["down_3"]["q95"]["source_n"] == 100
assert "scores de validation" in source
# Un test qui monte à 0,11 ne déclenche pas un seuil de 0,50 appris dans le passé.
high = fake_predictions(n=100, threshold=0.50, score_value=0.11, label="q95")
assert not any(signal_flags(high, "up_3", "q95")), "le seuil passé ne doit pas s'adapter au test"
low = fake_predictions(n=100, threshold=0.10, score_value=0.11, label="q50")
assert all(signal_flags(low, "up_3", "q50")), "0,11 >= 0,10 : signal partout"
def test_coverage_is_measured_not_guaranteed():
predictions = fake_predictions(n=100, threshold=0.30, signal_from=13)
metrics = score_threshold(
[
dict(
p,
thresholds={
"q95": dict(p["thresholds"]["q95"], calibrated_as="quantile 95% des scores de validation")
},
)
for p in predictions
],
"up_3",
"q95",
)
metrics = score_threshold(predictions, "up_3", "q95")
assert metrics["n_signaled"] == 87
assert metrics["actual_test_coverage"] == pytest.approx(0.87)
assert "quantile 95%" in metrics["calibrated_as"], "le nom dit la cible de validation"
assert metrics["lift_vs_base"] is not None
assert "quantile 95%" in metrics["calibrated_as"], "le libellé dit la cible de validation"
assert metrics["threshold_source_period"] == "2025-01-01 → 2025-12-31"
assert metrics["lift_vs_base"] is not None and metrics["precision_ci"] is not None
def test_calibrator_uses_validation_only():
@@ -115,6 +108,7 @@ def test_episodes_and_non_overlapping_are_stricter_than_daily():
summary = episode_summary(predictions, "up_3", "q95")
assert summary["n_episodes"] == 1, "50 jours consécutifs = une seule opportunité"
assert summary["n_days_signaled"] == 50
assert summary["mean_episode_length_days"] == pytest.approx(50.0)
disjoint = non_overlapping(predictions, "up_3", "q95", 14)
assert disjoint["n_signaled"] == 4, "origines tous les 14 jours : fenêtres disjointes"
assert disjoint["step_days"] == 14
@@ -123,8 +117,7 @@ def test_episodes_and_non_overlapping_are_stricter_than_daily():
def test_block_bootstrap_is_deterministic_and_pairs_aware():
values = [1, 1, 0, 1, 1, 0, 0, 1] * 20
first = bootstrap_ci(values)
second = bootstrap_ci(values)
assert first == second, "graine fixe : résultat reproductible"
assert first == bootstrap_ci(values), "graine fixe : résultat reproductible"
assert first["low"] <= first["high"] and first["block_days"] == 28
assert bootstrap_ci(values[:5]) is None
@@ -133,7 +126,7 @@ def test_selection_happens_on_validation_only():
rows = [(0.05, {k: False for k in KEYS}) for _ in range(400)]
rows += [(0.32, {k: True for k in KEYS}) for _ in range(80)]
rows += [(0.12, {k: (i % 2 == 0) for k in KEYS}) for i in range(200)]
snapshot = dict(pairs=[[score, hits] for score, hits in rows])
snapshot = dict(pairs=[[{k: score for k in KEYS}, hits] for score, hits in rows])
choice = select_on_validation(snapshot, "up_3")
# À lift égal (0,15 / 0,20 / 0,30 / 0,35 / 0,40 couvrent les mêmes 80 lignes), on retient le
# seuil le plus bas : même précision pour une couverture plus large.
@@ -151,7 +144,7 @@ def test_risk_scores_are_scores_not_calibrated_probabilities():
stats["hits"][key] += 1 if index % 5 == 0 else 0
scores = risk_scores(stats, empty_stats())
assert set(scores) == {"frequency", "local_regime"}
# Le score local est rétréci vers la base : il reste borné, sans prétention de calibration.
assert set(scores["local_regime"]) == set(KEYS), "un score par événement"
assert all(0.0 <= value <= 1.0 for value in scores["local_regime"].values())
@@ -159,5 +152,5 @@ def test_raw_copies_are_never_mutated_by_evaluation():
predictions = fake_predictions(n=40, signal_from=5)
original = copy.deepcopy(predictions)
score_threshold(predictions, "up_3", "q95")
episodes(predictions, signal_flags(predictions, "q95"), "up_3")
episodes(predictions, signal_flags(predictions, "up_3", "q95"), "up_3")
assert predictions == original