Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions changelog.d/fit-fold-degenerate-classes.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Two fold-level cases in microcosm-fit no longer leave values that are not probabilities or weights. Output for every other input is unchanged: a differential run of a fixed workload through the old and new code matched in every value.

- `out_of_fold_proba` gives each learner (`boosted`, `spline_logit`) the model's probabilities in a fold whose training rows hold a single class: certainty of that class, which the model already gave. No learner is fitted on such rows, and before, each learner's rows in that fold stayed at zero, which `categorical_scores` refuses as not a distribution (it used to score them at the log-loss floor). In such a fold each learner's rows now equal the model's, so none is left at zero. A learner that no fold fitted, as when the target holds one class, still stays out of the result. For a target with two classes or more, folds from `stratified_folds` after `can_deal_folds` reach this only when they deal whole groups into exactly two folds; the UK SPI stage deals households into five, and the UK APS stage deals rows.
- The class-balanced cross-fitted sign gate's weight helper refuses, by name, a class whose rows carry no weight. Before, it divided by that zero total and returned NaN weights. No fit reached it with such weights: the cross-fitted gate falls back to the in-sample gate (`in_sample_weightless_fold`) when some fold's training rows carry no weight for a class, testing the same totals before it balances anything. A class whose total overflows to infinity still counts as carrying weight, and its rows still weigh zero, as before. If every class's total overflows, every row's weight is NaN and the fit fails in scikit-learn, also as before.
16 changes: 8 additions & 8 deletions docs/evidence/spec-engine/us-f0-coverage.json
Original file line number Diff line number Diff line change
Expand Up @@ -1642,13 +1642,13 @@
"compiler_ir.node_slices"
],
"expected": {
"map_sha256": "d5898b936de9db3546d01b8d2986d6bfd7c66836aa1619afc453350d3ffddc7d",
"protocol_sha256": "206be396c145873c7f3c5078c56a55b59d851af0ec68ff4c4cff9b7b8cbc99ec"
"map_sha256": "6474719c2fbd765114d104118fc9f265df4694c25fab6ddde6cf5974d069b522",
"protocol_sha256": "d3a0baf888c2ac5a9d10980ec725f6cb4d1ca7de5f5e6624297858341c1a2035"
},
"failures": [],
"observed": {
"map_sha256": "d5898b936de9db3546d01b8d2986d6bfd7c66836aa1619afc453350d3ffddc7d",
"protocol_sha256": "206be396c145873c7f3c5078c56a55b59d851af0ec68ff4c4cff9b7b8cbc99ec"
"map_sha256": "6474719c2fbd765114d104118fc9f265df4694c25fab6ddde6cf5974d069b522",
"protocol_sha256": "d3a0baf888c2ac5a9d10980ec725f6cb4d1ca7de5f5e6624297858341c1a2035"
},
"status": "covered"
},
Expand All @@ -1663,7 +1663,7 @@
"compiler_ir.seed_stream_map"
],
"expected": {
"implementation_sha256": "206be396c145873c7f3c5078c56a55b59d851af0ec68ff4c4cff9b7b8cbc99ec",
"implementation_sha256": "d3a0baf888c2ac5a9d10980ec725f6cb4d1ca7de5f5e6624297858341c1a2035",
"protocol": "legacy-v1",
"streams": [
"build_model",
Expand All @@ -1684,7 +1684,7 @@
},
"failures": [],
"observed": {
"implementation_sha256": "206be396c145873c7f3c5078c56a55b59d851af0ec68ff4c4cff9b7b8cbc99ec",
"implementation_sha256": "d3a0baf888c2ac5a9d10980ec725f6cb4d1ca7de5f5e6624297858341c1a2035",
"protocol": "legacy-v1",
"streams": [
"build_model",
Expand Down Expand Up @@ -2585,7 +2585,7 @@
"country": "us",
"schema_id": "country_spec",
"schema_version": 1,
"spec_sha256": "9ad067de4d9e5ac8a70734886963145c35983b4e385177e43a04da162b700b31"
"spec_sha256": "4e2b6c19661079b1c75ab694d043c76d22f52465e7b01d37dc499a3611ca6d8c"
}
},
"report_schema_version": 3,
Expand All @@ -2595,7 +2595,7 @@
"country": "us",
"schema_id": "country_spec",
"schema_version": 1,
"spec_sha256": "9ad067de4d9e5ac8a70734886963145c35983b4e385177e43a04da162b700b31"
"spec_sha256": "4e2b6c19661079b1c75ab694d043c76d22f52465e7b01d37dc499a3611ca6d8c"
},
"status": "pass"
}
Original file line number Diff line number Diff line change
Expand Up @@ -396,9 +396,11 @@
# partnership step changes acs_transfer's attested bytes. Off its flag no
# draw, RNG rule or QRF target changes.
# microcosm#1543's fit input checks (the microimpute bug-parity audit)
# move both again; no valid input's draw changes.
"seed_map": "d5898b936de9db3546d01b8d2986d6bfd7c66836aa1619afc453350d3ffddc7d",
"seed_protocol": "206be396c145873c7f3c5078c56a55b59d851af0ec68ff4c4cff9b7b8cbc99ec",
# move both again; no valid input's draw changes. microcosm#1617's refusal
# of a weightless class in the balanced gate's weights moves both again;
# no fit reached it, and no draw changes.
"seed_map": "6474719c2fbd765114d104118fc9f265df4694c25fab6ddde6cf5974d069b522",
"seed_protocol": "d3a0baf888c2ac5a9d10980ec725f6cb4d1ca7de5f5e6624297858341c1a2035",
"source_manifest": "dc3879886d2a69f20fb982a675d7fb322c0e4017afef6471be54b0ee3cbd2af6",
"take_up": "9522ce40f7dea569312dd7a7beb474e5a5afadd2f1e10cb5876534c3ef623d35",
"tail": "565f0ceeadab69d3e96a886a00dd0305f7425fa3acde24d12ba48db2b37d5fc0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non
# The fit input checks from the microimpute bug-parity audit move the fit
# kernels' bytes too.
assert first.spec_sha256 == (
"b7c843a1c77a70b49428c9977c4111f138e7cd0b46a61c7cc3ab88636d1920bd"
"d4fc68aa1ceee27700b15e89f668b3368d361ce9f9adbc5e506aed00ee9b27bc"
)

second_root = _rich_minimal(tmp_path / "xy", note="second", store="local:b")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ def capture_equality(expected: object, actual: object) -> None:
# microcosm#922's county facts pin, two declared legacy resources,
# moves it.
# microcosm#1543's fit input checks in microcosm.fit.qrf move it again.
"spec_sha256": "9ad067de4d9e5ac8a70734886963145c35983b4e385177e43a04da162b700b31",
"spec_sha256": "4e2b6c19661079b1c75ab694d043c76d22f52465e7b01d37dc499a3611ca6d8c",
},
}

Expand Down
37 changes: 31 additions & 6 deletions packages/microcosm-fit/src/microcosm/fit/held_out.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,14 @@ def stratified_folds(

With ``groups`` whole groups are dealt, each with the rarest class it
contains, so rows that share a group are never split across folds.

Once :func:`can_deal_folds` holds, every class sits in every fold when rows
are dealt. When groups are dealt, only the rarest class (the first in
sorted order, if several tie) is sure to: another class can sit in one
fold. Even so, with three or more folds every fold's training rows (the
other folds) hold two classes or more whenever ``labels`` do. With two
folds they may hold a single class, which :func:`out_of_fold_proba`
handles.
"""
labels = np.asarray(labels)
return _qrf._stratified_folds(
Expand All @@ -98,10 +106,21 @@ def out_of_fold_proba(
"""Out-of-fold class probabilities for every row of ``table``.

Each fold's rows are scored by the model fitted on the other folds. The
result maps ``"model"`` to the model's probabilities, each fitted learner's
name (``"boosted"``, ``"spline_logit"``) to its own, and ``"marginal"`` to
the training folds' weighted class shares; ``"classes"`` holds the column
order, the sorted categories of ``table[target]``.
result maps ``"model"`` to the model's probabilities, each learner some
fold fitted (``"boosted"``, ``"spline_logit"``) to its own, and
``"marginal"`` to the training folds' weighted class shares;
``"classes"`` holds the column order, the sorted categories of
``table[target]``.

A fold whose training rows hold a single class fits no learner, and the
model gives that fold's rows the class with certainty. Each learner's rows
in that fold take the model's probabilities, so none is left at zero, and
the model, the learners and the constant are scored on the same rows; the
model and the learners differ only where a learner was fitted. When
``table[target]`` holds two classes or more, folds from
:func:`stratified_folds` after :func:`can_deal_folds` reach this only when
they deal whole groups into exactly two folds. A learner that no fold
fitted, as when ``table[target]`` holds one class, stays out of the result.
"""
weights = np.asarray(weights, dtype=np.float64)
folds = np.asarray(folds)
Expand All @@ -116,20 +135,27 @@ def full(fitted_classes: np.ndarray, proba: np.ndarray) -> np.ndarray:
result[:, np.searchsorted(classes, fitted_classes)] = proba
return result

single_class = np.zeros(len(table), dtype=bool)
for fold in np.unique(folds):
train, test = folds != fold, folds == fold
fitted = model.fit(
table.loc[train], predictors, [target], weights=weights[train]
)
scored = {"model": fitted.predict_proba(table.loc[test])}
scored.update(fitted.component_proba(table.loc[test]))
if len(fitted.classes_) == 1:
single_class |= test
shares = pd.Series(weights[train]).groupby(labels[train]).sum()
shares = shares.reindex(classes, fill_value=0.0).to_numpy()
for name, proba in scored.items():
out.setdefault(name, np.zeros((len(table), len(classes))))
out[name][test] = full(fitted.classes_, proba)
out.setdefault("marginal", np.zeros((len(table), len(classes))))
out["marginal"][test] = shares / shares.sum()
if single_class.any():
# No learner was fitted for these rows, so their rows are still zeros.
for name in out.keys() - {"classes", "model", "marginal"}:
out[name][single_class] = out["model"][single_class]
return out


Expand Down Expand Up @@ -192,8 +218,7 @@ def _scored_inputs(
raise ValueError(
f"{int(off.sum())} row(s) of proba do not sum to 1 (within "
f"{PROBABILITY_SUM_TOLERANCE:g}); each row must be a distribution "
"over the classes. A row of zeros usually means a learner was not "
"fitted for that row's fold."
"over the classes. A row of zeros means nothing scored that row."
)
if w.shape != (n,):
raise ValueError(f"weights need one value per label ({n}), got {w.shape}.")
Expand Down
23 changes: 22 additions & 1 deletion packages/microcosm-fit/src/microcosm/fit/qrf.py
Original file line number Diff line number Diff line change
Expand Up @@ -915,6 +915,20 @@ def _class_balanced_weights(

A row keeps its weight relative to the rows of its own class. The result
averages one, so the classifier's fit is on the scale of an unweighted one.

:func:`_cross_fit_gate` calls this only once every fold's training rows
carry weight for every class (:func:`_folds_carry_every_class`, the same
test on the same totals); otherwise the whole gate falls back to the
in-sample gate (:attr:`GateOutcome.WEIGHTLESS_FOLD`), so no fit meets the
refusal below. A class whose total overflows to infinity does carry
weight, and a fit can reach that. Its rows weigh zero here, as before;
if every class's total overflows, the rescale divides by a zero sum and
every row's weight is NaN, as before.

Raises:
ValueError: If a class's rows carry no weight (a total that is not
positive), naming the class: dividing by that total would give its
rows NaN weights.
"""
base = (
np.ones(len(labels), dtype=np.float64)
Expand All @@ -924,7 +938,14 @@ def _class_balanced_weights(
balanced = np.empty(len(labels), dtype=np.float64)
for value in np.unique(labels):
members = labels == value
balanced[members] = base[members] / base[members].sum()
total = base[members].sum()
if not total > 0.0:
raise ValueError(
"Class-balanced weights need every class to carry positive "
f"total weight; class {value!s} carries {float(total)!r} in "
"these rows."
)
balanced[members] = base[members] / total
return balanced * (len(labels) / balanced.sum())


Expand Down
Loading
Loading