bensemble 0.2.2__tar.gz → 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.
- {bensemble-0.2.2 → bensemble-0.3.0}/PKG-INFO +80 -64
- bensemble-0.3.0/README.md +231 -0
- {bensemble-0.2.2 → bensemble-0.3.0}/bensemble/__init__.py +2 -2
- bensemble-0.3.0/bensemble/calibration/scaling.py +162 -0
- bensemble-0.3.0/bensemble/core/ensemble.py +109 -0
- {bensemble-0.2.2 → bensemble-0.3.0}/bensemble/core/member.py +38 -20
- {bensemble-0.2.2 → bensemble-0.3.0}/bensemble/core/types.py +8 -4
- bensemble-0.3.0/bensemble/diversity/__init__.py +3 -0
- bensemble-0.3.0/bensemble/diversity/dropout.py +28 -0
- bensemble-0.3.0/bensemble/layers/__init__.py +4 -0
- {bensemble-0.2.2 → bensemble-0.3.0}/bensemble/layers/base.py +2 -1
- bensemble-0.3.0/bensemble/layers/conv.py +135 -0
- {bensemble-0.2.2 → bensemble-0.3.0}/bensemble/layers/linear.py +18 -14
- bensemble-0.3.0/bensemble/losses.py +189 -0
- {bensemble-0.2.2 → bensemble-0.3.0}/bensemble/methods/__init__.py +0 -1
- {bensemble-0.2.2 → bensemble-0.3.0}/bensemble/methods/laplace_approximation.py +212 -64
- {bensemble-0.2.2 → bensemble-0.3.0}/bensemble/methods/probabilistic_backpropagation.py +76 -28
- {bensemble-0.2.2 → bensemble-0.3.0}/bensemble/metrics.py +10 -5
- {bensemble-0.2.2 → bensemble-0.3.0}/bensemble/search/bayesian.py +29 -21
- {bensemble-0.2.2 → bensemble-0.3.0}/bensemble/search/nes.py +12 -14
- bensemble-0.3.0/bensemble/search/selection.py +140 -0
- {bensemble-0.2.2 → bensemble-0.3.0}/bensemble/search/space.py +1 -1
- bensemble-0.3.0/bensemble/uncertainty/__init__.py +6 -0
- {bensemble-0.2.2 → bensemble-0.3.0}/bensemble/uncertainty/decomposition.py +15 -9
- bensemble-0.3.0/bensemble/utils.py +273 -0
- {bensemble-0.2.2 → bensemble-0.3.0}/bensemble.egg-info/PKG-INFO +80 -64
- {bensemble-0.2.2 → bensemble-0.3.0}/bensemble.egg-info/SOURCES.txt +5 -1
- {bensemble-0.2.2 → bensemble-0.3.0}/bensemble.egg-info/requires.txt +9 -0
- {bensemble-0.2.2 → bensemble-0.3.0}/pyproject.toml +12 -3
- bensemble-0.3.0/tests/test_examples.py +104 -0
- bensemble-0.3.0/tests/test_losses.py +166 -0
- bensemble-0.3.0/tests/test_renyi_loss.py +225 -0
- {bensemble-0.2.2 → bensemble-0.3.0}/tests/test_utils.py +4 -2
- bensemble-0.3.0/tests/test_weight_sampling.py +204 -0
- bensemble-0.2.2/README.md +0 -223
- bensemble-0.2.2/bensemble/calibration/scaling.py +0 -126
- bensemble-0.2.2/bensemble/core/ensemble.py +0 -57
- bensemble-0.2.2/bensemble/diversity/dropout.py +0 -13
- bensemble-0.2.2/bensemble/layers/__init__.py +0 -3
- bensemble-0.2.2/bensemble/layers/conv.py +0 -102
- bensemble-0.2.2/bensemble/losses.py +0 -81
- bensemble-0.2.2/bensemble/search/selection.py +0 -128
- bensemble-0.2.2/bensemble/uncertainty/__init__.py +0 -0
- bensemble-0.2.2/bensemble/utils.py +0 -98
- bensemble-0.2.2/tests/test_losses.py +0 -81
- {bensemble-0.2.2 → bensemble-0.3.0}/LICENSE +0 -0
- {bensemble-0.2.2 → bensemble-0.3.0}/bensemble/calibration/__init__.py +0 -0
- {bensemble-0.2.2 → bensemble-0.3.0}/bensemble/core/__init__.py +0 -0
- {bensemble-0.2.2 → bensemble-0.3.0}/bensemble/search/__init__.py +5 -5
- {bensemble-0.2.2 → bensemble-0.3.0}/bensemble.egg-info/dependency_links.txt +0 -0
- {bensemble-0.2.2 → bensemble-0.3.0}/bensemble.egg-info/top_level.txt +0 -0
- {bensemble-0.2.2 → bensemble-0.3.0}/setup.cfg +0 -0
- {bensemble-0.2.2 → bensemble-0.3.0}/tests/test_metrics.py +0 -0
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: bensemble
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Library with implementations of various ensembling methods.
|
|
5
|
-
Author: Dmitrii Vasilenko, Fedor Sobolevsky, Muhammadsharif Nabiev, Vadim
|
|
5
|
+
Author: Dmitrii Vasilenko, Fedor Sobolevsky, Muhammadsharif Nabiev, Vadim Kasiuk
|
|
6
6
|
License: MIT
|
|
7
7
|
Project-URL: Homepage, https://github.com/intsystems/bensemble
|
|
8
8
|
Project-URL: Bug_Tracker, https://github.com/intsystems/bensemble/issues
|
|
9
|
-
Project-URL: Documentation, https://github.
|
|
9
|
+
Project-URL: Documentation, https://intsystems.github.io/bensemble/
|
|
10
10
|
Project-URL: Source, https://github.com/intsystems/bensemble
|
|
11
11
|
Keywords: bayesian,neural network,ensemble,variational inference,renyi
|
|
12
12
|
Classifier: Programming Language :: Python :: 3
|
|
@@ -37,6 +37,14 @@ Requires-Dist: mkdocstrings[python]; extra == "docs"
|
|
|
37
37
|
Requires-Dist: mkdocs-minify-plugin; extra == "docs"
|
|
38
38
|
Requires-Dist: pymdown-extensions; extra == "docs"
|
|
39
39
|
Requires-Dist: python-markdown-math; extra == "docs"
|
|
40
|
+
Provides-Extra: benchmarks
|
|
41
|
+
Requires-Dist: torchvision>=0.20; extra == "benchmarks"
|
|
42
|
+
Requires-Dist: tqdm; extra == "benchmarks"
|
|
43
|
+
Requires-Dist: pandas; extra == "benchmarks"
|
|
44
|
+
Requires-Dist: tabulate; extra == "benchmarks"
|
|
45
|
+
Requires-Dist: seaborn; extra == "benchmarks"
|
|
46
|
+
Requires-Dist: scikit-learn; extra == "benchmarks"
|
|
47
|
+
Requires-Dist: ucimlrepo; extra == "benchmarks"
|
|
40
48
|
Dynamic: license-file
|
|
41
49
|
|
|
42
50
|
# Bensemble: Modular Bayesian Deep Learning & Ensembling
|
|
@@ -47,8 +55,9 @@ Dynamic: license-file
|
|
|
47
55
|
[](https://intsystems.github.io/bensemble/)
|
|
48
56
|
[](https://github.com/astral-sh/ruff)
|
|
49
57
|
[](LICENSE)
|
|
58
|
+
[](https://joss.theoj.org/papers/0d7c1f90dc95cc1a9c913a29e7922a4d)
|
|
50
59
|
|
|
51
|
-
**Bensemble** is a
|
|
60
|
+
**Bensemble** is a PyTorch library for combining neural networks, estimating predictive uncertainty, and calibrating predictions.
|
|
52
61
|
|
|
53
62
|
---
|
|
54
63
|
|
|
@@ -59,80 +68,57 @@ Dynamic: license-file
|
|
|
59
68
|
| 📘 **[Documentation](https://intsystems.github.io/bensemble/)** | Full API reference and user guides. |
|
|
60
69
|
| 📝 **[Tech Report](https://github.com/intsystems/bensemble/blob/master/paper/bensemble_tech_report.pdf)** | In-depth technical details and theoretical background. |
|
|
61
70
|
| ✍️ **[Blog Post](https://github.com/intsystems/bensemble/blob/master/blog/bensemble-blogpost.md)** | Summary of the project and motivation. |
|
|
62
|
-
| 📊 **[Benchmarks](https://github.com/intsystems/bensemble/blob/master/
|
|
71
|
+
| 📊 **[Benchmarks](https://github.com/intsystems/bensemble/blob/master/benchmarks)** | Comparison of methods on standard datasets. |
|
|
63
72
|
|
|
64
73
|
---
|
|
65
74
|
|
|
66
75
|
## Features
|
|
67
76
|
|
|
68
|
-
-
|
|
69
|
-
-
|
|
70
|
-
-
|
|
71
|
-
-
|
|
72
|
-
- **Model Calibration & Metrics**: Evaluate models using Expected Calibration Error (ECE), Brier Score, and NLL. Fix overconfident networks post-hoc with Temperature and Vector Scaling.
|
|
77
|
+
- Combine independently trained PyTorch models or draw predictions from one model with MC dropout using `Ensemble`.
|
|
78
|
+
- Select ensembles with random search (NES-RS), evolutionary search (NES-RE), or Bayesian sampling (NES-BS).
|
|
79
|
+
- Split predictive uncertainty into aleatoric and epistemic components for classification and regression.
|
|
80
|
+
- Calibrate classifiers with temperature or vector scaling. Evaluate predictions with expected calibration error (ECE), Brier score, and negative log-likelihood.
|
|
73
81
|
|
|
74
82
|
---
|
|
75
83
|
|
|
76
84
|
## Installation
|
|
77
85
|
|
|
78
|
-
You can install `bensemble` using pip:
|
|
79
|
-
|
|
80
86
|
```bash
|
|
81
87
|
pip install bensemble
|
|
82
88
|
```
|
|
83
89
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
```bash
|
|
87
|
-
uv pip install bensemble
|
|
88
|
-
```
|
|
90
|
+
With [uv](https://github.com/astral-sh/uv), run `uv pip install bensemble`.
|
|
89
91
|
|
|
90
92
|
---
|
|
91
93
|
|
|
92
94
|
## Quick Start
|
|
93
95
|
|
|
94
|
-
###
|
|
96
|
+
### Combine trained classifiers
|
|
95
97
|
|
|
96
|
-
|
|
98
|
+
`models` is a list of trained PyTorch classifiers that return logits for the same classes in the same order. `x` is a batch of inputs.
|
|
97
99
|
|
|
98
100
|
```python
|
|
99
101
|
import torch
|
|
100
|
-
|
|
102
|
+
|
|
101
103
|
from bensemble.core.ensemble import Ensemble
|
|
102
|
-
from bensemble.calibration.scaling import TemperatureScaling
|
|
103
104
|
from bensemble.uncertainty import decompose_classification_uncertainty
|
|
104
|
-
from bensemble.metrics import expected_calibration_error
|
|
105
|
-
|
|
106
|
-
# 1. Create a Deep Ensemble from standard trained PyTorch models
|
|
107
|
-
models = [nn.Sequential(nn.Linear(10, 20), nn.ReLU(), nn.Linear(20, 3)) for _ in range(5)]
|
|
108
|
-
ensemble = Ensemble.from_models(models)
|
|
109
|
-
|
|
110
|
-
# 2. Calibrate the ensemble using a hold-out validation set
|
|
111
|
-
val_logits, val_labels = torch.randn(100, 3), torch.randint(0, 3, (100,))
|
|
112
|
-
scaler = TemperatureScaling(init_temp=1.5).fit(val_logits, val_labels)
|
|
113
|
-
|
|
114
|
-
# 3. Predict on test data
|
|
115
|
-
test_x = torch.randn(10, 10)
|
|
116
|
-
# Returns shape: [5 models, 10 batch_size, 3 classes]
|
|
117
|
-
logits = scaler(ensemble.predict_members(test_x))
|
|
118
|
-
probs = torch.softmax(logits, dim=-1)
|
|
119
105
|
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
print(f"Epistemic Uncertainty (OOD awareness): {epistemic.mean().item():.4f}")
|
|
106
|
+
ensemble = Ensemble.from_models(models).eval()
|
|
107
|
+
with torch.no_grad():
|
|
108
|
+
member_probs = ensemble.predict_members(x).softmax(dim=-1) # [members, batch, classes]
|
|
109
|
+
probs = member_probs.mean(dim=0)
|
|
110
|
+
total, aleatoric, epistemic = decompose_classification_uncertainty(member_probs)
|
|
126
111
|
```
|
|
127
112
|
|
|
128
|
-
|
|
113
|
+
For a runnable example with training and calibration, see [Getting Started](https://intsystems.github.io/bensemble/getting-started/).
|
|
114
|
+
|
|
115
|
+
### Variational inference
|
|
129
116
|
|
|
130
117
|
Build a Bayesian Neural Network from scratch using our custom layers with the Local Reparameterization Trick.
|
|
131
118
|
|
|
132
119
|
```python
|
|
133
120
|
import torch
|
|
134
121
|
import torch.nn as nn
|
|
135
|
-
from torch.utils.data import DataLoader, TensorDataset
|
|
136
122
|
|
|
137
123
|
from bensemble.layers import BayesianLinear
|
|
138
124
|
from bensemble.losses import VariationalLoss, GaussianLikelihood
|
|
@@ -165,22 +151,42 @@ mean, std = predict_with_uncertainty(model, torch.randn(5, 10), num_samples=100)
|
|
|
165
151
|
print(f"Prediction: {mean[0].item():.2f} ± {std[0].item():.2f}")
|
|
166
152
|
```
|
|
167
153
|
|
|
154
|
+
For Rényi training (`alpha != 1`), use matched weight draws and log densities:
|
|
155
|
+
|
|
156
|
+
```python
|
|
157
|
+
from bensemble.utils import sample_with_log_probs
|
|
158
|
+
|
|
159
|
+
criterion = VariationalLoss(likelihood, alpha=0.5)
|
|
160
|
+
optimizer.zero_grad()
|
|
161
|
+
predictions, log_p, log_q = sample_with_log_probs(model, x, num_samples=8)
|
|
162
|
+
loss = criterion(predictions, y, log_prior=log_p, log_posterior=log_q)
|
|
163
|
+
loss.backward()
|
|
164
|
+
optimizer.step()
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
A scalar KL is accepted only for the ordinary ELBO (`alpha=1`). See the
|
|
168
|
+
[Rényi guide](docs/docs/algorithms/variational-renyi.md) for the objective and
|
|
169
|
+
minibatch scaling.
|
|
170
|
+
|
|
168
171
|
---
|
|
169
172
|
|
|
170
173
|
## Algorithms & Demos
|
|
171
174
|
|
|
172
|
-
|
|
175
|
+
Start with the [examples guide](examples/README.md): four ordered tutorials cover
|
|
176
|
+
ensembling, MC Dropout, variational inference, and Laplace; `examples/search/`
|
|
177
|
+
contains the three NES methods. All seven notebooks use synthetic data on CPU
|
|
178
|
+
and include instructions for running them from a fresh kernel.
|
|
173
179
|
|
|
174
180
|
| Method | Description |
|
|
175
181
|
| :--- | :--- |
|
|
176
|
-
| **Deep Ensembles** |
|
|
177
|
-
| **Monte Carlo Dropout** | Implicit ensembling by keeping dropout active at test time. |
|
|
178
|
-
| **Neural Ensemble Search (NES)** |
|
|
179
|
-
| **NES via Bayesian Sampling** |
|
|
180
|
-
| **Variational Inference** |
|
|
181
|
-
| **Variational Rényi** |
|
|
182
|
-
| **Laplace Approximation** |
|
|
183
|
-
| **Probabilistic Backprop** |
|
|
182
|
+
| **[Deep Ensembles](examples/01_ensemble_basics.ipynb)** | Train independent classifiers, calibrate on held-out data, and decompose uncertainty. |
|
|
183
|
+
| **[Monte Carlo Dropout](examples/02_mc_dropout.ipynb)** | Implicit ensembling by keeping dropout active at test time. |
|
|
184
|
+
| **Neural Ensemble Search ([NES-RS](examples/search/nes_rs.ipynb) / [NES-RE](examples/search/nes_re.ipynb))** | Search architectures and select an ensemble on a separate validation set. |
|
|
185
|
+
| **[NES via Bayesian Sampling](examples/search/nes_bayesian_sampling.ipynb)** | Select from independently trained candidates using a validation-loss posterior and SVGD-inspired refinement. |
|
|
186
|
+
| **[Variational Inference](examples/03_variational_inference.ipynb)** | Learn a Gaussian approximation with the *Local Reparameterization Trick*. |
|
|
187
|
+
| **[Variational Rényi](examples/03_variational_inference.ipynb)** | Train with matched weight draws and per-sample prior/posterior log densities. |
|
|
188
|
+
| **[Laplace Approximation](examples/04_laplace.ipynb)** | Estimate curvature around a trained network and sample an ensemble. |
|
|
189
|
+
| **[Probabilistic Backprop](docs/docs/algorithms/pbp.md)** | Propagate moments using Assumed Density Filtering (ADF); see the algorithm guide. |
|
|
184
190
|
|
|
185
191
|
---
|
|
186
192
|
|
|
@@ -190,26 +196,36 @@ We implement a wide range of Bayesian and Ensembling approaches. Check out the i
|
|
|
190
196
|
bensemble/
|
|
191
197
|
├── core/ # Base protocols, ensemble abstractions, and adapters
|
|
192
198
|
│ ├── ensemble.py # Central `Ensemble` class
|
|
193
|
-
│
|
|
199
|
+
│ ├── member.py # Adapters for explicit and stochastic models
|
|
200
|
+
│ └── types.py # Protocols: Predictor, KLProvider, PosteriorSource
|
|
194
201
|
│
|
|
195
202
|
├── layers/ # Bayesian Layers for Variational Inference
|
|
203
|
+
│ ├── base.py # BaseBayesianLayer: KL divergence, SNR-based pruning
|
|
196
204
|
│ ├── linear.py # Bayesian Linear layer
|
|
197
205
|
│ └── conv.py # Bayesian Convolution layer
|
|
198
206
|
│
|
|
207
|
+
├── methods/ # Standalone posterior-approximation engines
|
|
208
|
+
│ ├── laplace_approximation.py # Laplace with K-FAC curvature
|
|
209
|
+
│ └── probabilistic_backpropagation.py # PBP (ADF-based)
|
|
210
|
+
│
|
|
199
211
|
├── search/ # Neural Ensemble Search algorithms
|
|
200
|
-
│ ├── nes.py
|
|
201
|
-
│
|
|
212
|
+
│ ├── nes.py # NES-RS & NES-RE (RandomSearcher, EvolutionarySearcher)
|
|
213
|
+
│ ├── bayesian.py # NESBS (discrete, SVGD-inspired sampler)
|
|
214
|
+
│ ├── selection.py # Greedy forward selection, scoring criteria
|
|
215
|
+
│ └── space.py # SearchSpace protocol
|
|
202
216
|
│
|
|
203
|
-
├── diversity/
|
|
204
|
-
│ └── dropout.py
|
|
217
|
+
├── diversity/ # Methods to induce ensemble variation
|
|
218
|
+
│ └── dropout.py # Monte Carlo Dropout wrapper
|
|
205
219
|
│
|
|
206
|
-
├── uncertainty/
|
|
207
|
-
│ └── decomposition.py
|
|
220
|
+
├── uncertainty/ # Uncertainty analysis
|
|
221
|
+
│ └── decomposition.py # Separation of Aleatoric and Epistemic uncertainty
|
|
208
222
|
│
|
|
209
|
-
├── calibration/
|
|
210
|
-
│ └── scaling.py
|
|
223
|
+
├── calibration/ # Post-hoc model calibration tools
|
|
224
|
+
│ └── scaling.py # Temperature Scaling and Vector Scaling
|
|
211
225
|
│
|
|
212
|
-
|
|
226
|
+
├── losses.py # VariationalLoss, GaussianLikelihood
|
|
227
|
+
├── utils.py # get_total_kl, predict_with_uncertainty, etc.
|
|
228
|
+
└── metrics.py # Scoring rules: ECE, NLL, Brier Score
|
|
213
229
|
```
|
|
214
230
|
|
|
215
231
|
---
|
|
@@ -255,7 +271,7 @@ Developed by:
|
|
|
255
271
|
- [**Dmitrii Vasilenko**](https://github.com/Dimundel)
|
|
256
272
|
- [**Muhammadsharif Nabiev**](https://github.com/mikhmed-nabiev)
|
|
257
273
|
- [**Fedor Sobolevsky**](https://github.com/TeoSable)
|
|
258
|
-
- [**Vadim
|
|
274
|
+
- [**Vadim Kasiuk**](https://github.com/KasiukVadim)
|
|
259
275
|
|
|
260
276
|
---
|
|
261
277
|
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
# Bensemble: Modular Bayesian Deep Learning & Ensembling
|
|
2
|
+
|
|
3
|
+
[](https://www.python.org/)
|
|
4
|
+
[](https://github.com/intsystems/bensemble/actions)
|
|
5
|
+
[](https://codecov.io/gh/intsystems/bensemble)
|
|
6
|
+
[](https://intsystems.github.io/bensemble/)
|
|
7
|
+
[](https://github.com/astral-sh/ruff)
|
|
8
|
+
[](LICENSE)
|
|
9
|
+
[](https://joss.theoj.org/papers/0d7c1f90dc95cc1a9c913a29e7922a4d)
|
|
10
|
+
|
|
11
|
+
**Bensemble** is a PyTorch library for combining neural networks, estimating predictive uncertainty, and calibrating predictions.
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
## Key Resources
|
|
16
|
+
|
|
17
|
+
| Resource | Description |
|
|
18
|
+
| :--- | :--- |
|
|
19
|
+
| 📘 **[Documentation](https://intsystems.github.io/bensemble/)** | Full API reference and user guides. |
|
|
20
|
+
| 📝 **[Tech Report](https://github.com/intsystems/bensemble/blob/master/paper/bensemble_tech_report.pdf)** | In-depth technical details and theoretical background. |
|
|
21
|
+
| ✍️ **[Blog Post](https://github.com/intsystems/bensemble/blob/master/blog/bensemble-blogpost.md)** | Summary of the project and motivation. |
|
|
22
|
+
| 📊 **[Benchmarks](https://github.com/intsystems/bensemble/blob/master/benchmarks)** | Comparison of methods on standard datasets. |
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## Features
|
|
27
|
+
|
|
28
|
+
- Combine independently trained PyTorch models or draw predictions from one model with MC dropout using `Ensemble`.
|
|
29
|
+
- Select ensembles with random search (NES-RS), evolutionary search (NES-RE), or Bayesian sampling (NES-BS).
|
|
30
|
+
- Split predictive uncertainty into aleatoric and epistemic components for classification and regression.
|
|
31
|
+
- Calibrate classifiers with temperature or vector scaling. Evaluate predictions with expected calibration error (ECE), Brier score, and negative log-likelihood.
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## Installation
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install bensemble
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
With [uv](https://github.com/astral-sh/uv), run `uv pip install bensemble`.
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## Quick Start
|
|
46
|
+
|
|
47
|
+
### Combine trained classifiers
|
|
48
|
+
|
|
49
|
+
`models` is a list of trained PyTorch classifiers that return logits for the same classes in the same order. `x` is a batch of inputs.
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
import torch
|
|
53
|
+
|
|
54
|
+
from bensemble.core.ensemble import Ensemble
|
|
55
|
+
from bensemble.uncertainty import decompose_classification_uncertainty
|
|
56
|
+
|
|
57
|
+
ensemble = Ensemble.from_models(models).eval()
|
|
58
|
+
with torch.no_grad():
|
|
59
|
+
member_probs = ensemble.predict_members(x).softmax(dim=-1) # [members, batch, classes]
|
|
60
|
+
probs = member_probs.mean(dim=0)
|
|
61
|
+
total, aleatoric, epistemic = decompose_classification_uncertainty(member_probs)
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
For a runnable example with training and calibration, see [Getting Started](https://intsystems.github.io/bensemble/getting-started/).
|
|
65
|
+
|
|
66
|
+
### Variational inference
|
|
67
|
+
|
|
68
|
+
Build a Bayesian Neural Network from scratch using our custom layers with the Local Reparameterization Trick.
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
import torch
|
|
72
|
+
import torch.nn as nn
|
|
73
|
+
|
|
74
|
+
from bensemble.layers import BayesianLinear
|
|
75
|
+
from bensemble.losses import VariationalLoss, GaussianLikelihood
|
|
76
|
+
from bensemble.utils import get_total_kl, predict_with_uncertainty
|
|
77
|
+
|
|
78
|
+
# 1. Define Model using Bayesian Layers
|
|
79
|
+
model = nn.Sequential(
|
|
80
|
+
BayesianLinear(10, 50, prior_sigma=1.0),
|
|
81
|
+
nn.ReLU(),
|
|
82
|
+
BayesianLinear(50, 1, prior_sigma=1.0),
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
# 2. Define Objectives (Likelihood + Divergence)
|
|
86
|
+
likelihood = GaussianLikelihood()
|
|
87
|
+
criterion = VariationalLoss(likelihood, alpha=1.0)
|
|
88
|
+
|
|
89
|
+
optimizer = torch.optim.Adam(list(model.parameters()) + list(likelihood.parameters()), lr=0.01)
|
|
90
|
+
|
|
91
|
+
# 3. Standard PyTorch Training Loop
|
|
92
|
+
model.train()
|
|
93
|
+
for epoch in range(50): # Dummy loop
|
|
94
|
+
x, y = torch.randn(10, 10), torch.randn(10, 1)
|
|
95
|
+
optimizer.zero_grad()
|
|
96
|
+
loss = criterion(model(x), y, get_total_kl(model))
|
|
97
|
+
loss.backward()
|
|
98
|
+
optimizer.step()
|
|
99
|
+
|
|
100
|
+
# 4. Predict with Uncertainty
|
|
101
|
+
mean, std = predict_with_uncertainty(model, torch.randn(5, 10), num_samples=100)
|
|
102
|
+
print(f"Prediction: {mean[0].item():.2f} ± {std[0].item():.2f}")
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
For Rényi training (`alpha != 1`), use matched weight draws and log densities:
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
from bensemble.utils import sample_with_log_probs
|
|
109
|
+
|
|
110
|
+
criterion = VariationalLoss(likelihood, alpha=0.5)
|
|
111
|
+
optimizer.zero_grad()
|
|
112
|
+
predictions, log_p, log_q = sample_with_log_probs(model, x, num_samples=8)
|
|
113
|
+
loss = criterion(predictions, y, log_prior=log_p, log_posterior=log_q)
|
|
114
|
+
loss.backward()
|
|
115
|
+
optimizer.step()
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
A scalar KL is accepted only for the ordinary ELBO (`alpha=1`). See the
|
|
119
|
+
[Rényi guide](docs/docs/algorithms/variational-renyi.md) for the objective and
|
|
120
|
+
minibatch scaling.
|
|
121
|
+
|
|
122
|
+
---
|
|
123
|
+
|
|
124
|
+
## Algorithms & Demos
|
|
125
|
+
|
|
126
|
+
Start with the [examples guide](examples/README.md): four ordered tutorials cover
|
|
127
|
+
ensembling, MC Dropout, variational inference, and Laplace; `examples/search/`
|
|
128
|
+
contains the three NES methods. All seven notebooks use synthetic data on CPU
|
|
129
|
+
and include instructions for running them from a fresh kernel.
|
|
130
|
+
|
|
131
|
+
| Method | Description |
|
|
132
|
+
| :--- | :--- |
|
|
133
|
+
| **[Deep Ensembles](examples/01_ensemble_basics.ipynb)** | Train independent classifiers, calibrate on held-out data, and decompose uncertainty. |
|
|
134
|
+
| **[Monte Carlo Dropout](examples/02_mc_dropout.ipynb)** | Implicit ensembling by keeping dropout active at test time. |
|
|
135
|
+
| **Neural Ensemble Search ([NES-RS](examples/search/nes_rs.ipynb) / [NES-RE](examples/search/nes_re.ipynb))** | Search architectures and select an ensemble on a separate validation set. |
|
|
136
|
+
| **[NES via Bayesian Sampling](examples/search/nes_bayesian_sampling.ipynb)** | Select from independently trained candidates using a validation-loss posterior and SVGD-inspired refinement. |
|
|
137
|
+
| **[Variational Inference](examples/03_variational_inference.ipynb)** | Learn a Gaussian approximation with the *Local Reparameterization Trick*. |
|
|
138
|
+
| **[Variational Rényi](examples/03_variational_inference.ipynb)** | Train with matched weight draws and per-sample prior/posterior log densities. |
|
|
139
|
+
| **[Laplace Approximation](examples/04_laplace.ipynb)** | Estimate curvature around a trained network and sample an ensemble. |
|
|
140
|
+
| **[Probabilistic Backprop](docs/docs/algorithms/pbp.md)** | Propagate moments using Assumed Density Filtering (ADF); see the algorithm guide. |
|
|
141
|
+
|
|
142
|
+
---
|
|
143
|
+
|
|
144
|
+
## Structure
|
|
145
|
+
|
|
146
|
+
```text
|
|
147
|
+
bensemble/
|
|
148
|
+
├── core/ # Base protocols, ensemble abstractions, and adapters
|
|
149
|
+
│ ├── ensemble.py # Central `Ensemble` class
|
|
150
|
+
│ ├── member.py # Adapters for explicit and stochastic models
|
|
151
|
+
│ └── types.py # Protocols: Predictor, KLProvider, PosteriorSource
|
|
152
|
+
│
|
|
153
|
+
├── layers/ # Bayesian Layers for Variational Inference
|
|
154
|
+
│ ├── base.py # BaseBayesianLayer: KL divergence, SNR-based pruning
|
|
155
|
+
│ ├── linear.py # Bayesian Linear layer
|
|
156
|
+
│ └── conv.py # Bayesian Convolution layer
|
|
157
|
+
│
|
|
158
|
+
├── methods/ # Standalone posterior-approximation engines
|
|
159
|
+
│ ├── laplace_approximation.py # Laplace with K-FAC curvature
|
|
160
|
+
│ └── probabilistic_backpropagation.py # PBP (ADF-based)
|
|
161
|
+
│
|
|
162
|
+
├── search/ # Neural Ensemble Search algorithms
|
|
163
|
+
│ ├── nes.py # NES-RS & NES-RE (RandomSearcher, EvolutionarySearcher)
|
|
164
|
+
│ ├── bayesian.py # NESBS (discrete, SVGD-inspired sampler)
|
|
165
|
+
│ ├── selection.py # Greedy forward selection, scoring criteria
|
|
166
|
+
│ └── space.py # SearchSpace protocol
|
|
167
|
+
│
|
|
168
|
+
├── diversity/ # Methods to induce ensemble variation
|
|
169
|
+
│ └── dropout.py # Monte Carlo Dropout wrapper
|
|
170
|
+
│
|
|
171
|
+
├── uncertainty/ # Uncertainty analysis
|
|
172
|
+
│ └── decomposition.py # Separation of Aleatoric and Epistemic uncertainty
|
|
173
|
+
│
|
|
174
|
+
├── calibration/ # Post-hoc model calibration tools
|
|
175
|
+
│ └── scaling.py # Temperature Scaling and Vector Scaling
|
|
176
|
+
│
|
|
177
|
+
├── losses.py # VariationalLoss, GaussianLikelihood
|
|
178
|
+
├── utils.py # get_total_kl, predict_with_uncertainty, etc.
|
|
179
|
+
└── metrics.py # Scoring rules: ECE, NLL, Brier Score
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
---
|
|
183
|
+
|
|
184
|
+
## Development Setup
|
|
185
|
+
|
|
186
|
+
If you want to contribute to `bensemble` or run tests, we recommend using **uv**.
|
|
187
|
+
|
|
188
|
+
```bash
|
|
189
|
+
# 1. Clone the repository
|
|
190
|
+
git clone https://github.com/intsystems/bensemble.git
|
|
191
|
+
cd bensemble
|
|
192
|
+
|
|
193
|
+
# 2. Create and activate virtual environment via uv
|
|
194
|
+
uv venv
|
|
195
|
+
source .venv/bin/activate # on Windows: .venv\Scripts\activate
|
|
196
|
+
|
|
197
|
+
# 3. Install in editable mode with dev dependencies
|
|
198
|
+
uv pip install -e ".[dev]"
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
### Run Tests
|
|
202
|
+
|
|
203
|
+
```bash
|
|
204
|
+
pytest tests/
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
### Linting
|
|
208
|
+
|
|
209
|
+
We use `ruff` to keep code clean:
|
|
210
|
+
|
|
211
|
+
```bash
|
|
212
|
+
ruff check .
|
|
213
|
+
ruff format .
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
---
|
|
217
|
+
|
|
218
|
+
## Authors
|
|
219
|
+
|
|
220
|
+
Developed by:
|
|
221
|
+
|
|
222
|
+
- [**Dmitrii Vasilenko**](https://github.com/Dimundel)
|
|
223
|
+
- [**Muhammadsharif Nabiev**](https://github.com/mikhmed-nabiev)
|
|
224
|
+
- [**Fedor Sobolevsky**](https://github.com/TeoSable)
|
|
225
|
+
- [**Vadim Kasiuk**](https://github.com/KasiukVadim)
|
|
226
|
+
|
|
227
|
+
---
|
|
228
|
+
|
|
229
|
+
## License
|
|
230
|
+
|
|
231
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
@@ -17,12 +17,12 @@ from .methods import (
|
|
|
17
17
|
LaplaceApproximation,
|
|
18
18
|
PBPEngine,
|
|
19
19
|
)
|
|
20
|
-
from .search import
|
|
20
|
+
from .search import EvolutionarySearcher, RandomSearcher, SearchSpace
|
|
21
21
|
|
|
22
22
|
__all__ = [
|
|
23
|
+
"EvolutionarySearcher",
|
|
23
24
|
"LaplaceApproximation",
|
|
24
25
|
"PBPEngine",
|
|
25
26
|
"RandomSearcher",
|
|
26
|
-
"EvolutionarySearcher",
|
|
27
27
|
"SearchSpace",
|
|
28
28
|
]
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""Post-hoc calibration for classifiers.
|
|
2
|
+
|
|
3
|
+
Both scalers recalibrate class logits against integer class labels; neither
|
|
4
|
+
has a regression counterpart.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import torch
|
|
8
|
+
import torch.nn.functional as F
|
|
9
|
+
from torch import nn, optim
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _fit_calibrator(
|
|
13
|
+
module: nn.Module,
|
|
14
|
+
params: list[nn.Parameter],
|
|
15
|
+
logits: torch.Tensor,
|
|
16
|
+
labels: torch.Tensor,
|
|
17
|
+
max_iter: int,
|
|
18
|
+
optimizer: optim.Optimizer | None,
|
|
19
|
+
) -> None:
|
|
20
|
+
"""Fits a calibration module by minimizing the negative log-likelihood.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
module: Calibration module mapping logits to calibrated logits.
|
|
24
|
+
params: Parameters to optimize, used to build the default optimizer.
|
|
25
|
+
logits: Unscaled logits of shape (N, num_classes).
|
|
26
|
+
labels: Ground truth class indices of shape (N,).
|
|
27
|
+
max_iter: Maximum number of optimizer iterations.
|
|
28
|
+
optimizer: Optimizer over `params`, or None to use the default L-BFGS.
|
|
29
|
+
"""
|
|
30
|
+
logits = logits.detach()
|
|
31
|
+
|
|
32
|
+
if optimizer is None:
|
|
33
|
+
optimizer = optim.LBFGS(
|
|
34
|
+
params,
|
|
35
|
+
lr=1.0,
|
|
36
|
+
max_iter=max_iter,
|
|
37
|
+
line_search_fn="strong_wolfe",
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
def eval_loss():
|
|
41
|
+
optimizer.zero_grad()
|
|
42
|
+
loss = F.cross_entropy(module(logits), labels)
|
|
43
|
+
loss.backward()
|
|
44
|
+
return loss
|
|
45
|
+
|
|
46
|
+
if isinstance(optimizer, optim.LBFGS):
|
|
47
|
+
optimizer.step(eval_loss)
|
|
48
|
+
else:
|
|
49
|
+
for _ in range(max_iter):
|
|
50
|
+
optimizer.step(eval_loss)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class TemperatureScaling(nn.Module):
|
|
54
|
+
"""Temperature Scaling for classifier calibration.
|
|
55
|
+
|
|
56
|
+
Divides logits by a single learnable scalar parameter T (temperature).
|
|
57
|
+
This softens probabilities and calibrates confidence without changing
|
|
58
|
+
classification accuracy (argmax remains identical).
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
def __init__(self, init_temp: float = 1.5):
|
|
62
|
+
"""Initializes the TemperatureScaling module.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
init_temp: Initial value for the temperature scalar. Defaults to 1.5.
|
|
66
|
+
"""
|
|
67
|
+
super().__init__()
|
|
68
|
+
self.temperature = nn.Parameter(torch.ones(1) * init_temp)
|
|
69
|
+
|
|
70
|
+
def forward(self, logits: torch.Tensor) -> torch.Tensor:
|
|
71
|
+
"""Applies temperature scaling to the input logits.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
logits: Raw uncalibrated logits of shape (batch_size, num_classes).
|
|
75
|
+
|
|
76
|
+
Returns:
|
|
77
|
+
torch.Tensor: Scaled logits of shape (batch_size, num_classes).
|
|
78
|
+
"""
|
|
79
|
+
return logits / self.temperature
|
|
80
|
+
|
|
81
|
+
def fit(
|
|
82
|
+
self,
|
|
83
|
+
logits: torch.Tensor,
|
|
84
|
+
labels: torch.Tensor,
|
|
85
|
+
max_iter: int = 50,
|
|
86
|
+
optimizer: optim.Optimizer | None = None,
|
|
87
|
+
) -> "TemperatureScaling":
|
|
88
|
+
"""Finds the optimal temperature T using a validation set.
|
|
89
|
+
|
|
90
|
+
Optimizes the negative log-likelihood.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
logits: Unscaled logits from a hold-out validation set of shape
|
|
94
|
+
(N, num_classes).
|
|
95
|
+
labels: Ground truth class indices of shape (N,).
|
|
96
|
+
max_iter: Maximum number of optimizer iterations. Defaults to 50.
|
|
97
|
+
optimizer: Optimizer over this module's parameters. Defaults to
|
|
98
|
+
L-BFGS with a strong Wolfe line search. L-BFGS runs up to
|
|
99
|
+
`max_iter` iterations within a single step, while any other
|
|
100
|
+
optimizer is stepped `max_iter` times.
|
|
101
|
+
|
|
102
|
+
Returns:
|
|
103
|
+
TemperatureScaling: The fitted instance itself.
|
|
104
|
+
"""
|
|
105
|
+
_fit_calibrator(self, [self.temperature], logits, labels, max_iter, optimizer)
|
|
106
|
+
return self
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class VectorScaling(nn.Module):
|
|
110
|
+
"""Vector Scaling for multi-class calibration (extension of Platt Scaling).
|
|
111
|
+
|
|
112
|
+
Applies a per-class affine transformation to uncalibrated logits:
|
|
113
|
+
calibrated_logits = logits * a + b
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
def __init__(self, num_classes: int):
|
|
117
|
+
"""Initializes the VectorScaling module.
|
|
118
|
+
|
|
119
|
+
Args:
|
|
120
|
+
num_classes: Number of classes in the classification task.
|
|
121
|
+
"""
|
|
122
|
+
super().__init__()
|
|
123
|
+
self.a = nn.Parameter(torch.ones(num_classes))
|
|
124
|
+
self.b = nn.Parameter(torch.zeros(num_classes))
|
|
125
|
+
|
|
126
|
+
def forward(self, logits: torch.Tensor) -> torch.Tensor:
|
|
127
|
+
"""Applies learned affine transformation to the input logits.
|
|
128
|
+
|
|
129
|
+
Args:
|
|
130
|
+
logits: Raw uncalibrated logits of shape (batch_size, num_classes).
|
|
131
|
+
|
|
132
|
+
Returns:
|
|
133
|
+
torch.Tensor: Calibrated logits of shape (batch_size, num_classes).
|
|
134
|
+
"""
|
|
135
|
+
return logits * self.a + self.b
|
|
136
|
+
|
|
137
|
+
def fit(
|
|
138
|
+
self,
|
|
139
|
+
logits: torch.Tensor,
|
|
140
|
+
labels: torch.Tensor,
|
|
141
|
+
max_iter: int = 50,
|
|
142
|
+
optimizer: optim.Optimizer | None = None,
|
|
143
|
+
) -> "VectorScaling":
|
|
144
|
+
"""Finds optimal scaling vectors 'a' and 'b' using a validation set.
|
|
145
|
+
|
|
146
|
+
Optimizes the negative log-likelihood.
|
|
147
|
+
|
|
148
|
+
Args:
|
|
149
|
+
logits: Unscaled logits from a hold-out validation set of shape
|
|
150
|
+
(N, num_classes).
|
|
151
|
+
labels: Ground truth class indices of shape (N,).
|
|
152
|
+
max_iter: Maximum number of optimizer iterations. Defaults to 50.
|
|
153
|
+
optimizer: Optimizer over this module's parameters. Defaults to
|
|
154
|
+
L-BFGS with a strong Wolfe line search. L-BFGS runs up to
|
|
155
|
+
`max_iter` iterations within a single step, while any other
|
|
156
|
+
optimizer is stepped `max_iter` times.
|
|
157
|
+
|
|
158
|
+
Returns:
|
|
159
|
+
VectorScaling: The fitted instance itself.
|
|
160
|
+
"""
|
|
161
|
+
_fit_calibrator(self, [self.a, self.b], logits, labels, max_iter, optimizer)
|
|
162
|
+
return self
|