Files
ssw-mvp/nax/tests/test_binning.py
T
admin 3247e9fd15 init: ssw-mvp initial commit
- boot/ (Java/Maven, JNPF 7.0) — 移除旧的 boot/.git,源码直接纳入仓库
- web/ (Vue 3 + Vite + Ant Design Vue, pnpm)
- docs/, scard/, nax/
- refs/INDEX.md + refs/国标/(其余 refs/* 开源子仓库不纳入)
- 已忽略: connector_data/, jweb/, log/, web/{dist,node_modules,.pnpm}, boot/*/target/, .DS_Store, .idea, .vscode
2026-08-05 18:29:12 +08:00

294 lines
13 KiB
Python

"""纵向联邦分箱 + WOE/IV 的端到端测试。
判据只有一条:**联邦口径必须逐箱等于 pandas 明文口径**。
分箱是风控建模的第一道工序,差一个样本都会让评分卡对不上,
所以这里不做「近似相等」,直接比整数。
"""
import numpy as np
import pandas as pd
import pytest
import nax
from nax.data import VFrame
from nax.errors import ProtocolError
from nax.ml import FeatureBinning, hetero_binning
from nax.ml.binning import BinReport
def make_credit(n=240, seed=0):
"""造一份「特征方有 age/income、标签方有逾期标记」的纵向数据。"""
rng = np.random.default_rng(seed)
age = rng.normal(40, 10, n)
income = rng.gamma(3.0, 8000, n)
logit = -0.08 * (age - 40) + 1.0e-5 * (income - 24000)
y = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
feat = pd.DataFrame({"id": np.arange(n), "age": age, "income": income})
lab = pd.DataFrame({"id": np.arange(n), "y": y})
return feat, lab
def build(feat, lab):
frame = VFrame(
{"alice": nax.site("alice").put(feat), "bob": nax.site("bob").put(lab)}
)
return frame, nax.vault(["alice", "bob"], seed=17)
def plain_counts(values, edges, y):
"""pandas 侧的参照实现:按同样的切点数箱。"""
idx = np.searchsorted(np.asarray(edges, dtype=np.float64), values, side="right")
n_bins = len(edges) + 1
cnt = np.bincount(idx, minlength=n_bins)
bad = np.bincount(idx, weights=y, minlength=n_bins)
return cnt.astype(int), bad.astype(int)
class TestAgainstPlaintext:
def test_counts_match_pandas(self, two_party):
feat, lab = make_credit()
frame, v = build(feat, lab)
rep = FeatureBinning(v, bins=5, expose_cuts=True).fit(
frame, "alice", ["age", "income"], "bob", "y"
)
for f in ("age", "income"):
cnt, bad = plain_counts(feat[f].values, rep.cuts[f], lab["y"].values)
got = rep.table[rep.table.feature == f].sort_values("bin")
assert np.array_equal(got["count"].values.astype(int), cnt)
assert np.array_equal(got["bad"].values.astype(int), bad)
assert np.array_equal(got["good"].values.astype(int), cnt - bad)
def test_iv_matches_plaintext(self, two_party):
feat, lab = make_credit()
frame, v = build(feat, lab)
smoothing = 0.5
rep = FeatureBinning(v, bins=4, smoothing=smoothing, expose_cuts=True).fit(
frame, "alice", ["age"], "bob", "y"
)
cnt, bad = plain_counts(feat["age"].values, rep.cuts["age"], lab["y"].values)
good = cnt - bad
g_all = good.sum() + smoothing * len(cnt)
b_all = bad.sum() + smoothing * len(cnt)
iv = sum(
((g + smoothing) / g_all - (b + smoothing) / b_all)
* np.log(((g + smoothing) / g_all) / ((b + smoothing) / b_all))
for g, b in zip(good, bad)
)
assert rep.iv["age"] == pytest.approx(float(iv), abs=1e-9)
def test_predictive_feature_ranks_first(self, two_party):
"""age 的系数是 income 的量级之上,IV 必须把它排前面。"""
feat, lab = make_credit(n=400, seed=3)
feat["noise"] = np.random.default_rng(9).normal(size=len(feat))
frame, v = build(feat, lab)
rep = hetero_binning(v, frame, "alice", ["age", "noise"], "bob", "y", bins=5)
assert rep.top_features(1) == ["age"]
assert rep.iv["age"] > rep.iv["noise"]
def test_row_totals_equal_sample_count(self, two_party):
feat, lab = make_credit(n=180, seed=5)
frame, v = build(feat, lab)
rep = hetero_binning(v, frame, "alice", ["age", "income"], "bob", "y")
assert rep.n_samples == 180
for f in ("age", "income"):
seg = rep.table[rep.table.feature == f]
assert int(seg["count"].sum()) == 180
class TestPrivacyGuards:
def test_cut_points_stay_home_by_default(self, two_party):
feat, lab = make_credit(n=120)
frame, v = build(feat, lab)
rep = FeatureBinning(v, bins=4).fit(frame, "alice", ["age"], "bob", "y")
assert rep.cuts is None
# 报告里只有箱号,没有任何切点数值
assert rep.table["lower"].isna().all()
assert rep.table["upper"].isna().all()
# 但统计量是照常发布的
assert rep.table["count"].notna().all()
def test_small_bins_are_suppressed(self, two_party):
"""人为造一个只有 2 个样本的箱,它必须整行不报数。"""
rng = np.random.default_rng(0)
n = 100
x = np.concatenate([rng.uniform(0, 1, n - 2), np.array([50.0, 51.0])])
y = (rng.random(n) < 0.4).astype(int)
feat = pd.DataFrame({"x": x, "z": rng.uniform(0, 1, n)})
lab = pd.DataFrame({"y": y})
frame, v = build(feat, lab)
rep = FeatureBinning(v, strategy="custom", min_bin_size=5).fit(
frame, "alice", ["x"], "bob", "y",
custom_cuts={"x": [0.3, 0.6, 10.0]},
)
tail = rep.table[rep.table.bin == 3].iloc[0]
assert bool(tail["suppressed"]) is True
assert pd.isna(tail["count"]) and pd.isna(tail["bad"]) and pd.isna(tail["woe"])
# 主抑制 + 互补抑制 = 两个洞
assert rep.suppressed == 2
assert int(rep.table["suppressed"].astype(bool).sum()) == 2
def test_suppressed_bin_not_recoverable_by_subtraction(self, two_party):
"""被抑制的箱不能靠「总数 − 其它箱」倒推出来。
总样本数 n 在 PSI 之后是公开的,所以只藏一个格子毫无意义。
互补抑制必须保证残差至少摊在两个格子上。
"""
rng = np.random.default_rng(1)
n = 80
x = np.concatenate([rng.uniform(0, 1, n - 3), np.array([9.0, 9.1, 9.2])])
y = (rng.random(n) < 0.5).astype(int)
frame, v = build(pd.DataFrame({"x": x}), pd.DataFrame({"y": y}))
rep = FeatureBinning(v, strategy="custom", min_bin_size=5).fit(
frame, "alice", ["x"], "bob", "y", custom_cuts={"x": [0.3, 0.6, 5.0]}
)
hidden = rep.table["suppressed"].astype(bool)
published = rep.table[~hidden]
residual = rep.n_samples - int(published["count"].sum())
# 残差 > 0 说明确实藏了东西,而藏的格子数 ≥ 2 说明摊不到具体某一个
assert residual > 0
assert int(hidden.sum()) >= 2
def test_feature_dropped_when_complement_impossible(self, two_party):
"""只剩两个箱、其中一个太小时,补也补不出来,整个特征作废。"""
rng = np.random.default_rng(2)
n = 60
x = np.concatenate([rng.uniform(0, 1, n - 2), np.array([9.0, 9.5])])
y = (rng.random(n) < 0.5).astype(int)
frame, v = build(pd.DataFrame({"x": x}), pd.DataFrame({"y": y}))
rep = FeatureBinning(v, strategy="custom", min_bin_size=5).fit(
frame, "alice", ["x"], "bob", "y", custom_cuts={"x": [5.0]}
)
assert bool(rep.table["suppressed"].astype(bool).all())
assert rep.iv["x"] == 0.0
def test_binning_is_audited(self, two_party):
feat, lab = make_credit(n=100)
frame, v = build(feat, lab)
hetero_binning(v, frame, "alice", ["age"], "bob", "y")
events = nax.audit().filter("binning")
assert len(events) == 1
assert events[0].label == nax.Label.RELEASED
assert events[0].detail["features"] == 1
assert "bob" in events[0].peers
def test_laplace_noise_perturbs_counts(self, two_party):
feat, lab = make_credit(n=200, seed=2)
frame, v = build(feat, lab)
clean = FeatureBinning(v, bins=4).fit(frame, "alice", ["age"], "bob", "y")
noisy = FeatureBinning(v, bins=4, laplace_eps=0.5, seed=0).fit(
frame, "alice", ["age"], "bob", "y"
)
a = clean.table["count"].astype(float).values
b = noisy.table["count"].astype(float).values
assert not np.array_equal(a, b) # 确实加上了噪声
assert np.abs(a - b).max() < 30 # 但没离谱到毁掉统计量(ε=0.5 → 尺度 2)
class TestStrategies:
def test_uniform_bins_are_equal_width(self, two_party):
feat = pd.DataFrame({"x": np.linspace(0.0, 100.0, 200)})
lab = pd.DataFrame({"y": ([0, 1] * 100)})
frame, v = build(feat, lab)
rep = FeatureBinning(v, bins=4, strategy="uniform", expose_cuts=True).fit(
frame, "alice", ["x"], "bob", "y"
)
cuts = np.asarray(rep.cuts["x"])
assert len(cuts) == 3
assert np.allclose(np.diff(cuts), 25.0)
def test_quantile_bins_are_balanced(self, two_party):
feat = pd.DataFrame({"x": np.arange(200.0)})
lab = pd.DataFrame({"y": ([0, 1] * 100)})
frame, v = build(feat, lab)
rep = FeatureBinning(v, bins=5).fit(frame, "alice", ["x"], "bob", "y")
assert list(rep.table["count"].astype(int)) == [40] * 5
def test_custom_cuts(self, two_party):
feat = pd.DataFrame({"x": np.arange(100.0)})
lab = pd.DataFrame({"y": ([1, 0] * 50)})
frame, v = build(feat, lab)
rep = FeatureBinning(v, strategy="custom", expose_cuts=True).fit(
frame, "alice", ["x"], "bob", "y", custom_cuts={"x": [30.0, 70.0]}
)
assert rep.cuts["x"] == [30.0, 70.0]
# searchsorted(side="right"):切点值本身落进右边的箱
assert list(rep.table["count"].astype(int)) == [30, 40, 30]
def test_duplicate_quantiles_collapse(self, two_party):
"""取值大量并列时分位点会重合,应自动合并成更少的箱而不是崩溃。"""
feat = pd.DataFrame({"x": np.concatenate([np.zeros(60), np.ones(40)])})
lab = pd.DataFrame({"y": ([0, 1] * 50)})
frame, v = build(feat, lab)
rep = FeatureBinning(v, bins=5).fit(frame, "alice", ["x"], "bob", "y")
assert rep.table.shape[0] < 5
assert int(rep.table["count"].sum()) == 100
def test_no_empty_leading_bin(self, two_party):
"""切点贴在最小值上会造出恒空的箱,必须被丢掉。"""
feat = pd.DataFrame({"x": np.concatenate([np.zeros(90), np.arange(1.0, 11.0)])})
lab = pd.DataFrame({"y": ([0, 1] * 50)})
frame, v = build(feat, lab)
rep = FeatureBinning(v, bins=5, expose_cuts=True).fit(
frame, "alice", ["x"], "bob", "y"
)
assert all(c > 0.0 for c in rep.cuts["x"])
assert (rep.table["count"].fillna(0).astype(int) > 0).all()
assert int(rep.table["count"].fillna(0).astype(int).sum()) == 100
class TestValidation:
def test_rejects_same_site(self, two_party):
feat, lab = make_credit(n=40)
frame, v = build(feat, lab)
with pytest.raises(ProtocolError, match="不需要联邦分箱"):
FeatureBinning(v).fit(frame, "alice", ["age"], "alice", "y")
def test_rejects_unknown_site(self, two_party):
feat, lab = make_credit(n=40)
frame, v = build(feat, lab)
with pytest.raises(ProtocolError, match="不在这张联邦表里"):
FeatureBinning(v).fit(frame, "alice", ["age"], "carol", "y")
def test_rejects_bad_strategy(self, two_party):
_, v = build(*make_credit(n=20))
with pytest.raises(ProtocolError, match="未知分箱策略"):
FeatureBinning(v, strategy="kmeans")
def test_rejects_single_bin(self, two_party):
_, v = build(*make_credit(n=20))
with pytest.raises(ProtocolError, match="箱数至少"):
FeatureBinning(v, bins=1)
def test_rejects_empty_features(self, two_party):
feat, lab = make_credit(n=40)
frame, v = build(feat, lab)
with pytest.raises(ProtocolError, match="至少要指定一个特征"):
FeatureBinning(v).fit(frame, "alice", [], "bob", "y")
def test_rejects_non_binary_label(self, two_party):
feat = pd.DataFrame({"x": np.arange(40.0)})
lab = pd.DataFrame({"y": np.arange(40.0)}) # 连续标签
frame, v = build(feat, lab)
with pytest.raises(Exception, match="0/1 二分类"):
FeatureBinning(v).fit(frame, "alice", ["x"], "bob", "y")
class TestReport:
def test_report_shape(self, two_party):
feat, lab = make_credit(n=120)
frame, v = build(feat, lab)
rep = hetero_binning(v, frame, "alice", ["age", "income"], "bob", "y", bins=4)
assert isinstance(rep, BinReport)
assert set(rep.iv) == {"age", "income"}
assert set(rep.table.columns) >= {
"feature", "bin", "count", "bad", "good", "bad_rate", "woe", "iv", "suppressed"
}
assert repr(rep).startswith("<BinReport")
def test_top_features_orders_by_iv(self, two_party):
feat, lab = make_credit(n=200, seed=4)
frame, v = build(feat, lab)
rep = hetero_binning(v, frame, "alice", ["age", "income"], "bob", "y")
order = rep.top_features(2)
assert order == sorted(rep.iv, key=lambda f: -rep.iv[f])