protectbayes 0.1.0.dev1__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 (49) hide show
  1. protectbayes-0.1.0.dev1/.github/workflows/docs.yaml +45 -0
  2. protectbayes-0.1.0.dev1/.github/workflows/publish.yaml +36 -0
  3. protectbayes-0.1.0.dev1/.github/workflows/tests.yaml +39 -0
  4. protectbayes-0.1.0.dev1/.gitignore +10 -0
  5. protectbayes-0.1.0.dev1/AGENTS.md +9 -0
  6. protectbayes-0.1.0.dev1/CITATION.cff +45 -0
  7. protectbayes-0.1.0.dev1/CONTRIBUTING.md +16 -0
  8. protectbayes-0.1.0.dev1/LICENSE +21 -0
  9. protectbayes-0.1.0.dev1/PKG-INFO +189 -0
  10. protectbayes-0.1.0.dev1/README.md +154 -0
  11. protectbayes-0.1.0.dev1/codemeta.json +52 -0
  12. protectbayes-0.1.0.dev1/docs/api.md +111 -0
  13. protectbayes-0.1.0.dev1/docs/figures/coefficients.svg +1925 -0
  14. protectbayes-0.1.0.dev1/docs/figures/diagnostics.svg +2142 -0
  15. protectbayes-0.1.0.dev1/docs/figures/prediction.svg +1958 -0
  16. protectbayes-0.1.0.dev1/docs/figures/trace.svg +3338 -0
  17. protectbayes-0.1.0.dev1/docs/mathematics.md +258 -0
  18. protectbayes-0.1.0.dev1/docs/migration.md +44 -0
  19. protectbayes-0.1.0.dev1/docs/release-status.md +28 -0
  20. protectbayes-0.1.0.dev1/docs/validation.md +42 -0
  21. protectbayes-0.1.0.dev1/docs/visualizations.md +80 -0
  22. protectbayes-0.1.0.dev1/llms.txt +54 -0
  23. protectbayes-0.1.0.dev1/pyproject.toml +55 -0
  24. protectbayes-0.1.0.dev1/src/protectbayes/__init__.py +18 -0
  25. protectbayes-0.1.0.dev1/src/protectbayes/_glm.py +155 -0
  26. protectbayes-0.1.0.dev1/src/protectbayes/core.py +775 -0
  27. protectbayes-0.1.0.dev1/src/protectbayes/cv.py +172 -0
  28. protectbayes-0.1.0.dev1/src/protectbayes/plotting.py +294 -0
  29. protectbayes-0.1.0.dev1/tests/test_core.py +157 -0
  30. protectbayes-0.1.0.dev1/tests/test_glm_observations.py +226 -0
  31. protectbayes-0.1.0.dev1/tests/test_mathematics.py +101 -0
  32. protectbayes-0.1.0.dev1/tests/test_plotting.py +112 -0
  33. protectbayes-0.1.0.dev1/tools/build_docs.py +97 -0
  34. protectbayes-0.1.0.dev1/tools/build_gallery.py +79 -0
  35. protectbayes-0.1.0.dev1/validation/extended-parity-comparison.csv +13 -0
  36. protectbayes-0.1.0.dev1/validation/extended-parity-data.csv +41 -0
  37. protectbayes-0.1.0.dev1/validation/extended-parity-r.csv +13 -0
  38. protectbayes-0.1.0.dev1/validation/extended_parity.R +23 -0
  39. protectbayes-0.1.0.dev1/validation/extended_parity.py +61 -0
  40. protectbayes-0.1.0.dev1/validation/parity-comparison.csv +35 -0
  41. protectbayes-0.1.0.dev1/validation/parity-data.csv +51 -0
  42. protectbayes-0.1.0.dev1/validation/parity-log.txt +7 -0
  43. protectbayes-0.1.0.dev1/validation/parity-python.csv +35 -0
  44. protectbayes-0.1.0.dev1/validation/parity-r.csv +35 -0
  45. protectbayes-0.1.0.dev1/validation/parity.R +15 -0
  46. protectbayes-0.1.0.dev1/validation/parity.py +54 -0
  47. protectbayes-0.1.0.dev1/validation/python-tests-current.txt +2 -0
  48. protectbayes-0.1.0.dev1/validation/python-tests-legacy.txt +2 -0
  49. protectbayes-0.1.0.dev1/validation/requirements-validation.txt +61 -0
@@ -0,0 +1,45 @@
1
+ name: Documentation
2
+ on:
3
+ push:
4
+ branches: [main]
5
+ pull_request:
6
+ workflow_dispatch:
7
+ permissions:
8
+ contents: read
9
+ concurrency:
10
+ group: pages-${{ github.ref }}
11
+ cancel-in-progress: true
12
+ jobs:
13
+ build:
14
+ permissions:
15
+ contents: read
16
+ pages: read
17
+ runs-on: ubuntu-latest
18
+ steps:
19
+ - uses: actions/checkout@v4
20
+ - uses: actions/setup-python@v5
21
+ with:
22
+ python-version: '3.12'
23
+ - uses: r-lib/actions/setup-pandoc@v2
24
+ - run: python -m pip install markdown==3.11.4
25
+ - run: python tools/build_docs.py
26
+ - uses: actions/configure-pages@v5
27
+ if: github.event_name != 'pull_request'
28
+ - uses: actions/upload-pages-artifact@v3
29
+ if: github.event_name != 'pull_request'
30
+ with:
31
+ path: _site
32
+ deploy:
33
+ permissions:
34
+ pages: write
35
+ id-token: write
36
+ if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
37
+ environment:
38
+ name: github-pages
39
+ url: ${{ steps.deployment.outputs.page_url }}
40
+ runs-on: ubuntu-latest
41
+ needs: build
42
+ steps:
43
+ - name: Deploy
44
+ id: deployment
45
+ uses: actions/deploy-pages@v4
@@ -0,0 +1,36 @@
1
+ name: Publish to PyPI
2
+ on:
3
+ workflow_dispatch:
4
+ permissions:
5
+ contents: read
6
+ jobs:
7
+ build:
8
+ runs-on: ubuntu-latest
9
+ steps:
10
+ - uses: actions/checkout@v4
11
+ - uses: actions/setup-python@v5
12
+ with:
13
+ python-version: '3.12'
14
+ - run: python -m pip install -e '.[dev]'
15
+ - run: ruff check .
16
+ - run: pytest
17
+ - run: python -m build
18
+ - run: python -m twine check dist/*
19
+ - uses: actions/upload-artifact@v4
20
+ with:
21
+ name: python-distributions
22
+ path: dist/
23
+ publish:
24
+ needs: build
25
+ runs-on: ubuntu-latest
26
+ environment:
27
+ name: pypi
28
+ url: https://pypi.org/project/protectbayes/
29
+ permissions:
30
+ id-token: write
31
+ steps:
32
+ - uses: actions/download-artifact@v4
33
+ with:
34
+ name: python-distributions
35
+ path: dist/
36
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,39 @@
1
+ name: Tests
2
+ on:
3
+ push:
4
+ branches: [main]
5
+ pull_request:
6
+ workflow_dispatch:
7
+ permissions:
8
+ contents: read
9
+ jobs:
10
+ tests:
11
+ runs-on: ${{ matrix.os }}
12
+ strategy:
13
+ fail-fast: false
14
+ matrix:
15
+ include:
16
+ - {os: ubuntu-latest, python: '3.10'}
17
+ - {os: ubuntu-latest, python: '3.12'}
18
+ - {os: ubuntu-latest, python: '3.14'}
19
+ - {os: windows-latest, python: '3.12'}
20
+ - {os: macos-latest, python: '3.13'}
21
+ steps:
22
+ - uses: actions/checkout@v4
23
+ - uses: actions/setup-python@v5
24
+ with:
25
+ python-version: ${{ matrix.python }}
26
+ - run: python -m pip install -e '.[dev]'
27
+ - run: ruff check .
28
+ - run: pytest
29
+ - run: python -m build
30
+ - run: python -m twine check dist/*
31
+ legacy-arviz:
32
+ runs-on: ubuntu-latest
33
+ steps:
34
+ - uses: actions/checkout@v4
35
+ - uses: actions/setup-python@v5
36
+ with:
37
+ python-version: '3.12'
38
+ - run: python -m pip install -e '.[dev]' 'arviz==0.22.0'
39
+ - run: pytest
@@ -0,0 +1,10 @@
1
+ __pycache__/
2
+ *.pyc
3
+ *.egg-info/
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ .venv/
7
+ dist/
8
+ build/
9
+ _site/
10
+ .DS_Store
@@ -0,0 +1,9 @@
1
+ # protectbayes Python development contract
2
+
3
+ Read docs/mathematics.md. Keep the private predecessor review out of published
4
+ materials. BPL and BPEN's Lasso limit
5
+ are distinct models. Protect by exact names, preserve RNG isolation and chain
6
+ axes, and do not advertise unsupported likelihoods or exact variable selection.
7
+ Use independent posterior/conditional-moment tests and cross-language moment
8
+ comparisons for statistical changes. Preserve authors, both citations, licensing
9
+ and honest limitations. Run pytest, ruff, build and twine check before release.
@@ -0,0 +1,45 @@
1
+ cff-version: 1.2.0
2
+ message: Please cite both accompanying articles when using BPL and BPEN.
3
+ type: software
4
+ title: 'protectbayes: Bayesian Partially Protected Regression for Python'
5
+ version: 0.1.0
6
+ license: MIT
7
+ repository-code: https://github.com/selimyaman/protectbayes-python
8
+ url: https://selimyaman.github.io/protectbayes-python/
9
+ authors: &id004
10
+ - &id002
11
+ family-names: Yaman
12
+ given-names: Selim
13
+ orcid: https://orcid.org/0000-0003-4723-5512
14
+ - &id001
15
+ family-names: Atalan
16
+ given-names: Yasir
17
+ orcid: https://orcid.org/0009-0003-9219-4833
18
+ - &id003
19
+ family-names: Gill
20
+ given-names: Jeff
21
+ orcid: https://orcid.org/0000-0002-8592-8996
22
+ preferred-citation:
23
+ type: article
24
+ title: Bayesian partially-protected regularization as a model selection tool
25
+ authors:
26
+ - *id001
27
+ - *id002
28
+ - *id003
29
+ journal: Journal of Applied Statistics
30
+ year: 2026
31
+ volume: 53
32
+ issue: 7
33
+ start: 1316
34
+ end: 1341
35
+ doi: 10.1080/02664763.2025.2559025
36
+ references:
37
+ - type: article
38
+ title: 'Bridging prediction and theory: Introducing the Bayesian Partially-Protected
39
+ Lasso'
40
+ authors: *id004
41
+ journal: Electoral Studies
42
+ year: 2024
43
+ volume: 87
44
+ start: 102730
45
+ doi: 10.1016/j.electstud.2023.102730
@@ -0,0 +1,16 @@
1
+ # Contributing
2
+
3
+ Read docs/mathematics.md before changing samplers. Keep the joint density,
4
+ conditional updates, R implementation and documentation consistent. Mathematical
5
+ changes need independent posterior integration or analytic moment tests, not
6
+ only implementation snapshots. Run pytest, ruff, build and twine check.
7
+
8
+ Preserve all three developers, both article citations and MIT licensing. Never
9
+ install dependencies during imports/tests, access the network at fit time, or
10
+ change the caller's global RNG. Retain original-scale coefficients and training
11
+ preprocessing. Report exact package versions and seeds with reproducible bugs.
12
+
13
+ Build the documentation with `python -m pip install markdown==3.11.4`,
14
+ Pandoc, and `python tools/build_docs.py`. This generates native MathML,
15
+ so the published formulas do not need a browser-side script. Regenerate
16
+ the gallery with `python tools/build_gallery.py` after installing `.[plot]`.
@@ -0,0 +1,21 @@
1
+ # MIT License
2
+
3
+ Copyright (c) 2026 Selim Yaman, Yasir Atalan and Jeff Gill
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,189 @@
1
+ Metadata-Version: 2.5
2
+ Name: protectbayes
3
+ Version: 0.1.0.dev1
4
+ Summary: Bayesian partially protected Lasso and elastic net regression for Gaussian, Bernoulli and Poisson outcomes
5
+ Project-URL: Homepage, https://github.com/selimyaman/protectbayes-python
6
+ Project-URL: Documentation, https://selimyaman.github.io/protectbayes-python/
7
+ Project-URL: Repository, https://github.com/selimyaman/protectbayes-python
8
+ Project-URL: Issues, https://github.com/selimyaman/protectbayes-python/issues
9
+ Project-URL: R implementation, https://github.com/selimyaman/protectBayes
10
+ Author-email: Selim Yaman <selimyaman26@gmail.com>, Yasir Atalan <ayasiratalan@gmail.com>, Jeff Gill <jgill@american.edu>
11
+ Maintainer-email: Selim Yaman <selimyaman26@gmail.com>
12
+ License-Expression: MIT
13
+ License-File: LICENSE
14
+ Keywords: BPEN,BPL,Bayesian,MCMC,elastic net,lasso,protected regularization
15
+ Classifier: Development Status :: 3 - Alpha
16
+ Classifier: Intended Audience :: Science/Research
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: arviz>=0.17
23
+ Requires-Dist: numpy>=1.24
24
+ Requires-Dist: pandas>=1.5
25
+ Requires-Dist: scipy>=1.10
26
+ Provides-Extra: dev
27
+ Requires-Dist: build>=1; extra == 'dev'
28
+ Requires-Dist: matplotlib>=3.6; extra == 'dev'
29
+ Requires-Dist: pytest>=8; extra == 'dev'
30
+ Requires-Dist: ruff>=0.9; extra == 'dev'
31
+ Requires-Dist: twine>=6; extra == 'dev'
32
+ Provides-Extra: plot
33
+ Requires-Dist: matplotlib>=3.6; extra == 'plot'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # protectbayes for Python
37
+
38
+ **Bayesian partially protected Lasso and elastic net regression.**
39
+ Supports Gaussian, Bernoulli-logistic and Poisson-log likelihoods.
40
+
41
+ A Python implementation of the explicitly specified models in
42
+ [protectBayes for R](https://github.com/selimyaman/protectBayes), the improved
43
+ second version of [protectR](https://github.com/selimyaman/protectR), by
44
+ **Selim Yaman, Yasir Atalan and Jeff Gill**.
45
+
46
+ [![Tests](https://github.com/selimyaman/protectbayes-python/actions/workflows/tests.yaml/badge.svg)](https://github.com/selimyaman/protectbayes-python/actions/workflows/tests.yaml)
47
+ [Documentation](https://selimyaman.github.io/protectbayes-python/) ·
48
+ [Visualizations](https://selimyaman.github.io/protectbayes-python/docs/visualizations.html) ·
49
+ [Mathematics](https://selimyaman.github.io/protectbayes-python/docs/mathematics.html) · [Validation](https://selimyaman.github.io/protectbayes-python/docs/validation.html)
50
+
51
+ ## Install
52
+
53
+ Until PyPI publication is confirmed, install from GitHub:
54
+
55
+ ```sh
56
+ python -m pip install "git+https://github.com/selimyaman/protectbayes-python.git"
57
+ ```
58
+
59
+ See [release status](https://selimyaman.github.io/protectbayes-python/docs/release-status.html) for verified distribution status.
60
+
61
+ ## Fit and predict
62
+
63
+ ```python
64
+ import numpy as np
65
+ from protectbayes import protect_lasso, protect_elastic_net
66
+
67
+ rng = np.random.default_rng(41)
68
+ X = rng.normal(size=(120, 3))
69
+ y = 3 + 1.5 * X[:, 0] - 0.5 * X[:, 1] + rng.normal(size=120)
70
+ names = ["theory", "exploratory", "noise"]
71
+
72
+ bpl = protect_lasso(X[:90], y[:90], feature_names=names, protected=["theory"], seed=123)
73
+ bpen = protect_elastic_net(
74
+ X[:90], y[:90], feature_names=names, protected=["theory"], lasso=1, ridge=0.5, seed=123
75
+ )
76
+ print(bpen.summary())
77
+ print(bpen.diagnostics())
78
+ print(bpen.predict(X[90:], interval="prediction"))
79
+ print(np.mean((y[90:] - bpen.predict(X[90:])) ** 2))
80
+ bpen.save("fit.npz")
81
+ ```
82
+
83
+ For counts where each row has a known amount of exposure:
84
+
85
+ ```python
86
+ exposure = rng.uniform(0.5, 3, size=len(X))
87
+ events = rng.poisson(exposure * np.exp(0.2 + 0.4 * X[:, 0]))
88
+ poisson_fit = protect_lasso(
89
+ X[:90], events[:90], family="poisson",
90
+ feature_names=names, protected=["theory"], offset=np.log(exposure[:90]),
91
+ )
92
+ expected_counts = poisson_fit.predict(X[90:], offset=np.log(exposure[90:]))
93
+ ```
94
+
95
+ Use `family="binomial"` for numeric 0/1 outcomes, and `missing="drop"`
96
+ only to opt into complete-case fitting. The [API guide](https://selimyaman.github.io/protectbayes-python/docs/api.html)
97
+ documents weights, missing rows, and prediction shapes.
98
+
99
+ Use `load_fit("fit.npz")` to restore the complete fit without pickle.
100
+ `posterior_epred()` returns mean-response draws; `posterior_predict()` draws
101
+ new observations from the fitted likelihood. `log_lik()` returns observation
102
+ log likelihoods; `to_arviz()` exposes draws for further diagnostics.
103
+
104
+ `beta` has axes **draw, chain, coefficient**; `sigma` has axes draw, chain
105
+ for Gaussian fits and is absent for discrete likelihoods.
106
+ Coefficient names include the intercept when present. `coef_` contains
107
+ posterior means in the original predictor units on the link scale. Predictions accept numeric matrices
108
+ in training-column order, or numeric pandas DataFrames aligned by column name.
109
+ Categorical columns must be explicitly encoded; the Python API does not yet
110
+ provide R's formula/contrast interface. Save and reuse the training encoding.
111
+
112
+ ## Visualizations
113
+
114
+ `bpen.plot(type="intervals")` separates protected and exploratory terms without
115
+ using a zero-crossing interval as a variable-selection rule.
116
+ `bpen.plot(type="prediction")` separates uncertainty in the mean from the
117
+ variation expected in a new observation. Install the optional plotting
118
+ dependency with
119
+ `python -m pip install "protectbayes[plot] @ git+https://github.com/selimyaman/protectbayes-python.git"`.
120
+
121
+ [![Posterior coefficient intervals from a simulated protected Lasso fit](docs/figures/coefficients.svg)](https://selimyaman.github.io/protectbayes-python/docs/visualizations.html#coefficients)
122
+
123
+ [![Predictive uncertainty from a simulated protected elastic net fit](docs/figures/prediction.svg)](https://selimyaman.github.io/protectbayes-python/docs/visualizations.html#prediction)
124
+
125
+ [See the visualization gallery](https://selimyaman.github.io/protectbayes-python/docs/visualizations.html)
126
+ for examples, source code and convergence diagnostics. For a task-to-method
127
+ quick reference, see the [agent guide](https://selimyaman.github.io/protectbayes-python/llms.txt)
128
+ or its [GitHub mirror](https://github.com/selimyaman/protectbayes-python/blob/main/llms.txt).
129
+
130
+ ## Statistical contract
131
+
132
+ * Gaussian BPL uses residual-scaled normal/exponential mixtures; discrete BPL uses the corresponding link-scale priors. Protected coefficients
133
+ retain a fixed local shrinkage prior and are excluded from learning the
134
+ global Lasso penalty.
135
+ * BPEN uses a fixed normal-Laplace prior for exploratory slopes and a weak
136
+ normal prior for protected slopes. `lasso` is an L1 **rate**, so larger means
137
+ stronger shrinkage. It equals the reciprocal of the paper's Appendix 2
138
+ Laplace scale. `ridge` is L2 precision.
139
+ * BPEN `ridge=0` and `lasso=0` give its Lasso and ridge limits. Its Lasso limit
140
+ differs from the hierarchical residual-scaled BPL model.
141
+ * Default `variance_prior=(2,1)` is inverse-gamma shape/scale with mean variance
142
+ 1 in response units. Choose a scientifically suitable scale; it is not
143
+ universally weak.
144
+ * Protection never guarantees statistical significance, causality, exact
145
+ sparsity or better prediction.
146
+ * Explicit offsets act on the linear predictor. Gaussian weights are relative
147
+ observation precision; discrete weights are positive integer frequencies,
148
+ not complex-survey weights. Missing training values are rejected unless
149
+ complete-case fitting is explicitly requested.
150
+
151
+ `cv_protect()` tunes fixed BPEN penalties with training-fold scaling and held-out
152
+ MSE for Gaussian forecasts or negative log posterior predictive density for
153
+ discrete forecasts. Pass group-aware `fold_id` for clustered data. Selection
154
+ scores are optimistic after tuning; use an untouched test set or nested CV.
155
+
156
+ ## Reliability
157
+
158
+ Gaussian Gibbs conditionals use Cholesky or auxiliary draws. Discrete
159
+ likelihoods use coordinate-wise slice sampling and conditional Gibbs updates.
160
+ Both use independent NumPy generators, rank-normalized ArviZ diagnostics and
161
+ safe NPZ persistence.
162
+ See the mathematical derivation and executed validation rather than treating
163
+ software output as proof of inferential validity. Check R-hat, bulk/tail ESS,
164
+ MCSE, traces and prior sensitivity. R/Python equivalence is distributional,
165
+ not identical random streams. Dense designs and stored posterior draws limit
166
+ very large datasets.
167
+
168
+ ## Required scholarly citation
169
+
170
+ Please cite the articles in work using these methods; cite both for BPL and BPEN:
171
+
172
+ 1. Yaman, S., Atalan, Y., & Gill, J. (2024). Bridging prediction and theory:
173
+ Introducing the Bayesian Partially-Protected Lasso. *Electoral Studies*,
174
+ 87, 102730. [doi:10.1016/j.electstud.2023.102730](https://doi.org/10.1016/j.electstud.2023.102730).
175
+ 2. Atalan, Y., Yaman, S., & Gill, J. (2026). Bayesian partially-protected
176
+ regularization as a model selection tool. *Journal of Applied Statistics*,
177
+ 53(7), 1316–1341. [doi:10.1080/02664763.2025.2559025](https://doi.org/10.1080/02664763.2025.2559025).
178
+
179
+ Machine-readable citations are in `CITATION.cff` and `codemeta.json`.
180
+ Scholarly citation is requested separately from the MIT software license.
181
+
182
+ ## Development and AI assistance
183
+
184
+ This implementation was prepared with AI assistance in Codex. The maintainer
185
+ requested the acknowledgement **“GPT-6.2 Astra, extra high.”** All three developers
186
+ retain attribution; AI assistance is not authorship or independent peer review.
187
+
188
+ Run `python -m pip install -e '.[dev]'`, `pytest`, `ruff check .`,
189
+ `python -m build` and `twine check dist/*`. See [contributing](https://selimyaman.github.io/protectbayes-python/CONTRIBUTING.html).
@@ -0,0 +1,154 @@
1
+ # protectbayes for Python
2
+
3
+ **Bayesian partially protected Lasso and elastic net regression.**
4
+ Supports Gaussian, Bernoulli-logistic and Poisson-log likelihoods.
5
+
6
+ A Python implementation of the explicitly specified models in
7
+ [protectBayes for R](https://github.com/selimyaman/protectBayes), the improved
8
+ second version of [protectR](https://github.com/selimyaman/protectR), by
9
+ **Selim Yaman, Yasir Atalan and Jeff Gill**.
10
+
11
+ [![Tests](https://github.com/selimyaman/protectbayes-python/actions/workflows/tests.yaml/badge.svg)](https://github.com/selimyaman/protectbayes-python/actions/workflows/tests.yaml)
12
+ [Documentation](https://selimyaman.github.io/protectbayes-python/) ·
13
+ [Visualizations](https://selimyaman.github.io/protectbayes-python/docs/visualizations.html) ·
14
+ [Mathematics](https://selimyaman.github.io/protectbayes-python/docs/mathematics.html) · [Validation](https://selimyaman.github.io/protectbayes-python/docs/validation.html)
15
+
16
+ ## Install
17
+
18
+ Until PyPI publication is confirmed, install from GitHub:
19
+
20
+ ```sh
21
+ python -m pip install "git+https://github.com/selimyaman/protectbayes-python.git"
22
+ ```
23
+
24
+ See [release status](https://selimyaman.github.io/protectbayes-python/docs/release-status.html) for verified distribution status.
25
+
26
+ ## Fit and predict
27
+
28
+ ```python
29
+ import numpy as np
30
+ from protectbayes import protect_lasso, protect_elastic_net
31
+
32
+ rng = np.random.default_rng(41)
33
+ X = rng.normal(size=(120, 3))
34
+ y = 3 + 1.5 * X[:, 0] - 0.5 * X[:, 1] + rng.normal(size=120)
35
+ names = ["theory", "exploratory", "noise"]
36
+
37
+ bpl = protect_lasso(X[:90], y[:90], feature_names=names, protected=["theory"], seed=123)
38
+ bpen = protect_elastic_net(
39
+ X[:90], y[:90], feature_names=names, protected=["theory"], lasso=1, ridge=0.5, seed=123
40
+ )
41
+ print(bpen.summary())
42
+ print(bpen.diagnostics())
43
+ print(bpen.predict(X[90:], interval="prediction"))
44
+ print(np.mean((y[90:] - bpen.predict(X[90:])) ** 2))
45
+ bpen.save("fit.npz")
46
+ ```
47
+
48
+ For counts where each row has a known amount of exposure:
49
+
50
+ ```python
51
+ exposure = rng.uniform(0.5, 3, size=len(X))
52
+ events = rng.poisson(exposure * np.exp(0.2 + 0.4 * X[:, 0]))
53
+ poisson_fit = protect_lasso(
54
+ X[:90], events[:90], family="poisson",
55
+ feature_names=names, protected=["theory"], offset=np.log(exposure[:90]),
56
+ )
57
+ expected_counts = poisson_fit.predict(X[90:], offset=np.log(exposure[90:]))
58
+ ```
59
+
60
+ Use `family="binomial"` for numeric 0/1 outcomes, and `missing="drop"`
61
+ only to opt into complete-case fitting. The [API guide](https://selimyaman.github.io/protectbayes-python/docs/api.html)
62
+ documents weights, missing rows, and prediction shapes.
63
+
64
+ Use `load_fit("fit.npz")` to restore the complete fit without pickle.
65
+ `posterior_epred()` returns mean-response draws; `posterior_predict()` draws
66
+ new observations from the fitted likelihood. `log_lik()` returns observation
67
+ log likelihoods; `to_arviz()` exposes draws for further diagnostics.
68
+
69
+ `beta` has axes **draw, chain, coefficient**; `sigma` has axes draw, chain
70
+ for Gaussian fits and is absent for discrete likelihoods.
71
+ Coefficient names include the intercept when present. `coef_` contains
72
+ posterior means in the original predictor units on the link scale. Predictions accept numeric matrices
73
+ in training-column order, or numeric pandas DataFrames aligned by column name.
74
+ Categorical columns must be explicitly encoded; the Python API does not yet
75
+ provide R's formula/contrast interface. Save and reuse the training encoding.
76
+
77
+ ## Visualizations
78
+
79
+ `bpen.plot(type="intervals")` separates protected and exploratory terms without
80
+ using a zero-crossing interval as a variable-selection rule.
81
+ `bpen.plot(type="prediction")` separates uncertainty in the mean from the
82
+ variation expected in a new observation. Install the optional plotting
83
+ dependency with
84
+ `python -m pip install "protectbayes[plot] @ git+https://github.com/selimyaman/protectbayes-python.git"`.
85
+
86
+ [![Posterior coefficient intervals from a simulated protected Lasso fit](docs/figures/coefficients.svg)](https://selimyaman.github.io/protectbayes-python/docs/visualizations.html#coefficients)
87
+
88
+ [![Predictive uncertainty from a simulated protected elastic net fit](docs/figures/prediction.svg)](https://selimyaman.github.io/protectbayes-python/docs/visualizations.html#prediction)
89
+
90
+ [See the visualization gallery](https://selimyaman.github.io/protectbayes-python/docs/visualizations.html)
91
+ for examples, source code and convergence diagnostics. For a task-to-method
92
+ quick reference, see the [agent guide](https://selimyaman.github.io/protectbayes-python/llms.txt)
93
+ or its [GitHub mirror](https://github.com/selimyaman/protectbayes-python/blob/main/llms.txt).
94
+
95
+ ## Statistical contract
96
+
97
+ * Gaussian BPL uses residual-scaled normal/exponential mixtures; discrete BPL uses the corresponding link-scale priors. Protected coefficients
98
+ retain a fixed local shrinkage prior and are excluded from learning the
99
+ global Lasso penalty.
100
+ * BPEN uses a fixed normal-Laplace prior for exploratory slopes and a weak
101
+ normal prior for protected slopes. `lasso` is an L1 **rate**, so larger means
102
+ stronger shrinkage. It equals the reciprocal of the paper's Appendix 2
103
+ Laplace scale. `ridge` is L2 precision.
104
+ * BPEN `ridge=0` and `lasso=0` give its Lasso and ridge limits. Its Lasso limit
105
+ differs from the hierarchical residual-scaled BPL model.
106
+ * Default `variance_prior=(2,1)` is inverse-gamma shape/scale with mean variance
107
+ 1 in response units. Choose a scientifically suitable scale; it is not
108
+ universally weak.
109
+ * Protection never guarantees statistical significance, causality, exact
110
+ sparsity or better prediction.
111
+ * Explicit offsets act on the linear predictor. Gaussian weights are relative
112
+ observation precision; discrete weights are positive integer frequencies,
113
+ not complex-survey weights. Missing training values are rejected unless
114
+ complete-case fitting is explicitly requested.
115
+
116
+ `cv_protect()` tunes fixed BPEN penalties with training-fold scaling and held-out
117
+ MSE for Gaussian forecasts or negative log posterior predictive density for
118
+ discrete forecasts. Pass group-aware `fold_id` for clustered data. Selection
119
+ scores are optimistic after tuning; use an untouched test set or nested CV.
120
+
121
+ ## Reliability
122
+
123
+ Gaussian Gibbs conditionals use Cholesky or auxiliary draws. Discrete
124
+ likelihoods use coordinate-wise slice sampling and conditional Gibbs updates.
125
+ Both use independent NumPy generators, rank-normalized ArviZ diagnostics and
126
+ safe NPZ persistence.
127
+ See the mathematical derivation and executed validation rather than treating
128
+ software output as proof of inferential validity. Check R-hat, bulk/tail ESS,
129
+ MCSE, traces and prior sensitivity. R/Python equivalence is distributional,
130
+ not identical random streams. Dense designs and stored posterior draws limit
131
+ very large datasets.
132
+
133
+ ## Required scholarly citation
134
+
135
+ Please cite the articles in work using these methods; cite both for BPL and BPEN:
136
+
137
+ 1. Yaman, S., Atalan, Y., & Gill, J. (2024). Bridging prediction and theory:
138
+ Introducing the Bayesian Partially-Protected Lasso. *Electoral Studies*,
139
+ 87, 102730. [doi:10.1016/j.electstud.2023.102730](https://doi.org/10.1016/j.electstud.2023.102730).
140
+ 2. Atalan, Y., Yaman, S., & Gill, J. (2026). Bayesian partially-protected
141
+ regularization as a model selection tool. *Journal of Applied Statistics*,
142
+ 53(7), 1316–1341. [doi:10.1080/02664763.2025.2559025](https://doi.org/10.1080/02664763.2025.2559025).
143
+
144
+ Machine-readable citations are in `CITATION.cff` and `codemeta.json`.
145
+ Scholarly citation is requested separately from the MIT software license.
146
+
147
+ ## Development and AI assistance
148
+
149
+ This implementation was prepared with AI assistance in Codex. The maintainer
150
+ requested the acknowledgement **“GPT-6.2 Astra, extra high.”** All three developers
151
+ retain attribution; AI assistance is not authorship or independent peer review.
152
+
153
+ Run `python -m pip install -e '.[dev]'`, `pytest`, `ruff check .`,
154
+ `python -m build` and `twine check dist/*`. See [contributing](https://selimyaman.github.io/protectbayes-python/CONTRIBUTING.html).
@@ -0,0 +1,52 @@
1
+ {
2
+ "@context": "https://doi.org/10.5063/schema/codemeta-2.0",
3
+ "@type": "SoftwareSourceCode",
4
+ "name": "protectbayes",
5
+ "version": "0.1.0.dev1",
6
+ "description": "Gaussian Bayesian partially protected Lasso and elastic net regression with posterior prediction and diagnostics.",
7
+ "license": "https://spdx.org/licenses/MIT",
8
+ "codeRepository": "https://github.com/selimyaman/protectbayes-python",
9
+ "url": "https://selimyaman.github.io/protectbayes-python/",
10
+ "programmingLanguage": "Python",
11
+ "runtimePlatform": "Python >= 3.10",
12
+ "keywords": [
13
+ "Bayesian regression",
14
+ "partially protected lasso",
15
+ "elastic net",
16
+ "BPL",
17
+ "BPEN",
18
+ "MCMC",
19
+ "theory-driven regularization"
20
+ ],
21
+ "author": [
22
+ {
23
+ "@type": "Person",
24
+ "givenName": "Selim",
25
+ "familyName": "Yaman",
26
+ "@id": "https://orcid.org/0000-0003-4723-5512"
27
+ },
28
+ {
29
+ "@type": "Person",
30
+ "givenName": "Yasir",
31
+ "familyName": "Atalan",
32
+ "@id": "https://orcid.org/0009-0003-9219-4833"
33
+ },
34
+ {
35
+ "@type": "Person",
36
+ "givenName": "Jeff",
37
+ "familyName": "Gill",
38
+ "@id": "https://orcid.org/0000-0002-8592-8996"
39
+ }
40
+ ],
41
+ "citation": [
42
+ "https://doi.org/10.1016/j.electstud.2023.102730",
43
+ "https://doi.org/10.1080/02664763.2025.2559025"
44
+ ],
45
+ "softwareRequirements": [
46
+ "Python >= 3.10",
47
+ "NumPy >= 1.24",
48
+ "SciPy >= 1.10",
49
+ "ArviZ >= 0.17",
50
+ "pandas >= 1.5"
51
+ ]
52
+ }