Bayes by Backprop
A Bayesian Neural Network framework for regression tasks implemented in PyTorch. This framework provides tools for uncertainty estimation in neural networks through variational inference.
Installation
pip install bayes-regression
Then install the required dependencies:
pip install git+https://github.com/zchccsx/Bayes-by-Backprop.git
Usage
Creating a Model
import Bayes
from Bayes import BayesianLinear, BayesianRegressor
# Create a Bayesian neural network
model = BayesianRegressor(input_dim=10, hidden_dims=[32, 16], output_dim=1)
### Training the Model
# Create trainer
trainer = BayesianRegressionTrainer(
model=model,
learning_rate=0.01
)
# Train model
trainer.train(
X_train=X_train,
y_train=y_train,
X_val=X_val,
y_val=y_val,
batch_size=64,
epochs=500,
samples_nbr=3 # Number of Monte Carlo samples for ELBO
)
Making Predictions with Uncertainty
# Get predictions with uncertainty estimates
y_pred_mean, y_pred_std, all_predictions = trainer.predict(
X_test,
num_samples=100 # More samples = better uncertainty estimates
)
# Confidence intervals (e.g., 95%)
ci_upper = y_pred_mean + (2 * y_pred_std) # 2 std devs = ~95% CI
ci_lower = y_pred_mean - (2 * y_pred_std)
Data Processing and Evaluation
from Bayes.utils import prepare_data, evaluate_uncertainty
# Prepare data
X_train, X_test, y_train, y_test, scaler_X, scaler_y = prepare_data(
X, y, test_size=0.2, random_state=42, scale=True
)
# Evaluate predictions with uncertainty
metrics = evaluate_uncertainty(
y_true=y_test,
y_pred_mean=y_pred_mean,
y_pred_std=y_pred_std,
std_multiplier=2 # 2 standard deviations (~95% confidence interval)
)
print(f"Mean Squared Error: {metrics['mse']:.4f}")
print(f"R² Score: {metrics['r2']:.4f}")
print(f"Confidence Interval Accuracy (95%): {metrics['ci_accuracy']*100:.2f}%")
Visualization
from Bayes.utils import plot_predictions
plot_predictions(
y_true=y_test,
y_pred_mean=y_pred_mean,
y_pred_std=y_pred_std,
std_multiplier=2, # 2 std devs = ~95% CI
max_samples=100 # Limit for clearer visualization
)
Advanced Usage
Customizing Prior Distributions
You can customize the prior distribution for the Bayesian layers:
from Bayes.modules import BayesianLinear
layer = BayesianLinear(
in_features=10,
out_features=5,
prior_sigma1=0.1, # Standard deviation for the first Gaussian
prior_sigma2=0.4, # Standard deviation for the second Gaussian
prior_pi=0.5 # Mixture weight
)
Freezing the Network for Evaluation
# Freeze network to use posterior means (deterministic prediction)
model.freeze()
# Make predictions using only the mean of the posterior
determinstic_preds = model(X_test)
# Unfreeze for sampling-based prediction with uncertainty
model.unfreeze()
Theory: Bayes by Backprop
Bayes by Backprop (Blundell et al., 2015) is a variational inference method for training Bayesian Neural Networks. The key ideas are:
-
Weight Uncertainty: Instead of single weight values, the network learns a distribution over weights (usually Gaussian)
-
Variational Inference: Approximate the true posterior distribution with a simpler one (variational distribution)
-
ELBO Loss: Optimize the Evidence Lower Bound, which balances data fit against complexity:
ELBO = E[log p(D|w)] - KL[q(w|θ) || p(w)]Where:
- E[log p(D|w)] is the expected log-likelihood (data fit)
- KL[q(w|θ) || p(w)] is the KL divergence between posterior and prior (complexity penalty)
-
Monte Carlo Sampling: Use random samples from the weight distributions during both training and inference
References
- Blundell, C., Cornebise, J., Kavukcuoglu, K., & Wierstra, D. (2015). Weight Uncertainty in Neural Networks. In Proceedings of the 32nd International Conference on Machine Learning.
License
MIT
Metadata
Release files for bayes-regression 0.1.7
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | |
|---|---|---|---|---|
| bayes_regression-0.1.7.tar.gz | 14.9 kB | Without provenance | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| bayes_regression-0.1.7-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 35.1 kB
Release files / bayes_regression-0.1.7.tar.gz
| Download URL | bayes_regression-0.1.7.tar.gz |
|---|---|
| Size | 14.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
ba6df0b46fdac025c0ae1b40a44bae8f571c9ef06ce586e5a448831c3a5bc04d
|
|
BLAKE2b-256 checksum How to use checksums |
8d3e24e3982df15a47ca30dd0f8d5fcf961e9660ee574117fe4c4dd0de7e2694
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.11.3
|
Release files / bayes_regression-0.1.7-py3-none-any.whl
| Download URL | bayes_regression-0.1.7-py3-none-any.whl |
|---|---|
| Size | 20.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
115d916751ff46b19a16161ff9bbca192aead09a2a08d08c805fabbc23384d46
|
|
BLAKE2b-256 checksum How to use checksums |
8216cca8e75145ade4e6ec8a5a126d7d425fc84ba7773776039f767864d6e2d4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.11.3
|
Security for bayes-regression 0.1.7
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.