rejectkit 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. rejectkit-0.3.0/.github/workflows/ci.yml +28 -0
  2. rejectkit-0.3.0/.gitignore +28 -0
  3. rejectkit-0.3.0/CHANGELOG.md +39 -0
  4. rejectkit-0.3.0/LICENSE +21 -0
  5. rejectkit-0.3.0/PKG-INFO +219 -0
  6. rejectkit-0.3.0/PUBLISHING.md +66 -0
  7. rejectkit-0.3.0/README.md +178 -0
  8. rejectkit-0.3.0/docs/api.md +27 -0
  9. rejectkit-0.3.0/docs/benchmark.md +41 -0
  10. rejectkit-0.3.0/docs/diagnostics.md +23 -0
  11. rejectkit-0.3.0/docs/explainer.md +91 -0
  12. rejectkit-0.3.0/docs/index.md +32 -0
  13. rejectkit-0.3.0/docs/methods.md +36 -0
  14. rejectkit-0.3.0/examples/plots/benchmark.png +0 -0
  15. rejectkit-0.3.0/examples/plots/ks_curve.png +0 -0
  16. rejectkit-0.3.0/examples/plots/score_distributions.png +0 -0
  17. rejectkit-0.3.0/examples/quickstart.py +56 -0
  18. rejectkit-0.3.0/examples/real_data_home_credit.ipynb +927 -0
  19. rejectkit-0.3.0/examples/walkthrough.ipynb +1076 -0
  20. rejectkit-0.3.0/examples/walkthrough.py +152 -0
  21. rejectkit-0.3.0/mkdocs.yml +21 -0
  22. rejectkit-0.3.0/pyproject.toml +73 -0
  23. rejectkit-0.3.0/src/rejectkit/__init__.py +47 -0
  24. rejectkit-0.3.0/src/rejectkit/_compat.py +19 -0
  25. rejectkit-0.3.0/src/rejectkit/base.py +94 -0
  26. rejectkit-0.3.0/src/rejectkit/benchmark.py +141 -0
  27. rejectkit-0.3.0/src/rejectkit/datasets.py +97 -0
  28. rejectkit-0.3.0/src/rejectkit/diagnostics.py +109 -0
  29. rejectkit-0.3.0/src/rejectkit/estimator.py +105 -0
  30. rejectkit-0.3.0/src/rejectkit/methods/__init__.py +20 -0
  31. rejectkit-0.3.0/src/rejectkit/methods/augmentation.py +69 -0
  32. rejectkit-0.3.0/src/rejectkit/methods/extrapolation.py +47 -0
  33. rejectkit-0.3.0/src/rejectkit/methods/heckman.py +98 -0
  34. rejectkit-0.3.0/src/rejectkit/methods/parcelling.py +87 -0
  35. rejectkit-0.3.0/src/rejectkit/methods/reclassification.py +45 -0
  36. rejectkit-0.3.0/src/rejectkit/methods/reweighting.py +47 -0
  37. rejectkit-0.3.0/src/rejectkit/methods/semi_supervised.py +64 -0
  38. rejectkit-0.3.0/src/rejectkit/plotting.py +75 -0
  39. rejectkit-0.3.0/tests/test_benchmark.py +40 -0
  40. rejectkit-0.3.0/tests/test_diagnostics.py +48 -0
  41. rejectkit-0.3.0/tests/test_estimator.py +49 -0
  42. rejectkit-0.3.0/tests/test_heckman.py +29 -0
  43. rejectkit-0.3.0/tests/test_methods.py +87 -0
  44. rejectkit-0.3.0/tests/test_plotting.py +25 -0
  45. rejectkit-0.3.0/tests/test_polars.py +26 -0
@@ -0,0 +1,28 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ jobs:
9
+ test:
10
+ runs-on: ubuntu-latest
11
+ strategy:
12
+ fail-fast: false
13
+ matrix:
14
+ python-version: ["3.9", "3.10", "3.11", "3.12"]
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - name: Set up Python ${{ matrix.python-version }}
18
+ uses: actions/setup-python@v5
19
+ with:
20
+ python-version: ${{ matrix.python-version }}
21
+ - name: Install
22
+ run: |
23
+ python -m pip install --upgrade pip
24
+ pip install -e ".[dev]"
25
+ - name: Lint
26
+ run: ruff check .
27
+ - name: Test
28
+ run: pytest -q
@@ -0,0 +1,28 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ *.egg
6
+ build/
7
+ dist/
8
+ .eggs/
9
+
10
+ # Test / tooling caches
11
+ .pytest_cache/
12
+ .ruff_cache/
13
+ .mypy_cache/
14
+ .coverage
15
+ htmlcov/
16
+
17
+ # Virtual environments
18
+ .venv/
19
+ venv/
20
+ env/
21
+
22
+ # Notebooks
23
+ .ipynb_checkpoints/
24
+
25
+ # OS / editor
26
+ .DS_Store
27
+ .idea/
28
+ .vscode/
@@ -0,0 +1,39 @@
1
+ # Changelog
2
+
3
+ The format follows [Keep a Changelog](https://keepachangelog.com/) and the
4
+ project adheres to [Semantic Versioning](https://semver.org/).
5
+
6
+ ## [0.3.0] - 2026-06-27
7
+
8
+ ### Added
9
+ - `SelfLearning` — semi-supervised self-training reject inference.
10
+ - `HeckmanClassifier` — two-step control-function correction (inverse Mills ratio).
11
+ - **Polars** support: all public entry points accept pandas, polars, or numpy.
12
+ - `rejectkit.plotting` — `plot_benchmark`, `plot_score_distributions`, `plot_ks`
13
+ (optional, `pip install rejectkit[plot]`).
14
+ - `diagnostics.feature_drift` (per-feature accept-vs-reject PSI) and
15
+ `diagnostics.swap_set` (swap-set analysis between two scorecards).
16
+ - `MaskedRejectBenchmark` gains `selection="cutoff"` (realistic PD-cutoff policy)
17
+ and can benchmark `"heckman"` alongside the resampling methods.
18
+ - Documentation site (`mkdocs` + Material).
19
+
20
+ ### Changed
21
+ - `auc_recovery` now reports `NaN` when the oracle does not clearly beat the
22
+ naive model, instead of an unstable ratio around a near-zero denominator.
23
+
24
+ ## [0.2.0] - 2026-06-27
25
+
26
+ ### Added
27
+ - `Reclassification` — iterative relabel-and-refit reject inference.
28
+ - `Extrapolation` (alias `twins`) — nearest-neighbour label extrapolation.
29
+
30
+ ## [0.1.0] - 2026-06-26
31
+
32
+ ### Added
33
+ - `BaseRejectInferencer` and the scikit-learn-style `fit` / `resample` /
34
+ `fit_resample` API.
35
+ - Methods: `SimpleAugmentation`, `FuzzyAugmentation`, `Parcelling`, `Reweighting`.
36
+ - `RejectInferenceClassifier` — wrap any classifier with reject inference.
37
+ - `MaskedRejectBenchmark` — measure whether reject inference helps on your data.
38
+ - Metrics: `auc`, `gini`, `ks_statistic`, `psi`.
39
+ - Synthetic data generators `make_credit_data`, `make_accept_reject`.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Han
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,219 @@
1
+ Metadata-Version: 2.4
2
+ Name: rejectkit
3
+ Version: 0.3.0
4
+ Summary: Reject inference for credit scoring — 8 scikit-learn-compatible methods plus an honest benchmark that tells you whether it actually helps.
5
+ Project-URL: Homepage, https://github.com/HangilKim11/rejectkit
6
+ Project-URL: Repository, https://github.com/HangilKim11/rejectkit
7
+ Project-URL: Issues, https://github.com/HangilKim11/rejectkit/issues
8
+ Author-email: Han <kim.hangil.ds@gmail.com>
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: credit-scoring,machine-learning,reject-inference,risk,sample-selection-bias,scikit-learn,scorecard
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Financial and Insurance Industry
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Requires-Python: >=3.9
23
+ Requires-Dist: numpy>=1.21
24
+ Requires-Dist: pandas>=1.3
25
+ Requires-Dist: scikit-learn>=1.0
26
+ Provides-Extra: dev
27
+ Requires-Dist: matplotlib>=3.4; extra == 'dev'
28
+ Requires-Dist: mkdocs-material>=9.0; extra == 'dev'
29
+ Requires-Dist: mkdocs>=1.5; extra == 'dev'
30
+ Requires-Dist: polars>=0.20; extra == 'dev'
31
+ Requires-Dist: pytest>=7; extra == 'dev'
32
+ Requires-Dist: ruff>=0.1; extra == 'dev'
33
+ Provides-Extra: docs
34
+ Requires-Dist: mkdocs-material>=9.0; extra == 'docs'
35
+ Requires-Dist: mkdocs>=1.5; extra == 'docs'
36
+ Provides-Extra: plot
37
+ Requires-Dist: matplotlib>=3.4; extra == 'plot'
38
+ Provides-Extra: polars
39
+ Requires-Dist: polars>=0.20; extra == 'polars'
40
+ Description-Content-Type: text/markdown
41
+
42
+ # rejectkit
43
+
44
+ **Reject inference for credit scoring — scikit-learn-compatible methods, plus an honest benchmark that tells you whether reject inference actually helps on your data.**
45
+
46
+ ![python](https://img.shields.io/badge/python-3.9%2B-blue)
47
+ ![license](https://img.shields.io/badge/license-MIT-green)
48
+ ![status](https://img.shields.io/badge/status-beta-orange)
49
+
50
+ <details>
51
+ <summary><b>한국어 요약 (Korean)</b></summary>
52
+
53
+ <br>
54
+
55
+ 신용 모델은 **승인된 신청자**(나중에 good/bad 결과를 아는 사람)로만 학습하지만, 실제로는 **거절자를 포함한 전체 신청자**를 평가해야 한다 — 이 표본 선택 편향을 바로잡는 기법이 **reject inference**다. `rejectkit`은 이 고전 기법 8가지를 scikit-learn 스타일의 한 API로 묶고, **"그 보정이 내 데이터에서 실제로 도움이 되는지"** 재는 벤치마크(`MaskedRejectBenchmark`)까지 제공한다. 입력은 pandas·polars·numpy 모두 지원. 자세한 한·영·일 설명은 [docs/explainer.md](docs/explainer.md), 실데이터 예제는 [examples/real_data_home_credit.ipynb](examples/real_data_home_credit.ipynb) 참고.
56
+
57
+ </details>
58
+
59
+ <details>
60
+ <summary><b>日本語要約 (Japanese)</b></summary>
61
+
62
+ <br>
63
+
64
+ 与信モデルは**承認された申込者**(後で good/bad の結果が分かる人)だけで学習するが、実際には**否認者を含む全申込者**を評価しなければならない — この標本選択バイアスを補正する手法が **reject inference**。`rejectkit` はこの古典的手法8種を scikit-learn 風の単一 API にまとめ、**「その補正が自分のデータで実際に役立つか」**を測るベンチマーク(`MaskedRejectBenchmark`)まで備える。入力は pandas・polars・numpy に対応。詳しい3言語解説は [docs/explainer.md](docs/explainer.md)、実データ例は [examples/real_data_home_credit.ipynb](examples/real_data_home_credit.ipynb) を参照。
65
+
66
+ </details>
67
+
68
+ ---
69
+
70
+ ## Why this exists
71
+
72
+ A credit model is trained on **accepted** applicants, whose good/bad outcome you eventually observe. But the model has to score the **whole** through-the-door population — including the applicants you **rejected**, who never get an outcome. Training on accepts only is a textbook case of sample-selection bias. *Reject inference* is the family of techniques that tries to correct it.
73
+
74
+ These methods are standard in the credit-risk world, yet the Python tooling is missing:
75
+
76
+ - **R** has [`scoringTools`](https://github.com/adimajo/scoringTools) (`augmentation`, `fuzzy_augmentation`, `parcelling`, `reclassification`, `twins`) — GitHub only.
77
+ - **Python** scorecard libraries — `scorecardpy`, `optbinning`, `scorecardbundle` — do WOE/IV binning and logistic scorecards but **skip reject inference entirely**.
78
+ - What's left online is one-off research code, not a packaged, tested library.
79
+
80
+ `rejectkit` fills that gap: eight reject inference methods behind one scikit-learn-style API, a benchmark harness even `scoringTools` lacks, plus drift diagnostics and plotting.
81
+
82
+ ## Install
83
+
84
+ ```bash
85
+ pip install -e . # core: numpy, pandas, scikit-learn
86
+ pip install -e ".[plot]" # + matplotlib plotting helpers
87
+ pip install -e ".[polars]" # + polars input support
88
+ ```
89
+
90
+ ## Quickstart
91
+
92
+ ```python
93
+ from sklearn.linear_model import LogisticRegression
94
+ from rejectkit import RejectInferenceClassifier
95
+
96
+ # X_accept, y_accept: accepted applicants and their good(0)/bad(1) outcomes
97
+ # X_reject: rejected applicants — features only, no labels
98
+ clf = RejectInferenceClassifier(
99
+ estimator=LogisticRegression(max_iter=1000),
100
+ method="parcelling",
101
+ method_params={"uplift": 1.3}, # assume rejects are ~30% worse per score band
102
+ )
103
+ clf.fit(X_accept, y_accept, X_reject)
104
+ pd_bad = clf.predict_proba(X_new)[:, 1]
105
+ ```
106
+
107
+ Just want the augmented training sample for your own pipeline?
108
+
109
+ ```python
110
+ from rejectkit import FuzzyAugmentation
111
+
112
+ X_aug, y_aug, sample_weight = (
113
+ FuzzyAugmentation(LogisticRegression(max_iter=1000))
114
+ .fit_resample(X_accept, y_accept, X_reject)
115
+ )
116
+ ```
117
+
118
+ Inputs may be **pandas, polars, or numpy**.
119
+
120
+ ## Methods
121
+
122
+ | Method | Class | Core idea | Assumption |
123
+ |---|---|---|---|
124
+ | Simple augmentation | `SimpleAugmentation` | Hard 0/1 label by score cutoff | Accept model ranks rejects |
125
+ | Fuzzy augmentation | `FuzzyAugmentation` | Two weighted rows per reject (P(bad), P(good)) | MAR; smooth labels |
126
+ | Parcelling | `Parcelling` | Per-score-band bad rate × `uplift` | Rejects worse by a fixed factor |
127
+ | Reclassification | `Reclassification` | Iteratively relabel & refit | Labels converge |
128
+ | Extrapolation / twins | `Extrapolation` | Local bad rate of nearest accepts | Similar applicants behave alike |
129
+ | Inverse-propensity reweighting | `Reweighting` | Reweight accepts by `1/P(accept)` | MAR; invents no labels |
130
+ | Self-training | `SelfLearning` | Pseudo-label only confident rejects | MAR; confident labels reliable |
131
+ | Heckman control function | `HeckmanClassifier` | Add inverse Mills ratio as a feature | Gaussian selection latent |
132
+
133
+ All resamplers share `fit(X_accept, y_accept, X_reject)` → `resample()` returning `(X, y, sample_weight)`. `HeckmanClassifier` augments the feature space, so it is a standalone classifier rather than a resampler.
134
+
135
+ ## Does reject inference actually help? Measure it.
136
+
137
+ You can never validate reject inference directly, because rejects have no outcome — the literature is genuinely split on whether it helps at all. `MaskedRejectBenchmark` settles the question **on your own data**: it hides the labels of a synthetically "rejected" subset of a labelled dataset and checks how well each method recovers a model close to the *oracle* (trained on the full population) versus the *naive* accepts-only baseline.
138
+
139
+ ```python
140
+ from rejectkit import MaskedRejectBenchmark
141
+ from rejectkit.datasets import make_credit_data
142
+
143
+ X, y = make_credit_data(n_samples=4000, random_state=0)
144
+ bench = MaskedRejectBenchmark(selection="mnar", accept_rate=0.6, random_state=0)
145
+ print(bench.compare(
146
+ ["fuzzy", "parcelling", "reweighting", "extrapolation", "selflearning", "heckman"],
147
+ X, y,
148
+ ).round(4))
149
+ ```
150
+
151
+ ```
152
+ auc ks gini auc_recovery
153
+ oracle 0.8203 0.4911 0.6406 1.0000
154
+ naive 0.7488 0.3651 0.4975 0.0000
155
+ fuzzy 0.7488 0.3663 0.4977 0.0010
156
+ parcelling 0.7404 0.3468 0.4809 -0.1161
157
+ reweighting 0.7249 0.3290 0.4498 -0.3334
158
+ extrapolation 0.6989 0.2889 0.3977 -0.6973
159
+ selflearning 0.7124 0.3093 0.4248 -0.5080
160
+ heckman 0.7457 0.3559 0.4914 -0.0424
161
+ ```
162
+
163
+ `auc_recovery`: `0` = no better than the naive accepts-only model, `1` = matches the full-data oracle.
164
+
165
+ Read this honestly. Selection here is **MNAR** (acceptance depends on the hidden outcome), so naive is badly biased (0.749 vs the 0.820 oracle) — yet the augmentation methods barely move it and several *hurt*; only Heckman nearly holds the naive line. That is what theory predicts when selection depends on the outcome: **reject inference is not a free lunch.** Switch to `selection="mar"` or `selection="cutoff"` and the verdict often flips the other way — frequently the naive model is *already* at the oracle, so `auc_recovery` returns `NaN` (no gap to recover) and reject inference is simply unnecessary. The harness exists so you find out *before* you ship it.
166
+
167
+ Selection mechanisms: `"mar"` (features only), `"mnar"` (features + hidden outcome), `"cutoff"` (accept the lowest-PD fraction — a realistic credit policy).
168
+
169
+ ## Diagnostics & plotting
170
+
171
+ ```python
172
+ from rejectkit.diagnostics import feature_drift, swap_set, psi
173
+ feature_drift(X_accept, X_reject) # per-feature accept-vs-reject PSI, worst first
174
+ swap_set(y, score_old, score_new, c_old, c_new) # who a new scorecard swaps in/out
175
+
176
+ from rejectkit import plotting # needs [plot]
177
+ plotting.plot_benchmark(results)
178
+ plotting.plot_score_distributions(score_accept, score_reject)
179
+ plotting.plot_ks(y_true, y_score)
180
+ ```
181
+
182
+ ## Caveats
183
+
184
+ - Augmentation methods infer reject labels from a model fitted on the (biased) accepts, so they cannot escape strong **MNAR** selection on their own.
185
+ - Reject inference often affects **calibration** more than **ranking** (AUC). Evaluate the metric you care about.
186
+ - Always benchmark before adopting. `rejectkit` makes that one function call.
187
+
188
+ ## Documentation
189
+
190
+ Build the docs site locally:
191
+
192
+ ```bash
193
+ pip install -e ".[docs]"
194
+ mkdocs serve
195
+ ```
196
+
197
+ ## Examples
198
+
199
+ - `examples/quickstart.py` — 60-second tour (single model + benchmark).
200
+ - `examples/walkthrough.ipynb` — every function on sample data (trilingual KO/EN/JA, executed).
201
+ - `examples/real_data_home_credit.ipynb` — **applied to the real Kaggle Home Credit dataset**: under MNAR selection the naive model collapses (AUC 0.74 → 0.57) and reject inference recovers ~7–8% of the gap; under MAR/cutoff it is unnecessary (trilingual, executed).
202
+
203
+ ## Roadmap
204
+
205
+ - **v0.1** — core augmentation/parcelling/reweighting, `RejectInferenceClassifier`, benchmark. ✅
206
+ - **v0.2** — reclassification, extrapolation / twins. ✅
207
+ - **v0.3** — self-training, Heckman, polars, plotting, drift diagnostics, docs. ✅
208
+ - **Next** — calibration-focused benchmark metrics, deep generative reject inference (optional extra), PyPI release.
209
+
210
+ ## References
211
+
212
+ - Hand & Henley (1993), *Can reject inference ever work?*
213
+ - Crook & Banasik (2004), *Does reject inference really improve the performance of application scoring models?*
214
+ - Lopes, *Should we "reject" Reject Inference? An empirical study.*
215
+ - `scoringTools` (R): https://github.com/adimajo/scoringTools
216
+
217
+ ## License
218
+
219
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,66 @@
1
+ # Publishing rejectkit to PyPI
2
+
3
+ Once published, anyone can `pip install rejectkit`. The package name `rejectkit`
4
+ was free on PyPI at the time of writing.
5
+
6
+ ## 0. One-time setup
7
+ - Create a PyPI account: https://pypi.org/account/register/
8
+ - Create an API token (Account settings → API tokens). It looks like `pypi-AgE…`.
9
+ - Install the tooling:
10
+
11
+ ```bash
12
+ pip install build twine
13
+ ```
14
+
15
+ ## 1. Before each release
16
+ - Fill in the real values in `pyproject.toml` (`authors`, `[project.urls]`) and
17
+ `LICENSE` (copyright holder).
18
+ - Bump `version` in `pyproject.toml` (e.g. `0.3.0` → `0.3.1`) and add a
19
+ `CHANGELOG.md` entry. **PyPI will not let you re-upload an existing version.**
20
+ - (Optional) Remove the hard-coded data path in
21
+ `examples/real_data_home_credit.ipynb` before publishing.
22
+
23
+ ## 2. Build the distributions
24
+
25
+ ```bash
26
+ rm -rf dist build
27
+ python -m build # creates dist/*.whl and dist/*.tar.gz
28
+ python -m twine check dist/* # must say PASSED
29
+ ```
30
+
31
+ ## 3. (Recommended) Test on TestPyPI first
32
+
33
+ ```bash
34
+ python -m twine upload --repository testpypi dist/*
35
+ # then, in a fresh virtualenv:
36
+ pip install -i https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ rejectkit
37
+ ```
38
+
39
+ ## 4. Publish to the real PyPI
40
+
41
+ ```bash
42
+ python -m twine upload dist/*
43
+ # username: __token__
44
+ # password: your pypi-… API token
45
+ ```
46
+
47
+ Or non-interactively:
48
+
49
+ ```bash
50
+ TWINE_USERNAME=__token__ TWINE_PASSWORD=pypi-XXXX python -m twine upload dist/*
51
+ ```
52
+
53
+ ## 5. Verify
54
+
55
+ ```bash
56
+ pip install rejectkit
57
+ python -c "import rejectkit; print(rejectkit.__version__)"
58
+ ```
59
+
60
+ ## Notes
61
+ - The wheel ships **only the `rejectkit` package code** (verified). Example data
62
+ (Home Credit, etc.) is **not** included — users bring their own; the synthetic
63
+ `rejectkit.datasets.make_credit_data` is bundled so they can try it immediately.
64
+ - Optional extras install with `pip install "rejectkit[plot]"`, `"[polars]"`, `"[docs]"`, `"[dev]"`.
65
+ - Publishing a version to PyPI is effectively permanent; you can *yank* a bad
66
+ release but not silently replace it. Get the metadata right first.
@@ -0,0 +1,178 @@
1
+ # rejectkit
2
+
3
+ **Reject inference for credit scoring — scikit-learn-compatible methods, plus an honest benchmark that tells you whether reject inference actually helps on your data.**
4
+
5
+ ![python](https://img.shields.io/badge/python-3.9%2B-blue)
6
+ ![license](https://img.shields.io/badge/license-MIT-green)
7
+ ![status](https://img.shields.io/badge/status-beta-orange)
8
+
9
+ <details>
10
+ <summary><b>한국어 요약 (Korean)</b></summary>
11
+
12
+ <br>
13
+
14
+ 신용 모델은 **승인된 신청자**(나중에 good/bad 결과를 아는 사람)로만 학습하지만, 실제로는 **거절자를 포함한 전체 신청자**를 평가해야 한다 — 이 표본 선택 편향을 바로잡는 기법이 **reject inference**다. `rejectkit`은 이 고전 기법 8가지를 scikit-learn 스타일의 한 API로 묶고, **"그 보정이 내 데이터에서 실제로 도움이 되는지"** 재는 벤치마크(`MaskedRejectBenchmark`)까지 제공한다. 입력은 pandas·polars·numpy 모두 지원. 자세한 한·영·일 설명은 [docs/explainer.md](docs/explainer.md), 실데이터 예제는 [examples/real_data_home_credit.ipynb](examples/real_data_home_credit.ipynb) 참고.
15
+
16
+ </details>
17
+
18
+ <details>
19
+ <summary><b>日本語要約 (Japanese)</b></summary>
20
+
21
+ <br>
22
+
23
+ 与信モデルは**承認された申込者**(後で good/bad の結果が分かる人)だけで学習するが、実際には**否認者を含む全申込者**を評価しなければならない — この標本選択バイアスを補正する手法が **reject inference**。`rejectkit` はこの古典的手法8種を scikit-learn 風の単一 API にまとめ、**「その補正が自分のデータで実際に役立つか」**を測るベンチマーク(`MaskedRejectBenchmark`)まで備える。入力は pandas・polars・numpy に対応。詳しい3言語解説は [docs/explainer.md](docs/explainer.md)、実データ例は [examples/real_data_home_credit.ipynb](examples/real_data_home_credit.ipynb) を参照。
24
+
25
+ </details>
26
+
27
+ ---
28
+
29
+ ## Why this exists
30
+
31
+ A credit model is trained on **accepted** applicants, whose good/bad outcome you eventually observe. But the model has to score the **whole** through-the-door population — including the applicants you **rejected**, who never get an outcome. Training on accepts only is a textbook case of sample-selection bias. *Reject inference* is the family of techniques that tries to correct it.
32
+
33
+ These methods are standard in the credit-risk world, yet the Python tooling is missing:
34
+
35
+ - **R** has [`scoringTools`](https://github.com/adimajo/scoringTools) (`augmentation`, `fuzzy_augmentation`, `parcelling`, `reclassification`, `twins`) — GitHub only.
36
+ - **Python** scorecard libraries — `scorecardpy`, `optbinning`, `scorecardbundle` — do WOE/IV binning and logistic scorecards but **skip reject inference entirely**.
37
+ - What's left online is one-off research code, not a packaged, tested library.
38
+
39
+ `rejectkit` fills that gap: eight reject inference methods behind one scikit-learn-style API, a benchmark harness even `scoringTools` lacks, plus drift diagnostics and plotting.
40
+
41
+ ## Install
42
+
43
+ ```bash
44
+ pip install -e . # core: numpy, pandas, scikit-learn
45
+ pip install -e ".[plot]" # + matplotlib plotting helpers
46
+ pip install -e ".[polars]" # + polars input support
47
+ ```
48
+
49
+ ## Quickstart
50
+
51
+ ```python
52
+ from sklearn.linear_model import LogisticRegression
53
+ from rejectkit import RejectInferenceClassifier
54
+
55
+ # X_accept, y_accept: accepted applicants and their good(0)/bad(1) outcomes
56
+ # X_reject: rejected applicants — features only, no labels
57
+ clf = RejectInferenceClassifier(
58
+ estimator=LogisticRegression(max_iter=1000),
59
+ method="parcelling",
60
+ method_params={"uplift": 1.3}, # assume rejects are ~30% worse per score band
61
+ )
62
+ clf.fit(X_accept, y_accept, X_reject)
63
+ pd_bad = clf.predict_proba(X_new)[:, 1]
64
+ ```
65
+
66
+ Just want the augmented training sample for your own pipeline?
67
+
68
+ ```python
69
+ from rejectkit import FuzzyAugmentation
70
+
71
+ X_aug, y_aug, sample_weight = (
72
+ FuzzyAugmentation(LogisticRegression(max_iter=1000))
73
+ .fit_resample(X_accept, y_accept, X_reject)
74
+ )
75
+ ```
76
+
77
+ Inputs may be **pandas, polars, or numpy**.
78
+
79
+ ## Methods
80
+
81
+ | Method | Class | Core idea | Assumption |
82
+ |---|---|---|---|
83
+ | Simple augmentation | `SimpleAugmentation` | Hard 0/1 label by score cutoff | Accept model ranks rejects |
84
+ | Fuzzy augmentation | `FuzzyAugmentation` | Two weighted rows per reject (P(bad), P(good)) | MAR; smooth labels |
85
+ | Parcelling | `Parcelling` | Per-score-band bad rate × `uplift` | Rejects worse by a fixed factor |
86
+ | Reclassification | `Reclassification` | Iteratively relabel & refit | Labels converge |
87
+ | Extrapolation / twins | `Extrapolation` | Local bad rate of nearest accepts | Similar applicants behave alike |
88
+ | Inverse-propensity reweighting | `Reweighting` | Reweight accepts by `1/P(accept)` | MAR; invents no labels |
89
+ | Self-training | `SelfLearning` | Pseudo-label only confident rejects | MAR; confident labels reliable |
90
+ | Heckman control function | `HeckmanClassifier` | Add inverse Mills ratio as a feature | Gaussian selection latent |
91
+
92
+ All resamplers share `fit(X_accept, y_accept, X_reject)` → `resample()` returning `(X, y, sample_weight)`. `HeckmanClassifier` augments the feature space, so it is a standalone classifier rather than a resampler.
93
+
94
+ ## Does reject inference actually help? Measure it.
95
+
96
+ You can never validate reject inference directly, because rejects have no outcome — the literature is genuinely split on whether it helps at all. `MaskedRejectBenchmark` settles the question **on your own data**: it hides the labels of a synthetically "rejected" subset of a labelled dataset and checks how well each method recovers a model close to the *oracle* (trained on the full population) versus the *naive* accepts-only baseline.
97
+
98
+ ```python
99
+ from rejectkit import MaskedRejectBenchmark
100
+ from rejectkit.datasets import make_credit_data
101
+
102
+ X, y = make_credit_data(n_samples=4000, random_state=0)
103
+ bench = MaskedRejectBenchmark(selection="mnar", accept_rate=0.6, random_state=0)
104
+ print(bench.compare(
105
+ ["fuzzy", "parcelling", "reweighting", "extrapolation", "selflearning", "heckman"],
106
+ X, y,
107
+ ).round(4))
108
+ ```
109
+
110
+ ```
111
+ auc ks gini auc_recovery
112
+ oracle 0.8203 0.4911 0.6406 1.0000
113
+ naive 0.7488 0.3651 0.4975 0.0000
114
+ fuzzy 0.7488 0.3663 0.4977 0.0010
115
+ parcelling 0.7404 0.3468 0.4809 -0.1161
116
+ reweighting 0.7249 0.3290 0.4498 -0.3334
117
+ extrapolation 0.6989 0.2889 0.3977 -0.6973
118
+ selflearning 0.7124 0.3093 0.4248 -0.5080
119
+ heckman 0.7457 0.3559 0.4914 -0.0424
120
+ ```
121
+
122
+ `auc_recovery`: `0` = no better than the naive accepts-only model, `1` = matches the full-data oracle.
123
+
124
+ Read this honestly. Selection here is **MNAR** (acceptance depends on the hidden outcome), so naive is badly biased (0.749 vs the 0.820 oracle) — yet the augmentation methods barely move it and several *hurt*; only Heckman nearly holds the naive line. That is what theory predicts when selection depends on the outcome: **reject inference is not a free lunch.** Switch to `selection="mar"` or `selection="cutoff"` and the verdict often flips the other way — frequently the naive model is *already* at the oracle, so `auc_recovery` returns `NaN` (no gap to recover) and reject inference is simply unnecessary. The harness exists so you find out *before* you ship it.
125
+
126
+ Selection mechanisms: `"mar"` (features only), `"mnar"` (features + hidden outcome), `"cutoff"` (accept the lowest-PD fraction — a realistic credit policy).
127
+
128
+ ## Diagnostics & plotting
129
+
130
+ ```python
131
+ from rejectkit.diagnostics import feature_drift, swap_set, psi
132
+ feature_drift(X_accept, X_reject) # per-feature accept-vs-reject PSI, worst first
133
+ swap_set(y, score_old, score_new, c_old, c_new) # who a new scorecard swaps in/out
134
+
135
+ from rejectkit import plotting # needs [plot]
136
+ plotting.plot_benchmark(results)
137
+ plotting.plot_score_distributions(score_accept, score_reject)
138
+ plotting.plot_ks(y_true, y_score)
139
+ ```
140
+
141
+ ## Caveats
142
+
143
+ - Augmentation methods infer reject labels from a model fitted on the (biased) accepts, so they cannot escape strong **MNAR** selection on their own.
144
+ - Reject inference often affects **calibration** more than **ranking** (AUC). Evaluate the metric you care about.
145
+ - Always benchmark before adopting. `rejectkit` makes that one function call.
146
+
147
+ ## Documentation
148
+
149
+ Build the docs site locally:
150
+
151
+ ```bash
152
+ pip install -e ".[docs]"
153
+ mkdocs serve
154
+ ```
155
+
156
+ ## Examples
157
+
158
+ - `examples/quickstart.py` — 60-second tour (single model + benchmark).
159
+ - `examples/walkthrough.ipynb` — every function on sample data (trilingual KO/EN/JA, executed).
160
+ - `examples/real_data_home_credit.ipynb` — **applied to the real Kaggle Home Credit dataset**: under MNAR selection the naive model collapses (AUC 0.74 → 0.57) and reject inference recovers ~7–8% of the gap; under MAR/cutoff it is unnecessary (trilingual, executed).
161
+
162
+ ## Roadmap
163
+
164
+ - **v0.1** — core augmentation/parcelling/reweighting, `RejectInferenceClassifier`, benchmark. ✅
165
+ - **v0.2** — reclassification, extrapolation / twins. ✅
166
+ - **v0.3** — self-training, Heckman, polars, plotting, drift diagnostics, docs. ✅
167
+ - **Next** — calibration-focused benchmark metrics, deep generative reject inference (optional extra), PyPI release.
168
+
169
+ ## References
170
+
171
+ - Hand & Henley (1993), *Can reject inference ever work?*
172
+ - Crook & Banasik (2004), *Does reject inference really improve the performance of application scoring models?*
173
+ - Lopes, *Should we "reject" Reject Inference? An empirical study.*
174
+ - `scoringTools` (R): https://github.com/adimajo/scoringTools
175
+
176
+ ## License
177
+
178
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,27 @@
1
+ # API reference
2
+
3
+ ## Estimators
4
+
5
+ - **`RejectInferenceClassifier(estimator=None, method="fuzzy", base_scorer=None, method_params=None)`**
6
+ Wrap any classifier with reject inference. `fit(X_accept, y_accept, X_reject)`, then `predict` / `predict_proba`.
7
+ - **`HeckmanClassifier(selection_estimator=None, outcome_estimator=None)`**
8
+ Two-step control-function correction. `fit(X_accept, y_accept, X_reject)`, then `predict_proba`.
9
+ - **`get_inferencer(method, base_estimator=None, **params)`** — factory for the resampler classes.
10
+
11
+ ## Reject inference methods (resamplers)
12
+
13
+ All subclass `BaseRejectInferencer` and expose `fit`, `resample`, `fit_resample`:
14
+
15
+ `SimpleAugmentation`, `FuzzyAugmentation`, `Parcelling`, `Reclassification`,
16
+ `Extrapolation`, `Reweighting`, `SelfLearning`.
17
+
18
+ ## Benchmark
19
+
20
+ - **`MaskedRejectBenchmark(selection="mnar", accept_rate=0.6, test_size=0.3, selection_strength=2.0, random_state=0)`**
21
+ `.compare(methods, X, y, estimator=None, method_params=None) -> DataFrame`.
22
+
23
+ ## Data & diagnostics
24
+
25
+ - `datasets.make_credit_data(...)`, `datasets.make_accept_reject(...)`
26
+ - `diagnostics.auc / gini / ks_statistic / psi / feature_drift / swap_set`
27
+ - `plotting.plot_benchmark / plot_score_distributions / plot_ks`
@@ -0,0 +1,41 @@
1
+ # Benchmark
2
+
3
+ You can never validate reject inference directly, because rejects have no outcome. `MaskedRejectBenchmark` settles the question **on your own data**: it takes a fully labelled dataset, hides the labels of a synthetically "rejected" subset, and measures how well each method recovers a model close to the *oracle* (trained on the full population) versus the *naive* accepts-only baseline.
4
+
5
+ ```python
6
+ from rejectkit import MaskedRejectBenchmark
7
+ from rejectkit.datasets import make_credit_data
8
+
9
+ X, y = make_credit_data(n_samples=4000, random_state=0)
10
+ bench = MaskedRejectBenchmark(selection="cutoff", accept_rate=0.6, random_state=0)
11
+ print(bench.compare(
12
+ ["simple", "fuzzy", "parcelling", "reweighting",
13
+ "reclassification", "extrapolation", "selflearning", "heckman"],
14
+ X, y,
15
+ ).round(4))
16
+ ```
17
+
18
+ `auc_recovery`: `0` = no better than the naive accepts-only model, `1` = matches the full-data oracle.
19
+
20
+ ## Selection mechanisms
21
+
22
+ | `selection` | Acceptance depends on | Use it to model |
23
+ |---|---|---|
24
+ | `"mar"` | observed features only | missing-at-random selection |
25
+ | `"mnar"` | features **and** the hidden outcome | the hard case; naive is most biased |
26
+ | `"cutoff"` | predicted PD (accept lowest-risk fraction) | a realistic credit policy cutoff |
27
+
28
+ ## How the accept/reject split is simulated
29
+
30
+ Real labelled data has an outcome for every row, so the harness *creates* rejects:
31
+
32
+ 1. Score each applicant: `acceptance = f(features) (+ outcome term under MNAR) + noise`.
33
+ 2. Accept the top `accept_rate` fraction; reject the rest.
34
+ 3. Hide the rejected rows' labels (the *"Masked"* in the name).
35
+ 4. Train each model on accepts (+ inferred rejects) and score it against the **held-out, fully-labelled** test set.
36
+
37
+ The rejects are therefore not real declined applicants but labelled rows whose outcome was deliberately hidden — the only way to *measure* recovery, since genuine rejects have no outcome to check against.
38
+
39
+ ## Reading the result honestly
40
+
41
+ Reject inference is **not** a free lunch. Under pure **MNAR** selection, augmentation methods inherit the accept model's bias and often fail to beat naive — exactly what theory predicts. Under **MAR** and **cutoff** selection, methods such as parcelling and extrapolation can recover a meaningful share of the oracle gap. The point of the harness is to let you discover which regime you are in *before* shipping reject inference on faith.