From 4453cb204c78881e9b890aca9e6ad64173f199db Mon Sep 17 00:00:00 2001 From: bh-official Date: Mon, 26 Oct 2026 23:51:09 +0000 Subject: [PATCH 1/2] Document WOE-transformed inputs and test what the page claims Add docs/howto/woe.md covering what the artifact holds for WOE columns, band construction on a plateaued latent, reason dictionaries written against the underlying attribute, the sign of monotone constraints in WOE units, and how a missing bin differs from NaN. It ends with what has not been tested. tests/test_woe_inputs.py pins each statement on seeded synthetic WOE data: parity with the source model for sklearn, XGBoost and LightGBM, thresholds between bin values, one band per bin combination, within-band AUC, reasons, baseline behaviour, constraint signs, missing-bin handling and metadata. Closes #18 --- CHANGELOG.md | 6 + README.md | 1 + docs/howto/woe.md | 123 ++++++++++++++++++ docs/index.md | 1 + mkdocs.yml | 1 + tests/test_woe_inputs.py | 260 +++++++++++++++++++++++++++++++++++++++ 6 files changed, 392 insertions(+) create mode 100644 docs/howto/woe.md create mode 100644 tests/test_woe_inputs.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 3487d26..81c8742 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ inside each artifact (`schema_version`). ## [Unreleased] +### Documentation + +- A how-to for weight-of-evidence inputs (`docs/howto/woe.md`): what the artifact + holds, bands, reason dictionaries, monotone signs and missing bins, each + pinned by `tests/test_woe_inputs.py`. + ## [0.9.2] - 2026-10-11 The WoE floor no longer ignores rare 0/1 columns. No change to the runtime, diff --git a/README.md b/README.md index a499941..fc06c5b 100644 --- a/README.md +++ b/README.md @@ -389,6 +389,7 @@ src/compileml/runtime/ * [Tuning the compilation](docs/howto/tuning.md) * [Artifact specification](docs/ARTIFACT_SPEC.md) * [Reason codes](docs/howto/reason-codes.md) +* [Weight-of-evidence inputs](docs/howto/woe.md) * [Recalibration without band churn](docs/howto/recalibrate.md) * [Deploying to Python, SQL, and COBOL](docs/howto/deploy.md) * [Validation framework](docs/howto/validate.md) diff --git a/docs/howto/woe.md b/docs/howto/woe.md new file mode 100644 index 0000000..8861072 --- /dev/null +++ b/docs/howto/woe.md @@ -0,0 +1,123 @@ +# Weight-of-evidence inputs + +A WOE-transformed column is an ordinary numeric column that takes one value +per bin. CompileML needs nothing special for it: compile the model on the WOE +values and the artifact scores WOE values. This page lists what changes when +the inputs look like that. Every statement here is pinned by +[`tests/test_woe_inputs.py`](https://github.com/orgoca/CompileML/blob/main/tests/test_woe_inputs.py), +which uses four WOE columns of three or four bins each, built from synthetic +data with a fixed seed. sklearn, XGBoost and LightGBM models all compile and +score within the usual quantization bound of the source model. + +## What the artifact contains + +The artifact holds split thresholds **in WOE units**. It does not hold the WOE +table, the raw attribute or the bin edges, so the transform stays in your +pipeline and must be the same one the model was trained on. In the sklearn +whitebox every threshold falls between two WOE values seen in training, so a +split separates bins and never cuts one. + +If you refit the WOE table, the numbers the artifact sees change; compile a new +artifact rather than feeding new WOE values to the old one. To keep the link +visible, put the table's version in `metadata`, which is part of the hash: + +```python +artifact = build_artifact(…, metadata={"woe_table": "2026-q3"}) +``` + +## Bands and within-band AUC + +Because every column takes few values, the latent score is a plateau: rows +with the same WOE values get the same latent and therefore the same band. A +band edge can sit between bin combinations but never inside one, so a band is +always a union of bin combinations. + +The band builders run on a WOE latent without changes. +`governance_bands(latent, y, min_band_size=300)` on the test data returns +several bands and reports `band_auc` in its metadata; every band is at or +below the default cap of 0.60. + +Not measured: whether WOE inputs give more or fewer certified bands than the +same model on raw continuous features, and how `semantic_bands` behaves on +them at its default strictness. [Risk bands](../concepts/bands.md) explains +why a strict `eps_auc` can leave a plateaued latent with few bands. + +## Reason codes + +Reasons are keyed by the column name, so the dictionary key is the WOE +column's name. The text should describe the underlying attribute, because +that is what the applicant understands. The WOE value is an internal encoding +and never appears in a notice: + +```python +reasons = { + "woe_util": { + "code": "HIGH_UTILIZATION", + "negative": "Credit utilization is high relative to available limits.", + "positive": "Credit utilization is well managed.", + }, + "woe_late": { + "code": "LATE_PAYMENTS", + "negative": "Payments were made after their due date.", + "positive": "Payments were made on time.", + }, +} +display_names = {"woe_util": "Credit utilization", "woe_late": "Late payments"} + +artifact = build_artifact(…, reasons=reasons, display_names=display_names) +``` + +A row in the lowest-WOE utilization bin then reports `HIGH_UTILIZATION` with +the `negative` sentence and the label `Credit utilization`. The rest of the +mechanism is in [Reason codes](reason-codes.md). + +Two things follow from the inputs being bins: + +- **The reason is about the bin.** The artifact never sees the raw value, so a + reason says the applicant's bin scored worse than the baseline's bin, not + where inside the bin they fall. +- **The baseline should be a bin.** Attribution is measured against the + `baseline` row, and a row equal to the baseline has no reasons at all. A + per-column median of WOE values need not be any bin's value, so pass the WOE + value of the bin you mean as the reference, such as the most common bin of + each column. + +## Monotone directions + +Declared directions are in WOE units. With WOE defined as `ln(good/bad)`, +higher WOE means lower risk, so a model scoring risk is non-increasing in WOE +and the declaration is `-1`. If your WOE runs the other way, the sign flips. + +```python +model, _ = train_whitebox(X_woe, y, monotone_constraints=[-1, -1, -1, -1]) +artifact = build_artifact(…, monotone_constraints=[-1, -1, -1, -1]) +``` + +The build re-verifies the compiled trees against the declaration, as +described in [Tuning](tuning.md#enforcing-monotone-directions). Declaring the +wrong sign makes the build raise. What this guarantees is monotonicity in the +**WOE value**. Whether risk is monotone in the raw attribute is decided by how +you bin it. + +## Missing values + +If missing has its own WOE bin, give those rows that bin's WOE value before +they reach the artifact. It is then one more value of the column, and it is +scored and explained like any other bin. + +Do not pass `NaN` to stand in for it. `train_whitebox` refuses `NaN`, and a +`NaN` reaching a compiled artifact is replaced by the baseline (under the +default `missing_policy`), which is the baseline bin and not the missing bin. +A `missing_as_bin` policy is an open design +([#11](https://github.com/orgoca/CompileML/issues/11)). + +## Not yet tested + +- Real portfolios. All of the above is checked on synthetic data. +- Whether WOE inputs change the band count compared with raw features, beyond + the single case above. +- `compile_selected(..., reference="woe")` when `X` is already WOE-encoded. The + reference fits its own WOE tables on whatever columns it is given. +- Monitoring and drift reports on WOE inputs. They run on any numeric input, + but their behaviour on a column with few values is not covered here. +- Bins with very few rows, where the WOE value itself is unstable. diff --git a/docs/index.md b/docs/index.md index 05b0b7f..3f8e0e1 100644 --- a/docs/index.md +++ b/docs/index.md @@ -27,6 +27,7 @@ model ──compile──► decision.json ──runs on──► stdlib Pyt - Want the exact rules → [Artifact specification](ARTIFACT_SPEC.md) - "Why should I believe the determinism claim?" → [Determinism](concepts/determinism.md) - Writing reason codes — adverse-action notices, alert reasons → [Reason codes](howto/reason-codes.md) +- Feeding it WOE-transformed features → [Weight-of-evidence inputs](howto/woe.md) - Model risk / validation team → [Validate before deploying](howto/validate.md) ## The design in one paragraph diff --git a/mkdocs.yml b/mkdocs.yml index 237b8f2..113e2e7 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -55,6 +55,7 @@ nav: - How-to: - Tuning the compilation: howto/tuning.md - Reason codes: howto/reason-codes.md + - Weight-of-evidence inputs: howto/woe.md - Visualize decisions: howto/visualize.md - Zero-churn recalibration: howto/recalibrate.md - Deploy (runtime, SQL, COBOL): howto/deploy.md diff --git a/tests/test_woe_inputs.py b/tests/test_woe_inputs.py new file mode 100644 index 0000000..e9ea520 --- /dev/null +++ b/tests/test_woe_inputs.py @@ -0,0 +1,260 @@ +"""WOE-transformed inputs: what docs/howto/woe.md says about them. + +A weight-of-evidence column is an ordinary numeric column that takes a handful +of values, one per bin. These tests pin the statements that page makes, on +synthetic data with a fixed seed: four raw attributes cut into 3-4 bins each +and replaced by the bin's WOE (higher WOE = lower risk). +""" + +import warnings + +import numpy as np +import pytest + +from compileml.artifact import build_artifact +from compileml.bands import governance_bands +from compileml.compile import extract_trees, train_whitebox +from compileml.runtime import decide + +NAMES = ["woe_util", "woe_late", "woe_tenure", "woe_income"] +N = 6000 + + +@pytest.fixture(scope="module") +def data(): + rng = np.random.default_rng(11) + util = rng.beta(2, 3, N) + late = rng.poisson(0.6, N) + tenure = rng.gamma(3, 2, N) + income = rng.lognormal(0, 0.5, N) + logit = -1.4 + 2.0 * util + 0.5 * np.minimum(late, 3) - 0.08 * tenure - 0.3 * np.log(income) + y = (rng.random(N) < 1 / (1 + np.exp(-logit))).astype(int) + bins = np.column_stack( + [ + np.digitize(util, [0.2, 0.4, 0.6]), + np.digitize(late, [1, 2]), + np.digitize(tenure, [3, 6, 10]), + np.digitize(income, [0.7, 1.0, 1.5]), + ] + ) + woe = np.zeros(bins.shape) + for j in range(bins.shape[1]): + for b in np.unique(bins[:, j]): + m = bins[:, j] == b + bad, good = y[m].sum() + 0.5, (1 - y[m]).sum() + 0.5 + woe[m, j] = np.log((good / (y == 0).sum()) / (bad / (y == 1).sum())) + return woe, y + + +def _modal(X): + """The most common WOE value of each column: a bin, not an average of bins.""" + return np.array( + [ + np.unique(c, return_counts=True)[0][np.argmax(np.unique(c, return_counts=True)[1])] + for c in X.T + ] + ) + + +def _build(model, X, y, **kw): + latent = np.clip(model.predict(X), 0.0, 1.0) + kw.setdefault("baseline", _modal(X)) + baseline = kw.pop("baseline") + with warnings.catch_warnings(): + warnings.simplefilter("ignore") # reason coverage warning tested elsewhere + return build_artifact( + model, + NAMES, + baseline, + np.quantile(latent, np.linspace(0, 1, 6)), + calibration_latent=latent, + calibration_y=y, + X_sample=X[:500], + **kw, + ) + + +@pytest.fixture(scope="module") +def model(data): + X, y = data + return train_whitebox(X, y.astype(float), n_estimators=40)[0] + + +@pytest.fixture(scope="module") +def artifact(data, model): + X, y = data + return _build(model, X, y) + + +def test_woe_features_compile_and_match_the_source_model(data, model, artifact): + X, _ = data + assert all(len(np.unique(X[:, j])) <= 4 for j in range(X.shape[1])) + bound = artifact["metadata"]["quantization"]["error_bound"] + 1e-6 + for row in X[:300]: + got = decide(artifact, [float(v) for v in row], explain=False)["raw_micro"] / 1e6 + assert abs(got - float(model.predict(row.reshape(1, -1))[0])) <= bound + + +def test_split_thresholds_fall_between_woe_values(data, model): + """A split can only separate bins, so thresholds sit between observed values.""" + X, _ = data + extracted = extract_trees(model) + for tree in extracted.trees: + for f, thr in zip(tree["feature"], tree["threshold"]): + if f < 0: + continue + values = np.unique(X[:, f]) + assert thr not in values + assert values.min() < thr < values.max() + + +@pytest.mark.parametrize("family", ["xgboost", "lightgbm"]) +def test_boosting_libraries_compile_woe_features(data, family): + lib = pytest.importorskip(family) + X, y = data + if family == "xgboost": + model = lib.XGBRegressor(n_estimators=20, max_depth=2, learning_rate=0.3, random_state=0) + else: + model = lib.LGBMRegressor(n_estimators=20, max_depth=2, learning_rate=0.3, verbose=-1) + model.fit(X, y.astype(float)) + art = _build(model, X, y) + bound = art["metadata"]["quantization"]["error_bound"] + 1e-6 + for row in X[:300]: + got = decide(art, [float(v) for v in row], explain=False)["raw_micro"] / 1e6 + assert abs(got - float(model.predict(row.reshape(1, -1))[0])) <= bound + + +def test_rows_with_the_same_woe_values_share_a_band(data, artifact): + """Coarse bins make the latent a plateau, so edges cannot split a bin combination.""" + X, _ = data + seen: dict[tuple, int] = {} + for row in X[:2000]: + out = decide(artifact, [float(v) for v in row], explain=False) + assert seen.setdefault(tuple(row), out["band_idx"]) == out["band_idx"] + assert len(seen) < 2000 + + +def test_governance_bands_cap_within_band_auc_on_woe_latent(data, model): + X, y = data + latent = np.clip(model.predict(X), 0.0, 1.0) + spec = governance_bands(latent, y, min_band_size=300) + assert spec.n_bands >= 2 + assert max(spec.metadata["band_auc"]) <= 0.60 + + +REASONS = { + "woe_util": { + "code": "HIGH_UTILIZATION", + "negative": "Credit utilization is high relative to available limits.", + "positive": "Credit utilization is well managed.", + }, + "woe_late": { + "code": "LATE_PAYMENTS", + "negative": "Payments were made after their due date.", + "positive": "Payments were made on time.", + }, + "woe_tenure": { + "code": "SHORT_HISTORY", + "negative": "The credit history is short.", + "positive": "The credit history is long.", + }, + "woe_income": { + "code": "LOW_INCOME", + "negative": "Reported income is low.", + "positive": "Reported income is high.", + }, +} +LABELS = { + "woe_util": "Credit utilization", + "woe_late": "Late payments", + "woe_tenure": "Length of credit history", + "woe_income": "Income", +} + + +def test_reasons_carry_the_dictionary_text_for_the_underlying_attribute(data, model): + X, y = data + art = _build(model, X, y, reasons=REASONS, display_names=LABELS) + base = _modal(X) + util = np.unique(X[:, 0]) + + worst = base.copy() + worst[0] = util.min() # lowest WOE = highest risk + adverse = decide(art, list(worst))["reasons_negative"] + assert adverse[0]["feature"] == "woe_util" + assert adverse[0]["code"] == "HIGH_UTILIZATION" + assert adverse[0]["label"] == "Credit utilization" + assert adverse[0]["message"] == REASONS["woe_util"]["negative"] + + best = base.copy() + best[0] = util.max() + favorable = decide(art, list(best))["reasons_positive"] + assert favorable[0]["code"] == "HIGH_UTILIZATION" + assert favorable[0]["message"] == REASONS["woe_util"]["positive"] + + +def test_the_baseline_is_a_woe_value_and_a_row_at_the_baseline_has_no_reasons( + data, model, artifact +): + """Reasons are measured against the baseline row, not against a bin.""" + X, _ = data + base = [float(v) for v in artifact["features"]["baseline"]] + assert all(v in np.unique(X[:, j]) for j, v in enumerate(base)) + out = decide(artifact, base) + assert out["reasons_negative"] == [] and out["reasons_positive"] == [] + assert out["attribution_sum_half_micro"] == 0 + + +def test_declared_direction_is_in_woe_units(data): + """Higher WOE is lower risk, so a risk-scored model is decreasing in WOE.""" + X, y = data + cst = [-1, -1, -1, -1] + model = train_whitebox(X, y.astype(float), n_estimators=40, monotone_constraints=cst)[0] + art = _build(model, X, y, monotone_constraints=cst) + assert art["model"]["monotone_constraints"] == cst + + base = [float(v) for v in art["features"]["baseline"]] + for j in range(X.shape[1]): + scores = [] + for v in np.unique(X[:, j]): + row = list(base) + row[j] = float(v) + scores.append(decide(art, row, explain=False)["raw_micro"]) + assert scores == sorted(scores, reverse=True) + + with pytest.raises(ValueError, match="monotone constraint violated"): + _build(model, X, y, monotone_constraints=[+1, -1, -1, -1]) + + +def test_a_missing_bin_is_an_ordinary_woe_value_and_nan_is_not_that_bin(data): + X, y = data + X = X.copy() + gone = np.random.default_rng(3).random(N) < 0.1 + X[gone, 3] = 0.9 # the WOE assigned to "income missing", scored like any bin + model = train_whitebox(X, y.astype(float), n_estimators=40)[0] + art = _build(model, X, y) + base = [float(v) for v in art["features"]["baseline"]] + + in_missing_bin = list(base) + in_missing_bin[3] = 0.9 + at_baseline = decide(art, base, explain=False) + # A NaN reaching the artifact is replaced by the baseline, not by the missing bin. + for j in range(len(base)): + with_nan = list(base) + with_nan[j] = float("nan") + assert decide(art, with_nan, explain=False)["raw_micro"] == at_baseline["raw_micro"] + assert decide(art, in_missing_bin, explain=False)["raw_micro"] != at_baseline["raw_micro"] + + X_nan = X.copy() + X_nan[0, 3] = np.nan + with pytest.raises(ValueError, match="missing values"): + train_whitebox(X_nan, y.astype(float)) + + +def test_woe_table_version_can_travel_in_hashed_metadata(data, model): + """The artifact holds split thresholds in WOE units, not the WOE table.""" + X, y = data + a = _build(model, X, y, metadata={"woe_table": "v1"}) + b = _build(model, X, y, metadata={"woe_table": "v2"}) + assert a["metadata"]["woe_table"] == "v1" + assert a["artifact_hash"] != b["artifact_hash"] From 08be8abac6f77db0710d2b2a0f95ad3ecfebcc7a Mon Sep 17 00:00:00 2001 From: bh-official Date: Tue, 27 Oct 2026 13:15:54 +0000 Subject: [PATCH 2/2] docs: state that a wrong sign used for both training and declaration is not caught A review pointed out that the build only raises when the declared monotone direction disagrees with how the trees were trained. If the same wrong sign is used for both, the build passes and the cost shows up as lost discrimination, so say that explicitly. Also describe the baseline compile_selected uses (the per-column median of the development rows, which for a WOE column is a bin's value except at an exact tie), and draw the missing-bin test rows from the riskier rows so the trees are certain to split them off the baseline bin. --- docs/howto/woe.md | 18 +++++++++++------- tests/test_woe_inputs.py | 4 +++- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/docs/howto/woe.md b/docs/howto/woe.md index 8861072..cfb0b06 100644 --- a/docs/howto/woe.md +++ b/docs/howto/woe.md @@ -77,10 +77,12 @@ Two things follow from the inputs being bins: reason says the applicant's bin scored worse than the baseline's bin, not where inside the bin they fall. - **The baseline should be a bin.** Attribution is measured against the - `baseline` row, and a row equal to the baseline has no reasons at all. A - per-column median of WOE values need not be any bin's value, so pass the WOE - value of the bin you mean as the reference, such as the most common bin of - each column. + `baseline` row, and a row equal to the baseline has no reasons at all. + `compile_selected` uses the per-column median of the development rows, which + for a WOE column is a bin's value except at an exact tie, when the two middle + rows sit in different bins and the median falls between them. If you call + `build_artifact` directly, pass the WOE value of the bin you mean as the + reference, such as the most common bin of each column. ## Monotone directions @@ -94,9 +96,11 @@ artifact = build_artifact(…, monotone_constraints=[-1, -1, -1, -1]) ``` The build re-verifies the compiled trees against the declaration, as -described in [Tuning](tuning.md#enforcing-monotone-directions). Declaring the -wrong sign makes the build raise. What this guarantees is monotonicity in the -**WOE value**. Whether risk is monotone in the raw attribute is decided by how +described in [Tuning](tuning.md#enforcing-monotone-directions). If the declaration +disagrees with the trees, the build raises. A wrong sign used for both training +and the declaration is not caught: it constrains the model against the data, and +you see it as lost discrimination. What the check guarantees is monotonicity in +the **WOE value**. Whether risk is monotone in the raw attribute is decided by how you bin it. ## Missing values diff --git a/tests/test_woe_inputs.py b/tests/test_woe_inputs.py index e9ea520..e67abdc 100644 --- a/tests/test_woe_inputs.py +++ b/tests/test_woe_inputs.py @@ -229,7 +229,9 @@ def test_declared_direction_is_in_woe_units(data): def test_a_missing_bin_is_an_ordinary_woe_value_and_nan_is_not_that_bin(data): X, y = data X = X.copy() - gone = np.random.default_rng(3).random(N) < 0.1 + # Draw the "missing" rows from the riskier (bad) rows, so the trees have a reason + # to split them off the baseline bin instead of leaving it to chance. + gone = (y == 1) & (np.random.default_rng(3).random(N) < 0.3) X[gone, 3] = 0.9 # the WOE assigned to "income missing", scored like any bin model = train_whitebox(X, y.astype(float), n_estimators=40)[0] art = _build(model, X, y)