Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(signals): add per-head ranking classification metrics (#107441)

posthog[bot]e91bc558e0d6
diff --git a/docs/internal/inbox-ranking-training.md b/docs/internal/inbox-ranking-training.md
index fdf127f94a24..e5d85f88dc20 100644
--- a/docs/internal/inbox-ranking-training.md
+++ b/docs/internal/inbox-ranking-training.md
@@ -64,3 +64,52 @@ For the final evaluation, compare counts and metrics with the matching baked eve
Check missing-partition metadata and grading runtime; the grader reads at most `max(horizon_days) + 1` scores objects per run.
Existing baked-only consumers need no filter changes.
New charts must opt into the daily event and select one revision per cohort as described above.
+
+## Classification metrics
+
+Every fitted head reports classification metrics next to AUC and calibration.
+They answer two questions: of the reports a head flags, how many have the outcome (precision), and of the outcomes, how many the head flags (recall).
+
+### Threshold
+
+A head predicts positive when `score >= classification_threshold`.
+A score equal to the threshold is a positive prediction.
+The threshold is the positive rate of the rows the booster was fit on.
+It means "at least as likely as the average fitting example", not a 50% probability.
+
+- **Holdout:** the threshold is the positive rate of the train-only rows. It is fixed before the holdout outcomes are read.
+- **Unseen:** the threshold is the positive rate of every row the refit was fit on. The candidate saves it per head as `refit_classification_threshold` in `metadata.json`. The scorer copies it onto each saved score as `classification_threshold`, and every daily and mature grade of those scores reads that value.
+- A champion keeps its own threshold. A candidate and a champion graded on the same reports use different cuts.
+
+The threshold is specific to the head, family, version and fitting population.
+A row budget keeps every positive and samples the negatives, so it raises the rate.
+Do not read the threshold as population prevalence, and do not compute it again from evaluation labels.
+
+### Metrics
+
+The metrics use the same eligible rows as the other metrics of the grade.
+
+- Counts: `true_positives`, `false_positives`, `true_negatives`, `false_negatives`.
+- Ratios: `precision`, `recall`, `f1`, `specificity`, `accuracy`, `balanced_accuracy` (the mean of recall and specificity), `predicted_positive_rate`.
+- `inbox_ranking_candidate_trained` carries them with a `holdout_` prefix, plus `refit_classification_threshold`.
+- `inbox_ranking_unseen_head_graded` and `inbox_ranking_unseen_head_evaluated` carry them without a prefix.
+
+Null values have three causes:
+
+- A ratio with a zero denominator is null. For example, a cohort without positives has a null recall.
+- An empty cohort with a known threshold has zero counts and null ratios.
+- A model or scores object saved before thresholds existed has null classification fields. Its other metrics stay.
+
+Readability and maturity rules do not change.
+An unbaked negative can still become a positive, so unbaked precision and recall are provisional.
+These metrics are evaluation-only: they do not change inbox order or champion promotion.
+
+### Pooling
+
+Read families and maturity levels apart.
+To pool cohorts or days, select one revision per cohort as described in [Reading the two versions](#reading-the-two-versions), sum the confusion counts, and then compute the ratios from the sums.
+Never average daily precision, recall or F1.
+A pooled line over several versions uses the frozen threshold of each version, so label it that way.
+
+After deployment and a new training and scoring run, check that the candidate events carry numeric `holdout_` fields and `refit_classification_threshold`, and that the unseen events carry `classification_threshold`.
+Check the mature grades as each head's horizon becomes available.
diff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.py
index 27930f5b4739..9055bb7d07da 100644
--- a/products/signals/dags/inbox_ranking/tests/test_training.py
+++ b/products/signals/dags/inbox_ranking/tests/test_training.py
@@ -64,6 +64,7 @@ from products.signals.dags.inbox_ranking.training.calibration import (
calibration_buckets,
expected_calibration_error,
)
+from products.signals.dags.inbox_ranking.training.classification import classification_metrics
from products.signals.dags.inbox_ranking.training.dag import (
_EXTRA_SNAPSHOT_TABLES,
METADATA_FILE,
@@ -72,6 +73,7 @@ from products.signals.dags.inbox_ranking.training.dag import (
_train_candidate,
candidate_metadata,
champion_object_key,
+ classification_thresholds,
embeddings_extras,
examples_object_key,
grade_metadata,
@@ -139,6 +141,7 @@ from products.signals.dags.inbox_ranking.training.unseen import (
score_event_rows,
score_pool,
scored_pool,
+ scores_table,
unseen_pool,
with_model_names,
)
@@ -532,6 +535,20 @@ def test_train_head_learns_a_separable_signal_and_names_its_features():
assert trained.metrics.holdout_positive_rate == pytest.approx(
trained.metrics.holdout_positives / trained.metrics.holdout_rows
)
+ # The holdout cut is the train-only rate, and the unseen cut is the rate of every refit row.
+ holdout = trained.metrics.holdout_classification
+ assert holdout.threshold == pytest.approx(trained.metrics.train_positives / trained.metrics.train_rows)
+ assert trained.metrics.refit_classification_threshold == pytest.approx(examples["label"].mean())
+ assert holdout.threshold != trained.metrics.refit_classification_threshold
+ counts = (holdout.true_positives, holdout.false_positives, holdout.true_negatives, holdout.false_negatives)
+ assert sum(count or 0 for count in counts) == trained.metrics.holdout_rows
+ assert holdout.precision is not None and holdout.precision > 0.8
+ assert holdout.recall is not None and holdout.recall > 0.8
+ metadata_head = trained.metrics.as_dict()
+ assert metadata_head["holdout_classification_threshold"] == holdout.threshold
+ assert classification_thresholds({"heads": [metadata_head]}) == {
+ head.name: trained.metrics.refit_classification_threshold
+ }
booster = xgb.Booster()
booster.load_model(bytearray(trained.booster_ubj))
assert booster.feature_names == list(FEATURE_NAMES)
@@ -588,6 +605,10 @@ def test_train_head_keeps_logloss_on_a_single_class_holdout():
assert len(trained.calibration) == BUCKETS
assert trained.metrics.holdout_mean_score is not None
assert trained.metrics.holdout_expected_calibration_error == pytest.approx(trained.metrics.holdout_mean_score)
+ # No holdout positive: recall has no denominator, and the negatives still give specificity.
+ assert trained.metrics.holdout_classification.recall is None
+ assert trained.metrics.holdout_classification.false_negatives == 0
+ assert trained.metrics.holdout_classification.specificity is not None
def test_train_head_returns_none_without_both_classes():
@@ -965,7 +986,7 @@ def test_unseen_daily_evaluations_keep_baked_events_at_each_heads_horizon(
def test_daily_evaluation_keeps_empty_and_single_class_cohorts_explicit(impressions):
head = HEADS_BY_NAME["open"]
graded = graded_rows(
- _scores(["pending"], head_readable=[False]),
+ _scores(["pending"], head_readable=[False], classification_threshold=[0.2]),
_labels(["pending"], impression_unit_count=[impressions]),
head,
pool=POOL_NAME,
@@ -974,11 +995,62 @@ def test_daily_evaluation_keeps_empty_and_single_class_cohorts_explicit(impressi
assert (grade.scored_rows, grade.rows, grade.positives) == (1, impressions, 0)
assert (grade.auc, grade.recency_auc, grade.null_auc) == (None, None, None)
assert grade.readable is False
+ assert grade.classification.threshold == 0.2
+ assert (grade.classification.true_positives or 0) + (grade.classification.false_positives or 0) == impressions
+ assert grade.classification.recall is None
if not impressions:
assert (grade.mean_score, grade.base_rate, grade.expected_calibration_error) == (None, None, None)
assert head_grades(graded, head, pool=POOL_NAME, scoring_partition=D0.isoformat()) == []
+ "outcomes,scores,threshold,expected",
+ [
+ # A score equal to the threshold is a positive prediction.
+ (
+ [1, 1, 0, 0, 1],
+ [0.3, 0.2, 0.3, 0.1, 0.05],
+ 0.2,
+ {
+ "true_positives": 2,
+ "false_positives": 1,
+ "true_negatives": 1,
+ "false_negatives": 1,
+ "precision": 2 / 3,
+ "recall": 2 / 3,
+ "f1": 2 / 3,
+ "specificity": 0.5,
+ "accuracy": 0.6,
+ "balanced_accuracy": (2 / 3 + 0.5) / 2,
+ "predicted_positive_rate": 0.6,
+ },
+ ),
+ # Nothing flagged: precision has no denominator, so it and F1 are null.
+ (
+ [1, 0],
+ [0.1, 0.1],
+ 0.5,
+ {"true_positives": 0, "false_negatives": 1, "precision": None, "recall": 0.0, "f1": None},
+ ),
+ # A single-class cohort has no recall and no balanced accuracy.
+ ([0, 0], [0.9, 0.1], 0.5, {"recall": None, "specificity": 0.5, "balanced_accuracy": None, "f1": None}),
+ # An empty cohort with a known cut keeps zero counts and null ratios.
+ (
+ [],
+ [],
+ 0.5,
+ {"true_positives": 0, "false_positives": 0, "accuracy": None, "predicted_positive_rate": None},
+ ),
+ # A model saved before thresholds existed reports every field as null.
+ ([1, 0], [0.9, 0.1], None, {"threshold": None, "true_positives": None, "precision": None}),
+ ],
+)
+def test_classification_metrics_at_a_frozen_threshold(outcomes, scores, threshold, expected):
+ metrics = classification_metrics(np.array(outcomes, dtype=bool), np.array(scores, dtype=float), threshold)
+ actual = {name: getattr(metrics, name) for name in expected}
+ assert actual == pytest.approx(expected)
+
+
def test_calibration_buckets_keep_a_run_of_tied_scores_in_one_bucket():
# Splitting a run of equal scores would give each half a realized rate that depends on the
# order the rows arrived in, and report a gap that is not there.
@@ -1083,9 +1155,20 @@ def test_head_grades_keep_every_family_apart_on_the_same_rows():
EMBEDDINGS_MODEL_NAME: [0.1, 0.9],
TITLE_EMBEDDINGS_MODEL_NAME: [0.8, 0.2],
}
+ thresholds = {TABULAR_MODEL_NAME: 0.5, EMBEDDINGS_MODEL_NAME: 0.05, TITLE_EMBEDDINGS_MODEL_NAME: 0.95}
graded = pd.concat(
[
- graded_rows(_scores(["a", "e"], score=score, model_name=[model_name] * 2), labels, head, pool=POOL_NAME)
+ graded_rows(
+ _scores(
+ ["a", "e"],
+ score=score,
+ model_name=[model_name] * 2,
+ classification_threshold=[thresholds[model_name]] * 2,
+ ),
+ labels,
+ head,
+ pool=POOL_NAME,
+ )
for model_name, score in per_family.items()
],
ignore_index=True,
@@ -1096,6 +1179,12 @@ def test_head_grades_keep_every_family_apart_on_the_same_rows():
(TABULAR_MODEL_NAME, 2, 1.0),
(TITLE_EMBEDDINGS_MODEL_NAME, 2, 1.0),
]
+ # Each model keeps the cut it saved, and never borrows another model's.
+ assert [(grade.classification.threshold, grade.classification.predicted_positive_rate) for grade in grades] == [
+ (0.05, 1.0),
+ (0.5, 0.5),
+ (0.95, 0.0),
+ ]
# And the calibration read follows the grade, so each family has its own deciles.
assert {row["model_name"] for row in calibration_rows(grades)} == set(per_family)
@@ -1194,7 +1283,9 @@ def test_load_unseen_models_skips_a_family_with_nothing_to_score_that_day(monkey
"feature_set": TABULAR_FEATURE_SET.name,
"feature_schema_version": FEATURE_SCHEMA_VERSION,
"feature_names": list(FEATURE_NAMES),
- "heads": [{"head": "open", "readable": True, "file": "open.ubj"}],
+ "heads": [
+ {"head": "open", "readable": True, "file": "open.ubj", "refit_classification_threshold": 0.12},
+ ],
}
client = _ModelStoreS3(
{
@@ -1215,6 +1306,7 @@ def test_load_unseen_models_skips_a_family_with_nothing_to_score_that_day(monkey
assert [(model.model_name, model.model_role, sorted(model.boosters)) for model in models] == [
(TABULAR_MODEL_NAME, CANDIDATE_ROLE, ["open"])
]
+ assert models[0].classification_thresholds == {"open": 0.12}
@pytest.mark.parametrize(
@@ -1265,12 +1357,21 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):
"lookback_days": 60,
"holdout_days": 7,
"heads": [
- {"head": "open", "holdout_auc": 0.67, "readable": True, "file": "open.ubj", "holdout_file": None},
+ {
+ "head": "open",
+ "holdout_auc": 0.67,
+ "holdout_precision": 0.4,
+ "readable": True,
+ "file": "open.ubj",
+ "holdout_file": None,
+ },
{"head": "action", "holdout_auc": None, "readable": False, "file": "action.ubj", "holdout_file": None},
],
"skipped_heads": ["dismiss_wrong"],
}
- scores = _scores(["a"], model_version=["2026-08-25"], score=[0.8], label_at_scoring=[True])
+ scores = _scores(
+ ["a"], model_version=["2026-08-25"], score=[0.8], label_at_scoring=[True], classification_threshold=[0.3]
+ )
graded = graded_rows(scores, _labels(["a"], open_count=[1]), HEADS_BY_NAME["open"], pool=POOL_NAME)
grades = head_grades(graded, HEADS_BY_NAME["open"], pool=POOL_NAME, scoring_partition="2026-08-22")
events = [
@@ -1341,6 +1442,7 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):
candidates = by_event["inbox_ranking_candidate_trained"]
assert [c["properties"]["head"] for c in candidates] == ["open", "action", "dismiss_wrong"]
assert candidates[0]["properties"]["holdout_auc"] == 0.67
+ assert candidates[0]["properties"]["holdout_precision"] == 0.4
assert candidates[0]["properties"]["lookback_days"] == 60
assert candidates[0]["properties"]["trained"] is True
# The unseen events carry both roles, so this side needs the role to survive the same filter.
@@ -1388,6 +1490,11 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):
"readable": True,
"auc": None,
"mean_score": 0.8,
+ "classification_threshold": 0.3,
+ "true_positives": 1,
+ "precision": 1.0,
+ "recall": 1.0,
+ "specificity": None,
}.items() <= head_graded_props.items()
assert head_graded_props["expected_calibration_error"] == pytest.approx(0.2)
calibration_props = by_event["inbox_ranking_unseen_calibration"][0]["properties"]
@@ -1640,15 +1747,26 @@ def test_an_unreadable_trained_head_is_still_scored_and_graded():
feature_set=TABULAR_FEATURE_SET,
boosters={"open": booster, "thumbs_up": booster},
readable_heads=readable_head_names(metadata),
+ classification_thresholds={"thumbs_up": 0.0},
)
scores = score_pool(_state(["a", "b"]), _labels(["a", "b"]), [model], snapshot_date=D0)
assert scores.groupby("head")["head_readable"].all().to_dict() == {"open": True, "thumbs_up": False}
+ # The saved threshold survives the scores object, and a head without one stays null.
+ buffer = io.BytesIO()
+ pq.write_table(scores_table(scores), buffer)
+ scores = pq.read_table(io.BytesIO(buffer.getvalue())).to_pandas()
+ assert scores.groupby("head")["classification_threshold"].max().fillna(-1).to_dict() == {
+ "open": -1,
+ "thumbs_up": 0.0,
+ }
head = HEADS_BY_NAME["thumbs_up"]
labels = _labels(["a", "b"], open_count=[1, 1], feedback_positive_count=[1, 0])
graded = graded_rows(scores[scores["head"] == head.name], labels, head, pool=POOL_NAME)
(grade,) = head_grades(graded, head, pool=POOL_NAME, scoring_partition="2026-08-10")
assert (grade.rows, grade.positives, grade.readable) == (2, 1, False)
+ assert (grade.classification.threshold, grade.classification.true_positives) == (0.0, 1)
+ assert grade.as_dict()["recall"] == 1.0
def test_a_scores_object_written_before_the_readable_column_grades_as_readable():
@@ -1660,6 +1778,9 @@ def test_a_scores_object_written_before_the_readable_column_grades_as_readable()
assert graded["head_readable"].all()
(grade,) = head_grades(graded, head, pool=POOL_NAME, scoring_partition="2026-08-10")
assert grade.readable
+ # No saved threshold either: the other metrics stay and the classification fields are null.
+ assert grade.auc == 0.5
+ assert grade.classification.threshold is None and grade.as_dict()["precision"] is None
def test_score_pool_builds_one_matrix_per_feature_set_and_shares_it():
diff --git a/products/signals/dags/inbox_ranking/training/classification.py b/products/signals/dags/inbox_ranking/training/classification.py
new file mode 100644
index 000000000000..f4b72f2e5a9f
--- /dev/null
+++ b/products/signals/dags/inbox_ranking/training/classification.py
@@ -0,0 +1,93 @@
+"""Per-head classification metrics at a frozen threshold.
+
+AUC and calibration grade the scores as a ranking and as probabilities. They do not say how many of
+the reports a head flags have the outcome, or how many of the outcomes it flags. Those answers need
+a cut, and every head predicts positive when its score is at least the positive rate of the rows its
+booster was fit on: "at least as likely as the average fitting example", not "above 50%".
+
+The threshold comes from the fit, never from the rows being graded. The holdout grade reads the
+train-only rate, and the unseen grade reads the refit rate saved with the model. A row budget keeps
+every positive, so that rate is the sample's rate and not the population's prevalence.
+"""
+
+import numpy as np
+
+from posthog.dataclasses import frozen
+
+
+@frozen
+class ClassificationMetrics:
+ """The confusion counts at `threshold`, and the ratios derived from them.
+
+ Every field is None when the threshold is unknown, which is the case for a model or a scores
+ object saved before thresholds existed. With a known threshold the counts are always ints,
+ zero on an empty cohort, and a ratio is None only when its denominator is zero.
+ """
+
+ threshold: float | None = None
+ true_positives: int | None = None
+ false_positives: int | None = None
+ true_negatives: int | None = None
+ false_negatives: int | None = None
+ precision: float | None = None
+ recall: float | None = None
+ f1: float | None = None
+ specificity: float | None = None
+ accuracy: float | None = None
+ balanced_accuracy: float | None = None
+ predicted_positive_rate: float | None = None
+
+ def as_dict(self, prefix: str = "") -> dict[str, int | float | None]:
+ return {
+ f"{prefix}classification_threshold": self.threshold,
+ f"{prefix}true_positives": self.true_positives,
+ f"{prefix}false_positives": self.false_positives,
+ f"{prefix}true_negatives": self.true_negatives,
+ f"{prefix}false_negatives": self.false_negatives,
+ f"{prefix}precision": self.precision,
+ f"{prefix}recall": self.recall,
+ f"{prefix}f1": self.f1,
+ f"{prefix}specificity": self.specificity,
+ f"{prefix}accuracy": self.accuracy,
+ f"{prefix}balanced_accuracy": self.balanced_accuracy,
+ f"{prefix}predicted_positive_rate": self.predicted_positive_rate,
+ }
+
+
+UNKNOWN_THRESHOLD = ClassificationMetrics()
+
+
+def _ratio(numerator: int, denominator: int) -> float | None:
+ return numerator / denominator if denominator else None
+
+
+def classification_metrics(outcomes: np.ndarray, scores: np.ndarray, threshold: float | None) -> ClassificationMetrics:
+ """The metrics of `scores >= threshold` against `outcomes`. A score equal to the threshold is a
+ positive prediction."""
+ if threshold is None:
+ return UNKNOWN_THRESHOLD
+ actual = np.asarray(outcomes, dtype=bool)
+ predicted = np.asarray(scores, dtype=float) >= threshold
+ tp = int((predicted & actual).sum())
+ fp = int((predicted & ~actual).sum())
+ tn = int((~predicted & ~actual).sum())
+ fn = int((~predicted & actual).sum())
+ precision = _ratio(tp, tp + fp)
+ recall = _ratio(tp, tp + fn)
+ specificity = _ratio(tn, tn + fp)
+ return ClassificationMetrics(
+ threshold=float(threshold),
+ true_positives=tp,
+ false_positives=fp,
+ true_negatives=tn,
+ false_negatives=fn,
+ precision=precision,
+ recall=recall,
+ # 2TP / (2TP + FP + FN) is the harmonic mean where precision and recall both exist, and
+ # reads 0 rather than 0/0 when both are 0.
+ f1=_ratio(2 * tp, 2 * tp + fp + fn) if precision is not None and recall is not None else None,
+ specificity=specificity,
+ accuracy=_ratio(tp + tn, len(actual)),
+ balanced_accuracy=(recall + specificity) / 2 if recall is not None and specificity is not None else None,
+ predicted_positive_rate=_ratio(tp + fp, len(actual)),
+ )
diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.py
index 4887d3dadab2..945de629622a 100644
--- a/products/signals/dags/inbox_ranking/training/dag.py
+++ b/products/signals/dags/inbox_ranking/training/dag.py
@@ -950,6 +950,16 @@ _HORIZON_MAPPING = dagster.TimeWindowPartitionMapping(
)
+def classification_thresholds(metadata: Mapping[str, Any]) -> dict[str, float]:
+ """The saved refit threshold per head. A model saved before thresholds existed has none, and its
+ grades then report null classification fields rather than a threshold read from the graded rows."""
+ return {
+ entry["head"]: float(entry["refit_classification_threshold"])
+ for entry in metadata.get("heads", [])
+ if entry.get("refit_classification_threshold") is not None
+ }
+
+
def load_family_models(
context: dagster.AssetExecutionContext, client, bucket: str, prefix: str, partition_key: str, model_name: str
) -> list[UnseenModel]:
@@ -992,6 +1002,7 @@ def load_family_models(
feature_set=feature_set,
boosters=boosters,
readable_heads=readable_head_names(metadata),
+ classification_thresholds=classification_thresholds(metadata),
)
)
return models
diff --git a/products/signals/dags/inbox_ranking/training/train.py b/products/signals/dags/inbox_ranking/training/train.py
index a6a3872b6adf..880239cb2f7a 100644
--- a/products/signals/dags/inbox_ranking/training/train.py
+++ b/products/signals/dags/inbox_ranking/training/train.py
@@ -21,6 +21,11 @@ from products.signals.dags.inbox_ranking.training.calibration import (
calibration_buckets,
expected_calibration_error,
)
+from products.signals.dags.inbox_ranking.training.classification import (
+ UNKNOWN_THRESHOLD,
+ ClassificationMetrics,
+ classification_metrics,
+)
from products.signals.dags.inbox_ranking.training.examples import holdout_mask
from products.signals.dags.inbox_ranking.training.heads import Head
@@ -71,6 +76,12 @@ class HeadMetrics:
# part of a gap to the unseen numbers is the refit rather than holdout optimism.
holdout_mean_score: float | None = None
holdout_expected_calibration_error: float | None = None
+ # The holdout graded at the positive rate of the train-only rows, the threshold fixed before the
+ # holdout outcomes are read.
+ holdout_classification: ClassificationMetrics = UNKNOWN_THRESHOLD
+ # The positive rate of every row the refit that ships was fit on. The unseen grades of this
+ # model read it as their threshold, so it is saved here rather than derived from the unseen rows.
+ refit_classification_threshold: float | None = None
def as_dict(self) -> dict[str, object]:
return {
@@ -90,6 +101,8 @@ class HeadMetrics:
"holdout_positive_rate": self.holdout_positive_rate,
"holdout_mean_score": self.holdout_mean_score,
"holdout_expected_calibration_error": self.holdout_expected_calibration_error,
+ **self.holdout_classification.as_dict(prefix="holdout_"),
+ "refit_classification_threshold": self.refit_classification_threshold,
}
@@ -188,6 +201,8 @@ def train_head(
holdout_positive_rate=float(y_test.mean()) if len(y_test) else None,
holdout_mean_score=float(holdout_scores.mean()) if len(y_test) else None,
holdout_expected_calibration_error=expected_calibration_error(calibration),
+ holdout_classification=classification_metrics(y_test, holdout_scores, float(y_train.mean())),
+ refit_classification_threshold=float(y.mean()),
)
# Refit on everything before shipping: the holdout only exists to grade the recipe.
final = _fit(x, y, seed)
diff --git a/products/signals/dags/inbox_ranking/training/unseen.py b/products/signals/dags/inbox_ranking/training/unseen.py
index bf50b6c2bd52..4dd90b0fb7bb 100644
--- a/products/signals/dags/inbox_ranking/training/unseen.py
+++ b/products/signals/dags/inbox_ranking/training/unseen.py
@@ -13,6 +13,7 @@ functions over frames; `training/dag.py` owns the S3 and telemetry plumbing.
import datetime
from collections.abc import Collection, Mapping, Sequence
+from dataclasses import field
from typing import Any
import numpy as np
@@ -38,6 +39,11 @@ from products.signals.dags.inbox_ranking.training.calibration import (
calibration_buckets,
expected_calibration_error,
)
+from products.signals.dags.inbox_ranking.training.classification import (
+ UNKNOWN_THRESHOLD,
+ ClassificationMetrics,
+ classification_metrics,
+)
from products.signals.dags.inbox_ranking.training.examples import birth_day_mask, point_in_time_mask, state_rows
from products.signals.dags.inbox_ranking.training.heads import HEADS_BY_NAME, Head
@@ -82,6 +88,9 @@ _SCORE_TYPES: dict[str, pa.DataType] = {
"age_hours": pa.float64(),
"label_at_scoring": pa.bool_(),
"head_readable": pa.bool_(),
+ # The refit positive rate of the model that wrote the row. Null for a model saved before the
+ # threshold existed, and absent from an object written before the column existed.
+ "classification_threshold": pa.float64(),
}
SCORES_SCHEMA = pa.schema(_SCORE_TYPES)
SCORE_COLUMNS = tuple(_SCORE_TYPES)
@@ -112,6 +121,9 @@ class UnseenModel:
# Of those heads, the ones whose holdout could be read. Carried onto every scored row, because
# the grade runs `horizon_days` later and has no metadata of the model that wrote the row.
readable_heads: frozenset[str] = frozenset()
+ # Per head, the threshold every later grade of these scores reads. Carried onto the scored rows
+ # for the same reason as `readable_heads`.
+ classification_thresholds: Mapping[str, float] = field(default_factory=dict)
@frozen
@@ -174,6 +186,9 @@ class HeadGrade:
# The deciles are a table, so they stay off the head event and go out one event per bucket.
calibration: tuple[CalibrationBucket, ...]
expected_calibration_error: float | None
+ # The in-cohort rows at the threshold of the model that wrote the scores, so an early and a
+ # mature grade of one cohort use the same cut.
+ classification: ClassificationMetrics = UNKNOWN_THRESHOLD
def metrics(self) -> dict[str, int | float | None]:
return {
@@ -189,6 +204,7 @@ class HeadGrade:
"null_auc": self.null_auc,
"null_auc_std": self.null_auc_std,
"null_permutations": NULL_PERMUTATIONS,
+ **self.classification.as_dict(),
}
def identity(self) -> dict[str, object]:
@@ -382,6 +398,7 @@ def score_pool(
"age_hours": age_hours,
"label_at_scoring": HEADS_BY_NAME[head_name].label(aligned_labels).to_numpy(),
"head_readable": head_name in model.readable_heads,
+ "classification_threshold": model.classification_thresholds.get(head_name, np.nan),
}
)
for head_name, booster_ubj in model.boosters.items()
@@ -480,6 +497,16 @@ def graded_rows(head_scores: pd.DataFrame, labels: pd.DataFrame, head: Head, *,
return graded
+def saved_threshold(scored: pd.DataFrame) -> float | None:
+ """The one threshold the model that wrote `scored` saved for the head, or None when the rows
+ carry none. More than one value means the rows did not come from one model, so no single cut
+ applies to them."""
+ if "classification_threshold" not in scored:
+ return None
+ values = scored["classification_threshold"].dropna().unique()
+ return float(values[0]) if len(values) == 1 else None
+
+
def head_grades(
graded: pd.DataFrame, head: Head, *, pool: str, scoring_partition: str, include_empty: bool = False
) -> list[HeadGrade]:
@@ -524,6 +551,8 @@ def head_grades(
null_auc_std=band.auc_std,
calibration=buckets,
expected_calibration_error=expected_calibration_error(buckets),
+ # Read from every scored row, so an empty cohort still reports its threshold.
+ classification=classification_metrics(outcomes, scores, saved_threshold(scored)),
)
)
return grades