bensemble 0.1.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Intelligent Systems, Phystech.edu
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,76 @@
1
+ Metadata-Version: 2.1
2
+ Name: bensemble
3
+ Version: 0.1.0
4
+ Summary: Bayesian ensemble methods for neural networks
5
+ Home-page: https://github.com/intsystems/bensemble
6
+ Author: Соболевский Федор, Набиев Мухаммадшариф, Василенко Дмитрий, Касюк Вадим
7
+ Author-email: kasukvadim@mail.ru
8
+ License: MIT
9
+ Project-URL: Bug Tracker, https://github.com/intsystems/bensemble/issues
10
+ Project-URL: Documentation, https://github.com/intsystems/bensemble#readme
11
+ Project-URL: Source, https://github.com/intsystems/bensemble
12
+ Keywords: bayesian neural network ensemble variational inference renyi
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Intended Audience :: Science/Research
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ Provides-Extra: dev
21
+ License-File: LICENSE
22
+
23
+ |test| |codecov| |docs|
24
+
25
+ .. |test| image:: https://github.com/intsystems/ProjectTemplate/workflows/test/badge.svg
26
+ :target: https://github.com/intsystems/ProjectTemplate/tree/master
27
+ :alt: Test status
28
+
29
+ .. |codecov| image:: https://img.shields.io/codecov/c/github/intsystems/ProjectTemplate/master
30
+ :target: https://app.codecov.io/gh/intsystems/ProjectTemplate
31
+ :alt: Test coverage
32
+
33
+ .. |docs| image:: https://github.com/intsystems/ProjectTemplate/workflows/docs/badge.svg
34
+ :target: https://intsystems.github.io/ProjectTemplate/
35
+ :alt: Docs status
36
+
37
+
38
+ .. class:: center
39
+
40
+ :Название исследуемой задачи: Bayesian ensembling
41
+ :Тип научной работы: Учебный проект по курсу байесовского мультимоделирования
42
+ :Автор: Соболевский Федор, Набиев Мухаммадшариф, Василенко Дмитрий, Касюк Вадим
43
+ :Научный руководитель: к. ф.-м. н. Бахтеев Олег Юрьевич
44
+ :Научный консультант(при наличии): степень, Фамилия Имя Отчество
45
+
46
+ Abstract: Comparative Analysis of Bayesian Deep Learning Methods for Multimodel Ensembling
47
+ ========
48
+
49
+ Bayesian methods provide a principled framework for uncertainty quantification in deep learning, which is crucial for safety-critical applications. This project presents a comprehensive comparative study of four prominent variational inference algorithms for Bayesian neural networks: the baseline Evidence Lower Bound (ELBO) with local reparameterization trick, hyperparameter optimization, and pruning; Renyi divergence as a generalization of ELBO offering tunable mode-seeking/covering behavior; scalable Laplace approximation for efficient posterior estimation; and Bayes by Backpropagation as an alternative variational inference scheme.
50
+
51
+ We implement these methods in a unified framework and evaluate them on benchmark classification and regression tasks using metrics including predictive accuracy, negative log-likelihood, expected calibration error, and out-of-distribution detection performance. Our results demonstrate the trade-offs between computational efficiency, uncertainty quantification quality, and model performance across different methods. Specifically, we show how Renyi divergence with α < 1 provides improved uncertainty calibration compared to standard ELBO, while scalable Laplace approximation offers competitive performance with reduced computational overhead. The study provides practical guidance for selecting appropriate Bayesian inference methods based on application requirements and computational constraints.
52
+
53
+ Keywords: Bayesian Deep Learning, Variational Inference, Uncertainty Quantification, Renyi Divergence, Laplace Approximation, Neural Networks Ensembling
54
+
55
+ Bayesian Multimodeling Project
56
+ ==============================
57
+
58
+ A comprehensive comparative study of Bayesian deep learning methods for neural network ensembling and uncertainty quantification.
59
+
60
+ Project documentation can be found here: https://intsystems.github.io/bensemble/
61
+
62
+ Blog post draft: https://github.com/intsystems/bensemble/blob/master/paper/blogpost_draft/blog_post_draft.pdf
63
+
64
+ Techreport draft: https://github.com/intsystems/bensemble/blob/master/paper/techreport_draft/bensemble_Tech_Report_draft.pdf
65
+
66
+ Benchmark notebook: https://github.com/intsystems/bensemble/blob/master/notebooks/benchmark.ipynb
67
+
68
+ Demos
69
+ --------------------
70
+ Practical Variational Inference: https://github.com/intsystems/bensemble/blob/master/notebooks/pvi_demo.ipynb
71
+
72
+ Kronecker-Factored Laplace Approximation: https://github.com/intsystems/bensemble/blob/master/notebooks/laplace_demo.ipynb
73
+
74
+ Variational Inference with Renyi Divergence: https://github.com/intsystems/bensemble/blob/master/notebooks/variatinal_renyi_demo.ipynb
75
+
76
+ Bayes by Backprop: https://github.com/intsystems/bensemble/blob/master/notebooks/pbp_probabilistic_backpropagation_test.ipynb
@@ -0,0 +1,54 @@
1
+ |test| |codecov| |docs|
2
+
3
+ .. |test| image:: https://github.com/intsystems/ProjectTemplate/workflows/test/badge.svg
4
+ :target: https://github.com/intsystems/ProjectTemplate/tree/master
5
+ :alt: Test status
6
+
7
+ .. |codecov| image:: https://img.shields.io/codecov/c/github/intsystems/ProjectTemplate/master
8
+ :target: https://app.codecov.io/gh/intsystems/ProjectTemplate
9
+ :alt: Test coverage
10
+
11
+ .. |docs| image:: https://github.com/intsystems/ProjectTemplate/workflows/docs/badge.svg
12
+ :target: https://intsystems.github.io/ProjectTemplate/
13
+ :alt: Docs status
14
+
15
+
16
+ .. class:: center
17
+
18
+ :Название исследуемой задачи: Bayesian ensembling
19
+ :Тип научной работы: Учебный проект по курсу байесовского мультимоделирования
20
+ :Автор: Соболевский Федор, Набиев Мухаммадшариф, Василенко Дмитрий, Касюк Вадим
21
+ :Научный руководитель: к. ф.-м. н. Бахтеев Олег Юрьевич
22
+ :Научный консультант(при наличии): степень, Фамилия Имя Отчество
23
+
24
+ Abstract: Comparative Analysis of Bayesian Deep Learning Methods for Multimodel Ensembling
25
+ ========
26
+
27
+ Bayesian methods provide a principled framework for uncertainty quantification in deep learning, which is crucial for safety-critical applications. This project presents a comprehensive comparative study of four prominent variational inference algorithms for Bayesian neural networks: the baseline Evidence Lower Bound (ELBO) with local reparameterization trick, hyperparameter optimization, and pruning; Renyi divergence as a generalization of ELBO offering tunable mode-seeking/covering behavior; scalable Laplace approximation for efficient posterior estimation; and Bayes by Backpropagation as an alternative variational inference scheme.
28
+
29
+ We implement these methods in a unified framework and evaluate them on benchmark classification and regression tasks using metrics including predictive accuracy, negative log-likelihood, expected calibration error, and out-of-distribution detection performance. Our results demonstrate the trade-offs between computational efficiency, uncertainty quantification quality, and model performance across different methods. Specifically, we show how Renyi divergence with α < 1 provides improved uncertainty calibration compared to standard ELBO, while scalable Laplace approximation offers competitive performance with reduced computational overhead. The study provides practical guidance for selecting appropriate Bayesian inference methods based on application requirements and computational constraints.
30
+
31
+ Keywords: Bayesian Deep Learning, Variational Inference, Uncertainty Quantification, Renyi Divergence, Laplace Approximation, Neural Networks Ensembling
32
+
33
+ Bayesian Multimodeling Project
34
+ ==============================
35
+
36
+ A comprehensive comparative study of Bayesian deep learning methods for neural network ensembling and uncertainty quantification.
37
+
38
+ Project documentation can be found here: https://intsystems.github.io/bensemble/
39
+
40
+ Blog post draft: https://github.com/intsystems/bensemble/blob/master/paper/blogpost_draft/blog_post_draft.pdf
41
+
42
+ Techreport draft: https://github.com/intsystems/bensemble/blob/master/paper/techreport_draft/bensemble_Tech_Report_draft.pdf
43
+
44
+ Benchmark notebook: https://github.com/intsystems/bensemble/blob/master/notebooks/benchmark.ipynb
45
+
46
+ Demos
47
+ --------------------
48
+ Practical Variational Inference: https://github.com/intsystems/bensemble/blob/master/notebooks/pvi_demo.ipynb
49
+
50
+ Kronecker-Factored Laplace Approximation: https://github.com/intsystems/bensemble/blob/master/notebooks/laplace_demo.ipynb
51
+
52
+ Variational Inference with Renyi Divergence: https://github.com/intsystems/bensemble/blob/master/notebooks/variatinal_renyi_demo.ipynb
53
+
54
+ Bayes by Backprop: https://github.com/intsystems/bensemble/blob/master/notebooks/pbp_probabilistic_backpropagation_test.ipynb
File without changes
File without changes
@@ -0,0 +1,73 @@
1
+ import abc
2
+ from typing import Any, Dict, List, Optional, Tuple
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+
7
+
8
+ class BaseBayesianEnsemble(abc.ABC):
9
+ """Базовый класс для всех методов байесовского ансамблирования"""
10
+
11
+ def __init__(self, model: nn.Module, **kwargs):
12
+ self.model = model
13
+ self.is_fitted = False
14
+ self.ensemble = []
15
+
16
+ @abc.abstractmethod
17
+ def fit(
18
+ self, #
19
+ train_loader: torch.utils.data.DataLoader,
20
+ val_loader: Optional[torch.utils.data.DataLoader] = None,
21
+ **kwargs
22
+ ) -> Dict[str, List[float]]:
23
+ """Обучение ансамбля"""
24
+ # Надо обсудить параметры и реализацию
25
+ pass
26
+
27
+ @abc.abstractmethod
28
+ def predict(
29
+ self, X: torch.Tensor, n_samples: int = 100
30
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
31
+ """Предсказание с оценкой неопределенности"""
32
+ # Надо обсудить параметры и реализацию
33
+ pass
34
+
35
+ @abc.abstractmethod
36
+ def sample_models(
37
+ self, n_models: int = 10
38
+ ) -> List[
39
+ nn.Module
40
+ ]: # Добавить онлайн-поддерживание сгенереированных моделей -> Поменять предикт
41
+ """Сэмплирование моделей из апостериорного распределения"""
42
+ # Надо обсудить параметры
43
+ pass
44
+
45
+ def save(self, path: str): # Сделать загрузку и выгрузку моделей через стэйт диктов
46
+ """Сохранение обученного ансамбля"""
47
+ torch.save(
48
+ {
49
+ "model_state_dict": self.model.state_dict(),
50
+ "ensemble_state": self._get_ensemble_state(),
51
+ "is_fitted": self.is_fitted,
52
+ },
53
+ path,
54
+ )
55
+
56
+ def load(self, path: str): # Сделать загрузку и выгрузку моделей через стэйт диктов
57
+ """Загрузка обученного ансамбля"""
58
+ checkpoint = torch.load(path)
59
+ self.model.load_state_dict(checkpoint["model_state_dict"])
60
+ self._set_ensemble_state(checkpoint["ensemble_state"])
61
+ self.is_fitted = checkpoint["is_fitted"]
62
+
63
+ @abc.abstractmethod
64
+ def _get_ensemble_state(self) -> Dict[str, Any]:
65
+ """Получение внутреннего состояния ансамбля"""
66
+ # Надо обсудить параметры
67
+ pass
68
+
69
+ @abc.abstractmethod
70
+ def _set_ensemble_state(self, state: Dict[str, Any]):
71
+ """Установка внутреннего состояния ансамбля"""
72
+ # Надо обсудить параметры
73
+ pass
@@ -0,0 +1,50 @@
1
+ from typing import Tuple
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+
6
+
7
+ def compute_uncertainty(predictions: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
8
+ """
9
+ Вычисление эпистемической и алеаторной неопределенности
10
+ """
11
+ # Эпистемическая неопределенность (вариация между моделями)
12
+ epistemic_uncertainty = predictions.var(dim=0)
13
+
14
+ # Алеаторная неопределенность (средняя энтропия предсказаний)
15
+ if predictions.dim() > 2: # Классификация
16
+ mean_probs = predictions.mean(dim=0)
17
+ aleatoric_uncertainty = -(mean_probs * torch.log(mean_probs + 1e-8)).sum(dim=-1)
18
+ else: # Регрессия
19
+ aleatoric_uncertainty = torch.zeros_like(epistemic_uncertainty)
20
+
21
+ return epistemic_uncertainty, aleatoric_uncertainty
22
+
23
+
24
+ def enable_dropout(model: nn.Module):
25
+ """Активация dropout слоев для MC Dropout"""
26
+ for module in model.modules():
27
+ if isinstance(module, nn.Dropout):
28
+ module.train()
29
+
30
+
31
+ class EarlyStopping:
32
+ """Ранняя остановка для обучения"""
33
+
34
+ def __init__(self, patience=10, delta=0):
35
+ self.patience = patience
36
+ self.delta = delta
37
+ self.counter = 0
38
+ self.best_score = None
39
+ self.early_stop = False
40
+
41
+ def __call__(self, val_loss):
42
+ if self.best_score is None:
43
+ self.best_score = val_loss
44
+ elif val_loss > self.best_score - self.delta:
45
+ self.counter += 1
46
+ if self.counter >= self.patience:
47
+ self.early_stop = True
48
+ else:
49
+ self.best_score = val_loss
50
+ self.counter = 0
File without changes