bensemble 0.1.0__tar.gz → 0.2.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.0/PKG-INFO +264 -0
- bensemble-0.2.0/README.md +223 -0
- bensemble-0.2.0/bensemble/__init__.py +24 -0
- bensemble-0.2.0/bensemble/calibration/scaling.py +126 -0
- {bensemble-0.1.0 → bensemble-0.2.0}/bensemble/core/base.py +22 -19
- bensemble-0.2.0/bensemble/core/ensemble.py +57 -0
- bensemble-0.2.0/bensemble/core/member.py +109 -0
- bensemble-0.2.0/bensemble/core/types.py +29 -0
- bensemble-0.2.0/bensemble/diversity/dropout.py +13 -0
- bensemble-0.2.0/bensemble/layers/__init__.py +3 -0
- bensemble-0.2.0/bensemble/layers/base.py +97 -0
- bensemble-0.2.0/bensemble/layers/conv.py +102 -0
- bensemble-0.2.0/bensemble/layers/linear.py +79 -0
- bensemble-0.2.0/bensemble/losses.py +81 -0
- bensemble-0.2.0/bensemble/methods/__init__.py +12 -0
- bensemble-0.2.0/bensemble/methods/laplace_approximation.py +483 -0
- {bensemble-0.1.0 → bensemble-0.2.0}/bensemble/methods/probabilistic_backpropagation.py +95 -35
- bensemble-0.2.0/bensemble/metrics.py +130 -0
- bensemble-0.2.0/bensemble/search/__init__.py +18 -0
- bensemble-0.2.0/bensemble/search/bayesian.py +173 -0
- bensemble-0.2.0/bensemble/search/nes.py +175 -0
- bensemble-0.2.0/bensemble/search/selection.py +128 -0
- bensemble-0.2.0/bensemble/search/space.py +21 -0
- bensemble-0.2.0/bensemble/uncertainty/decomposition.py +54 -0
- bensemble-0.2.0/bensemble/utils.py +70 -0
- bensemble-0.2.0/bensemble.egg-info/PKG-INFO +264 -0
- bensemble-0.2.0/bensemble.egg-info/SOURCES.txt +37 -0
- bensemble-0.2.0/bensemble.egg-info/requires.txt +18 -0
- bensemble-0.2.0/pyproject.toml +63 -0
- bensemble-0.2.0/tests/test_losses.py +81 -0
- bensemble-0.2.0/tests/test_metrics.py +107 -0
- bensemble-0.2.0/tests/test_utils.py +93 -0
- bensemble-0.1.0/PKG-INFO +0 -76
- bensemble-0.1.0/README.md +0 -54
- bensemble-0.1.0/bensemble/core/utils.py +0 -50
- bensemble-0.1.0/bensemble/methods/laplace_approximation.py +0 -470
- bensemble-0.1.0/bensemble/methods/prob_back_prop.py +0 -268
- bensemble-0.1.0/bensemble/methods/variational_inference.py +0 -240
- bensemble-0.1.0/bensemble/methods/variational_renyi.py +0 -259
- bensemble-0.1.0/bensemble.egg-info/PKG-INFO +0 -76
- bensemble-0.1.0/bensemble.egg-info/SOURCES.txt +0 -18
- bensemble-0.1.0/bensemble.egg-info/requires.txt +0 -13
- bensemble-0.1.0/setup.py +0 -50
- {bensemble-0.1.0 → bensemble-0.2.0}/LICENSE +0 -0
- {bensemble-0.1.0/bensemble → bensemble-0.2.0/bensemble/calibration}/__init__.py +0 -0
- {bensemble-0.1.0 → bensemble-0.2.0}/bensemble/core/__init__.py +0 -0
- {bensemble-0.1.0/bensemble/methods → bensemble-0.2.0/bensemble/uncertainty}/__init__.py +0 -0
- {bensemble-0.1.0 → bensemble-0.2.0}/bensemble.egg-info/dependency_links.txt +0 -0
- {bensemble-0.1.0 → bensemble-0.2.0}/bensemble.egg-info/top_level.txt +0 -0
- {bensemble-0.1.0 → bensemble-0.2.0}/setup.cfg +0 -0
bensemble-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: bensemble
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Library with implementations of various ensembling methods.
|
|
5
|
+
Author: Dmitrii Vasilenko, Fedor Sobolevsky, Muhammadsharif Nabiev, Vadim Kasyuk
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/intsystems/bensemble
|
|
8
|
+
Project-URL: Bug_Tracker, https://github.com/intsystems/bensemble/issues
|
|
9
|
+
Project-URL: Documentation, https://github.com/intsystems/bensemble#readme
|
|
10
|
+
Project-URL: Source, https://github.com/intsystems/bensemble
|
|
11
|
+
Keywords: bayesian,neural network,ensemble,variational inference,renyi
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Classifier: Intended Audience :: Science/Research
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: torch>=2.9.1
|
|
25
|
+
Requires-Dist: numpy>=2.2.6
|
|
26
|
+
Requires-Dist: matplotlib>=3.10.7
|
|
27
|
+
Requires-Dist: scipy>=1.15.3
|
|
28
|
+
Provides-Extra: dev
|
|
29
|
+
Requires-Dist: pytest; extra == "dev"
|
|
30
|
+
Requires-Dist: pytest-cov; extra == "dev"
|
|
31
|
+
Requires-Dist: nbqa; extra == "dev"
|
|
32
|
+
Requires-Dist: mypy; extra == "dev"
|
|
33
|
+
Requires-Dist: ruff; extra == "dev"
|
|
34
|
+
Provides-Extra: docs
|
|
35
|
+
Requires-Dist: mkdocs-material; extra == "docs"
|
|
36
|
+
Requires-Dist: mkdocstrings[python]; extra == "docs"
|
|
37
|
+
Requires-Dist: mkdocs-minify-plugin; extra == "docs"
|
|
38
|
+
Requires-Dist: pymdown-extensions; extra == "docs"
|
|
39
|
+
Requires-Dist: python-markdown-math; extra == "docs"
|
|
40
|
+
Dynamic: license-file
|
|
41
|
+
|
|
42
|
+
# Bensemble: Modular Bayesian Deep Learning & Ensembling
|
|
43
|
+
|
|
44
|
+
[](https://www.python.org/)
|
|
45
|
+
[](https://github.com/intsystems/bensemble/actions)
|
|
46
|
+
[](https://codecov.io/gh/intsystems/bensemble)
|
|
47
|
+
[](https://intsystems.github.io/bensemble/)
|
|
48
|
+
[](https://github.com/astral-sh/ruff)
|
|
49
|
+
[](LICENSE)
|
|
50
|
+
|
|
51
|
+
**Bensemble** is a production-ready, lightweight library for Bayesian Deep Learning and Neural Network Ensembling.
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## Key Resources
|
|
56
|
+
|
|
57
|
+
| Resource | Description |
|
|
58
|
+
| :--- | :--- |
|
|
59
|
+
| 📘 **[Documentation](https://intsystems.github.io/bensemble/)** | Full API reference and user guides. |
|
|
60
|
+
| 📝 **[Tech Report](https://github.com/intsystems/bensemble/blob/master/paper/bensemble_tech_report.pdf)** | In-depth technical details and theoretical background. |
|
|
61
|
+
| ✍️ **[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/notebooks/benchmark.ipynb)** | Comparison of methods on standard datasets. |
|
|
63
|
+
|
|
64
|
+
---
|
|
65
|
+
|
|
66
|
+
## Features
|
|
67
|
+
|
|
68
|
+
- **PyTorch-Native**: No hidden training loops. Use standard PyTorch to train your models, and use Bensemble for inference, ensembling, and analytics.
|
|
69
|
+
- **Unified Ensembling API**: Seamlessly combine explicit models (Deep Ensembles, NAS) and implicit methods (MC Dropout) via a single `Ensemble` interface.
|
|
70
|
+
- **Neural Ensemble Search (NES)**: Algorithms to automatically search for diverse architectures using NNI and Stein Variational Gradient Descent (SVGD).
|
|
71
|
+
- **Uncertainty Analytics**: Principled decomposition of predictive uncertainty into *aleatoric* (data noise) and *epistemic* (model ignorance) components.
|
|
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.
|
|
73
|
+
|
|
74
|
+
---
|
|
75
|
+
|
|
76
|
+
## Installation
|
|
77
|
+
|
|
78
|
+
You can install `bensemble` using pip:
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
pip install bensemble
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Or, using [uv](https://github.com/astral-sh/uv) for lightning-fast installation:
|
|
85
|
+
|
|
86
|
+
```bash
|
|
87
|
+
uv pip install bensemble
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## Quick Start
|
|
93
|
+
|
|
94
|
+
### Example 1: Ensembling, Calibration & Uncertainty
|
|
95
|
+
|
|
96
|
+
Easily ensemble standard PyTorch models, calibrate them, and decompose their uncertainty to detect Out-Of-Distribution data.
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
import torch
|
|
100
|
+
import torch.nn as nn
|
|
101
|
+
from bensemble.core.ensemble import Ensemble
|
|
102
|
+
from bensemble.calibration.scaling import TemperatureScaling
|
|
103
|
+
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
|
+
|
|
120
|
+
# 4. Decompose Uncertainty & Evaluate
|
|
121
|
+
total, aleatoric, epistemic = decompose_classification_uncertainty(probs)
|
|
122
|
+
ece = expected_calibration_error(probs.mean(dim=0), val_labels[:10])
|
|
123
|
+
|
|
124
|
+
print(f"Calibration Error (ECE): {ece:.4f}")
|
|
125
|
+
print(f"Epistemic Uncertainty (OOD awareness): {epistemic.mean().item():.4f}")
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
### Example 2: Variational Inference
|
|
129
|
+
|
|
130
|
+
Build a Bayesian Neural Network from scratch using our custom layers with the Local Reparameterization Trick.
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
import torch
|
|
134
|
+
import torch.nn as nn
|
|
135
|
+
from torch.utils.data import DataLoader, TensorDataset
|
|
136
|
+
|
|
137
|
+
from bensemble.layers import BayesianLinear
|
|
138
|
+
from bensemble.losses import VariationalLoss, GaussianLikelihood
|
|
139
|
+
from bensemble.utils import get_total_kl, predict_with_uncertainty
|
|
140
|
+
|
|
141
|
+
# 1. Define Model using Bayesian Layers
|
|
142
|
+
model = nn.Sequential(
|
|
143
|
+
BayesianLinear(10, 50, prior_sigma=1.0),
|
|
144
|
+
nn.ReLU(),
|
|
145
|
+
BayesianLinear(50, 1, prior_sigma=1.0),
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
# 2. Define Objectives (Likelihood + Divergence)
|
|
149
|
+
likelihood = GaussianLikelihood()
|
|
150
|
+
criterion = VariationalLoss(likelihood, alpha=1.0)
|
|
151
|
+
|
|
152
|
+
optimizer = torch.optim.Adam(list(model.parameters()) + list(likelihood.parameters()), lr=0.01)
|
|
153
|
+
|
|
154
|
+
# 3. Standard PyTorch Training Loop
|
|
155
|
+
model.train()
|
|
156
|
+
for epoch in range(50): # Dummy loop
|
|
157
|
+
x, y = torch.randn(10, 10), torch.randn(10, 1)
|
|
158
|
+
optimizer.zero_grad()
|
|
159
|
+
loss = criterion(model(x), y, get_total_kl(model))
|
|
160
|
+
loss.backward()
|
|
161
|
+
optimizer.step()
|
|
162
|
+
|
|
163
|
+
# 4. Predict with Uncertainty
|
|
164
|
+
mean, std = predict_with_uncertainty(model, torch.randn(5, 10), num_samples=100)
|
|
165
|
+
print(f"Prediction: {mean[0].item():.2f} ± {std[0].item():.2f}")
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
---
|
|
169
|
+
|
|
170
|
+
## Algorithms & Demos
|
|
171
|
+
|
|
172
|
+
We implement a wide range of Bayesian and Ensembling approaches. Check out the interactive demos in the `notebooks/` directory:
|
|
173
|
+
|
|
174
|
+
| Method | Description |
|
|
175
|
+
| :--- | :--- |
|
|
176
|
+
| **Deep Ensembles** | Naive yet powerful ensembling of independent networks with explicit uncertainty decomposition. |
|
|
177
|
+
| **Monte Carlo Dropout** | Implicit ensembling by keeping dropout active at test time. |
|
|
178
|
+
| **Neural Ensemble Search (NES)** | Automatically searches for diverse architectures (NES-RS/NES-RE) using NNI. |
|
|
179
|
+
| **NES via Bayesian Sampling** | Extracts diverse subnetworks from a Supernet using Stein Variational Gradient Descent (SVGD). |
|
|
180
|
+
| **Variational Inference** | Approximates posterior using Gaussian distributions with the *Local Reparameterization Trick*. |
|
|
181
|
+
| **Variational Rényi** | Generalization of VI minimizing $\alpha$-divergence (VR-VI) for better robustness. |
|
|
182
|
+
| **Laplace Approximation** | Fits a Gaussian around the MAP estimate using Kronecker-Factored Curvature (K-FAC). |
|
|
183
|
+
| **Probabilistic Backprop** | Propagates moments through the network using Assumed Density Filtering (ADF). |
|
|
184
|
+
|
|
185
|
+
---
|
|
186
|
+
|
|
187
|
+
## Structure
|
|
188
|
+
|
|
189
|
+
```text
|
|
190
|
+
bensemble/
|
|
191
|
+
├── core/ # Base protocols, ensemble abstractions, and adapters
|
|
192
|
+
│ ├── ensemble.py # Central `Ensemble` class
|
|
193
|
+
│ └── member.py # Adapters for explicit and stochastic models
|
|
194
|
+
│
|
|
195
|
+
├── layers/ # Bayesian Layers for Variational Inference
|
|
196
|
+
│ ├── linear.py # Bayesian Linear layer
|
|
197
|
+
│ └── conv.py # Bayesian Convolution layer
|
|
198
|
+
│
|
|
199
|
+
├── search/ # Neural Ensemble Search algorithms
|
|
200
|
+
│ ├── nes.py # NES-RS & NES-RE
|
|
201
|
+
│ └── bayesian.py # NES via Bayesian Sampling
|
|
202
|
+
│
|
|
203
|
+
├── diversity/ # Methods to induce ensemble variation
|
|
204
|
+
│ └── dropout.py # Monte Carlo Dropout wrapper
|
|
205
|
+
│
|
|
206
|
+
├── uncertainty/ # Uncertainty analysis
|
|
207
|
+
│ └── decomposition.py # Separation of Aleatoric and Epistemic uncertainty
|
|
208
|
+
│
|
|
209
|
+
├── calibration/ # Post-hoc model calibration tools
|
|
210
|
+
│ └── scaling.py # Temperature Scaling and Vector Scaling
|
|
211
|
+
│
|
|
212
|
+
└── metrics.py # Scoring rules: ECE, NLL, Brier Score
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
---
|
|
216
|
+
|
|
217
|
+
## Development Setup
|
|
218
|
+
|
|
219
|
+
If you want to contribute to `bensemble` or run tests, we recommend using **uv**.
|
|
220
|
+
|
|
221
|
+
```bash
|
|
222
|
+
# 1. Clone the repository
|
|
223
|
+
git clone https://github.com/intsystems/bensemble.git
|
|
224
|
+
cd bensemble
|
|
225
|
+
|
|
226
|
+
# 2. Create and activate virtual environment via uv
|
|
227
|
+
uv venv
|
|
228
|
+
source .venv/bin/activate # on Windows: .venv\Scripts\activate
|
|
229
|
+
|
|
230
|
+
# 3. Install in editable mode with dev dependencies
|
|
231
|
+
uv pip install -e ".[dev]"
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
### Run Tests
|
|
235
|
+
|
|
236
|
+
```bash
|
|
237
|
+
pytest tests/
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
### Linting
|
|
241
|
+
|
|
242
|
+
We use `ruff` to keep code clean:
|
|
243
|
+
|
|
244
|
+
```bash
|
|
245
|
+
ruff check .
|
|
246
|
+
ruff format .
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
---
|
|
250
|
+
|
|
251
|
+
## Authors
|
|
252
|
+
|
|
253
|
+
Developed by:
|
|
254
|
+
|
|
255
|
+
- [**Dmitrii Vasilenko**](https://github.com/Dimundel)
|
|
256
|
+
- [**Muhammadsharif Nabiev**](https://github.com/mikhmed-nabiev)
|
|
257
|
+
- [**Fedor Sobolevsky**](https://github.com/TeoSable)
|
|
258
|
+
- [**Vadim Kasyuk**](https://github.com/KasiukVadim)
|
|
259
|
+
|
|
260
|
+
---
|
|
261
|
+
|
|
262
|
+
## License
|
|
263
|
+
|
|
264
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
@@ -0,0 +1,223 @@
|
|
|
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
|
+
|
|
10
|
+
**Bensemble** is a production-ready, lightweight library for Bayesian Deep Learning and Neural Network Ensembling.
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## Key Resources
|
|
15
|
+
|
|
16
|
+
| Resource | Description |
|
|
17
|
+
| :--- | :--- |
|
|
18
|
+
| 📘 **[Documentation](https://intsystems.github.io/bensemble/)** | Full API reference and user guides. |
|
|
19
|
+
| 📝 **[Tech Report](https://github.com/intsystems/bensemble/blob/master/paper/bensemble_tech_report.pdf)** | In-depth technical details and theoretical background. |
|
|
20
|
+
| ✍️ **[Blog Post](https://github.com/intsystems/bensemble/blob/master/blog/bensemble-blogpost.md)** | Summary of the project and motivation. |
|
|
21
|
+
| 📊 **[Benchmarks](https://github.com/intsystems/bensemble/blob/master/notebooks/benchmark.ipynb)** | Comparison of methods on standard datasets. |
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## Features
|
|
26
|
+
|
|
27
|
+
- **PyTorch-Native**: No hidden training loops. Use standard PyTorch to train your models, and use Bensemble for inference, ensembling, and analytics.
|
|
28
|
+
- **Unified Ensembling API**: Seamlessly combine explicit models (Deep Ensembles, NAS) and implicit methods (MC Dropout) via a single `Ensemble` interface.
|
|
29
|
+
- **Neural Ensemble Search (NES)**: Algorithms to automatically search for diverse architectures using NNI and Stein Variational Gradient Descent (SVGD).
|
|
30
|
+
- **Uncertainty Analytics**: Principled decomposition of predictive uncertainty into *aleatoric* (data noise) and *epistemic* (model ignorance) components.
|
|
31
|
+
- **Model Calibration & Metrics**: Evaluate models using Expected Calibration Error (ECE), Brier Score, and NLL. Fix overconfident networks post-hoc with Temperature and Vector Scaling.
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## Installation
|
|
36
|
+
|
|
37
|
+
You can install `bensemble` using pip:
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install bensemble
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Or, using [uv](https://github.com/astral-sh/uv) for lightning-fast installation:
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
uv pip install bensemble
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
---
|
|
50
|
+
|
|
51
|
+
## Quick Start
|
|
52
|
+
|
|
53
|
+
### Example 1: Ensembling, Calibration & Uncertainty
|
|
54
|
+
|
|
55
|
+
Easily ensemble standard PyTorch models, calibrate them, and decompose their uncertainty to detect Out-Of-Distribution data.
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
import torch
|
|
59
|
+
import torch.nn as nn
|
|
60
|
+
from bensemble.core.ensemble import Ensemble
|
|
61
|
+
from bensemble.calibration.scaling import TemperatureScaling
|
|
62
|
+
from bensemble.uncertainty import decompose_classification_uncertainty
|
|
63
|
+
from bensemble.metrics import expected_calibration_error
|
|
64
|
+
|
|
65
|
+
# 1. Create a Deep Ensemble from standard trained PyTorch models
|
|
66
|
+
models = [nn.Sequential(nn.Linear(10, 20), nn.ReLU(), nn.Linear(20, 3)) for _ in range(5)]
|
|
67
|
+
ensemble = Ensemble.from_models(models)
|
|
68
|
+
|
|
69
|
+
# 2. Calibrate the ensemble using a hold-out validation set
|
|
70
|
+
val_logits, val_labels = torch.randn(100, 3), torch.randint(0, 3, (100,))
|
|
71
|
+
scaler = TemperatureScaling(init_temp=1.5).fit(val_logits, val_labels)
|
|
72
|
+
|
|
73
|
+
# 3. Predict on test data
|
|
74
|
+
test_x = torch.randn(10, 10)
|
|
75
|
+
# Returns shape: [5 models, 10 batch_size, 3 classes]
|
|
76
|
+
logits = scaler(ensemble.predict_members(test_x))
|
|
77
|
+
probs = torch.softmax(logits, dim=-1)
|
|
78
|
+
|
|
79
|
+
# 4. Decompose Uncertainty & Evaluate
|
|
80
|
+
total, aleatoric, epistemic = decompose_classification_uncertainty(probs)
|
|
81
|
+
ece = expected_calibration_error(probs.mean(dim=0), val_labels[:10])
|
|
82
|
+
|
|
83
|
+
print(f"Calibration Error (ECE): {ece:.4f}")
|
|
84
|
+
print(f"Epistemic Uncertainty (OOD awareness): {epistemic.mean().item():.4f}")
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### Example 2: Variational Inference
|
|
88
|
+
|
|
89
|
+
Build a Bayesian Neural Network from scratch using our custom layers with the Local Reparameterization Trick.
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
import torch
|
|
93
|
+
import torch.nn as nn
|
|
94
|
+
from torch.utils.data import DataLoader, TensorDataset
|
|
95
|
+
|
|
96
|
+
from bensemble.layers import BayesianLinear
|
|
97
|
+
from bensemble.losses import VariationalLoss, GaussianLikelihood
|
|
98
|
+
from bensemble.utils import get_total_kl, predict_with_uncertainty
|
|
99
|
+
|
|
100
|
+
# 1. Define Model using Bayesian Layers
|
|
101
|
+
model = nn.Sequential(
|
|
102
|
+
BayesianLinear(10, 50, prior_sigma=1.0),
|
|
103
|
+
nn.ReLU(),
|
|
104
|
+
BayesianLinear(50, 1, prior_sigma=1.0),
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
# 2. Define Objectives (Likelihood + Divergence)
|
|
108
|
+
likelihood = GaussianLikelihood()
|
|
109
|
+
criterion = VariationalLoss(likelihood, alpha=1.0)
|
|
110
|
+
|
|
111
|
+
optimizer = torch.optim.Adam(list(model.parameters()) + list(likelihood.parameters()), lr=0.01)
|
|
112
|
+
|
|
113
|
+
# 3. Standard PyTorch Training Loop
|
|
114
|
+
model.train()
|
|
115
|
+
for epoch in range(50): # Dummy loop
|
|
116
|
+
x, y = torch.randn(10, 10), torch.randn(10, 1)
|
|
117
|
+
optimizer.zero_grad()
|
|
118
|
+
loss = criterion(model(x), y, get_total_kl(model))
|
|
119
|
+
loss.backward()
|
|
120
|
+
optimizer.step()
|
|
121
|
+
|
|
122
|
+
# 4. Predict with Uncertainty
|
|
123
|
+
mean, std = predict_with_uncertainty(model, torch.randn(5, 10), num_samples=100)
|
|
124
|
+
print(f"Prediction: {mean[0].item():.2f} ± {std[0].item():.2f}")
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
---
|
|
128
|
+
|
|
129
|
+
## Algorithms & Demos
|
|
130
|
+
|
|
131
|
+
We implement a wide range of Bayesian and Ensembling approaches. Check out the interactive demos in the `notebooks/` directory:
|
|
132
|
+
|
|
133
|
+
| Method | Description |
|
|
134
|
+
| :--- | :--- |
|
|
135
|
+
| **Deep Ensembles** | Naive yet powerful ensembling of independent networks with explicit uncertainty decomposition. |
|
|
136
|
+
| **Monte Carlo Dropout** | Implicit ensembling by keeping dropout active at test time. |
|
|
137
|
+
| **Neural Ensemble Search (NES)** | Automatically searches for diverse architectures (NES-RS/NES-RE) using NNI. |
|
|
138
|
+
| **NES via Bayesian Sampling** | Extracts diverse subnetworks from a Supernet using Stein Variational Gradient Descent (SVGD). |
|
|
139
|
+
| **Variational Inference** | Approximates posterior using Gaussian distributions with the *Local Reparameterization Trick*. |
|
|
140
|
+
| **Variational Rényi** | Generalization of VI minimizing $\alpha$-divergence (VR-VI) for better robustness. |
|
|
141
|
+
| **Laplace Approximation** | Fits a Gaussian around the MAP estimate using Kronecker-Factored Curvature (K-FAC). |
|
|
142
|
+
| **Probabilistic Backprop** | Propagates moments through the network using Assumed Density Filtering (ADF). |
|
|
143
|
+
|
|
144
|
+
---
|
|
145
|
+
|
|
146
|
+
## Structure
|
|
147
|
+
|
|
148
|
+
```text
|
|
149
|
+
bensemble/
|
|
150
|
+
├── core/ # Base protocols, ensemble abstractions, and adapters
|
|
151
|
+
│ ├── ensemble.py # Central `Ensemble` class
|
|
152
|
+
│ └── member.py # Adapters for explicit and stochastic models
|
|
153
|
+
│
|
|
154
|
+
├── layers/ # Bayesian Layers for Variational Inference
|
|
155
|
+
│ ├── linear.py # Bayesian Linear layer
|
|
156
|
+
│ └── conv.py # Bayesian Convolution layer
|
|
157
|
+
│
|
|
158
|
+
├── search/ # Neural Ensemble Search algorithms
|
|
159
|
+
│ ├── nes.py # NES-RS & NES-RE
|
|
160
|
+
│ └── bayesian.py # NES via Bayesian Sampling
|
|
161
|
+
│
|
|
162
|
+
├── diversity/ # Methods to induce ensemble variation
|
|
163
|
+
│ └── dropout.py # Monte Carlo Dropout wrapper
|
|
164
|
+
│
|
|
165
|
+
├── uncertainty/ # Uncertainty analysis
|
|
166
|
+
│ └── decomposition.py # Separation of Aleatoric and Epistemic uncertainty
|
|
167
|
+
│
|
|
168
|
+
├── calibration/ # Post-hoc model calibration tools
|
|
169
|
+
│ └── scaling.py # Temperature Scaling and Vector Scaling
|
|
170
|
+
│
|
|
171
|
+
└── metrics.py # Scoring rules: ECE, NLL, Brier Score
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
---
|
|
175
|
+
|
|
176
|
+
## Development Setup
|
|
177
|
+
|
|
178
|
+
If you want to contribute to `bensemble` or run tests, we recommend using **uv**.
|
|
179
|
+
|
|
180
|
+
```bash
|
|
181
|
+
# 1. Clone the repository
|
|
182
|
+
git clone https://github.com/intsystems/bensemble.git
|
|
183
|
+
cd bensemble
|
|
184
|
+
|
|
185
|
+
# 2. Create and activate virtual environment via uv
|
|
186
|
+
uv venv
|
|
187
|
+
source .venv/bin/activate # on Windows: .venv\Scripts\activate
|
|
188
|
+
|
|
189
|
+
# 3. Install in editable mode with dev dependencies
|
|
190
|
+
uv pip install -e ".[dev]"
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
### Run Tests
|
|
194
|
+
|
|
195
|
+
```bash
|
|
196
|
+
pytest tests/
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
### Linting
|
|
200
|
+
|
|
201
|
+
We use `ruff` to keep code clean:
|
|
202
|
+
|
|
203
|
+
```bash
|
|
204
|
+
ruff check .
|
|
205
|
+
ruff format .
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
---
|
|
209
|
+
|
|
210
|
+
## Authors
|
|
211
|
+
|
|
212
|
+
Developed by:
|
|
213
|
+
|
|
214
|
+
- [**Dmitrii Vasilenko**](https://github.com/Dimundel)
|
|
215
|
+
- [**Muhammadsharif Nabiev**](https://github.com/mikhmed-nabiev)
|
|
216
|
+
- [**Fedor Sobolevsky**](https://github.com/TeoSable)
|
|
217
|
+
- [**Vadim Kasyuk**](https://github.com/KasiukVadim)
|
|
218
|
+
|
|
219
|
+
---
|
|
220
|
+
|
|
221
|
+
## License
|
|
222
|
+
|
|
223
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""
|
|
2
|
+
bensemble: Bayesian ensemble methods for neural networks.
|
|
3
|
+
|
|
4
|
+
Modules:
|
|
5
|
+
- core: базовые классы и утилиты
|
|
6
|
+
- methods: реализация методов вариационного и байесовского ансамбля
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
__version__ = "0.1.0"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
from .methods import (
|
|
13
|
+
LaplaceApproximation,
|
|
14
|
+
ProbabilisticBackpropagation,
|
|
15
|
+
)
|
|
16
|
+
from .search import RandomSearcher, EvolutionarySearcher, SearchSpace
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"LaplaceApproximation",
|
|
20
|
+
"ProbabilisticBackpropagation",
|
|
21
|
+
"RandomSearcher",
|
|
22
|
+
"EvolutionarySearcher",
|
|
23
|
+
"SearchSpace",
|
|
24
|
+
]
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import torch.nn as nn
|
|
3
|
+
import torch.nn.functional as F
|
|
4
|
+
import torch.optim as optim
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class TemperatureScaling(nn.Module):
|
|
8
|
+
"""
|
|
9
|
+
Temperature Scaling for model calibration.
|
|
10
|
+
|
|
11
|
+
Divides the logits by a learnable scalar parameter T (temperature).
|
|
12
|
+
This softens the probabilities and calibrates the model's confidence
|
|
13
|
+
without changing its accuracy (the argmax remains the same).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
def __init__(self, init_temp: float = 1.5):
|
|
17
|
+
"""
|
|
18
|
+
Args:
|
|
19
|
+
init_temp (float, optional): Initial value for temperature.
|
|
20
|
+
Modern deep networks are typically overconfident, so starting
|
|
21
|
+
with T > 1.0 is recommended. Defaults to 1.5.
|
|
22
|
+
"""
|
|
23
|
+
super().__init__()
|
|
24
|
+
self.temperature = nn.Parameter(torch.ones(1) * init_temp)
|
|
25
|
+
|
|
26
|
+
def forward(self, logits: torch.Tensor) -> torch.Tensor:
|
|
27
|
+
"""
|
|
28
|
+
Applies temperature scaling to the input logits.
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
logits (torch.Tensor): Raw uncalibrated logits of shape[Batch, Num_classes].
|
|
32
|
+
|
|
33
|
+
Returns:
|
|
34
|
+
torch.Tensor: Scaled logits of the same shape.
|
|
35
|
+
"""
|
|
36
|
+
return logits / self.temperature
|
|
37
|
+
|
|
38
|
+
def fit(
|
|
39
|
+
self, logits: torch.Tensor, labels: torch.Tensor, max_iter: int = 50
|
|
40
|
+
) -> "TemperatureScaling":
|
|
41
|
+
"""
|
|
42
|
+
Finds the optimal temperature T using a validation set.
|
|
43
|
+
|
|
44
|
+
Uses the L-BFGS optimizer, which is the standard and most efficient
|
|
45
|
+
algorithm for this 1D convex optimization problem.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
logits (torch.Tensor): Unscaled logits from a hold-out validation set. Shape: [N, Num_classes].
|
|
49
|
+
labels (torch.Tensor): Ground truth class indices. Shape: [N].
|
|
50
|
+
max_iter (int, optional): Maximum number of L-BFGS iterations. Defaults to 50.
|
|
51
|
+
|
|
52
|
+
Returns:
|
|
53
|
+
TemperatureScaling: The fitted model itself.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
logits = logits.detach()
|
|
57
|
+
optimizer = optim.LBFGS([self.temperature], lr=0.01, max_iter=max_iter)
|
|
58
|
+
|
|
59
|
+
def eval_loss():
|
|
60
|
+
optimizer.zero_grad()
|
|
61
|
+
scaled_logits = self.forward(logits)
|
|
62
|
+
loss = F.cross_entropy(scaled_logits, labels)
|
|
63
|
+
loss.backward()
|
|
64
|
+
return loss
|
|
65
|
+
|
|
66
|
+
optimizer.step(eval_loss)
|
|
67
|
+
|
|
68
|
+
return self
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class VectorScaling(nn.Module):
|
|
72
|
+
"""
|
|
73
|
+
Vector Scaling (Multi-class extension of Platt Scaling).
|
|
74
|
+
|
|
75
|
+
Applies a per-class affine transformation to the uncalibrated logits:
|
|
76
|
+
calibrated_logits = logits * a + b
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
def __init__(self, num_classes: int):
|
|
80
|
+
"""
|
|
81
|
+
Args:
|
|
82
|
+
num_classes (int): Number of classes in the classification task.
|
|
83
|
+
"""
|
|
84
|
+
super().__init__()
|
|
85
|
+
self.a = nn.Parameter(torch.ones(num_classes))
|
|
86
|
+
self.b = nn.Parameter(torch.zeros(num_classes))
|
|
87
|
+
|
|
88
|
+
def forward(self, logits: torch.Tensor) -> torch.Tensor:
|
|
89
|
+
"""
|
|
90
|
+
Applies the learned affine transformation to the logits.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
logits (torch.Tensor): Raw uncalibrated logits of shape [Batch, Num_classes].
|
|
94
|
+
|
|
95
|
+
Returns:
|
|
96
|
+
torch.Tensor: Calibrated logits of the same shape.
|
|
97
|
+
"""
|
|
98
|
+
return logits * self.a + self.b
|
|
99
|
+
|
|
100
|
+
def fit(
|
|
101
|
+
self, logits: torch.Tensor, labels: torch.Tensor, max_iter: int = 50
|
|
102
|
+
) -> "VectorScaling":
|
|
103
|
+
"""
|
|
104
|
+
Finds the optimal vectors 'a' and 'b' using a validation set.
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
logits (torch.Tensor): Unscaled logits from a hold-out validation set. Shape:[N, Num_classes].
|
|
108
|
+
labels (torch.Tensor): Ground truth class indices. Shape: [N].
|
|
109
|
+
max_iter (int, optional): Maximum number of L-BFGS iterations. Defaults to 50.
|
|
110
|
+
|
|
111
|
+
Returns:
|
|
112
|
+
PlattScaling: The fitted model itself.
|
|
113
|
+
"""
|
|
114
|
+
logits = logits.detach()
|
|
115
|
+
optimizer = optim.LBFGS([self.a, self.b], lr=0.01, max_iter=max_iter)
|
|
116
|
+
|
|
117
|
+
def eval_loss():
|
|
118
|
+
optimizer.zero_grad()
|
|
119
|
+
scaled_logits = self.forward(logits)
|
|
120
|
+
loss = F.cross_entropy(scaled_logits, labels)
|
|
121
|
+
loss.backward()
|
|
122
|
+
return loss
|
|
123
|
+
|
|
124
|
+
optimizer.step(eval_loss)
|
|
125
|
+
|
|
126
|
+
return self
|