Skip to main content

A Bayesian Neural Network framework for regression tasks implemented in PyTorch.

Project description

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:

  1. Weight Uncertainty: Instead of single weight values, the network learns a distribution over weights (usually Gaussian)

  2. Variational Inference: Approximate the true posterior distribution with a simpler one (variational distribution)

  3. 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)
  4. Monte Carlo Sampling: Use random samples from the weight distributions during both training and inference

References

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

bayes_regression-0.1.7.tar.gz (14.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

bayes_regression-0.1.7-py3-none-any.whl (20.2 kB view details)

Uploaded Python 3

File details

Details for the file bayes_regression-0.1.7.tar.gz.

File metadata

  • Download URL: bayes_regression-0.1.7.tar.gz
  • Upload date:
  • Size: 14.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.3

File hashes

Hashes for bayes_regression-0.1.7.tar.gz
Algorithm Hash digest
SHA256 ba6df0b46fdac025c0ae1b40a44bae8f571c9ef06ce586e5a448831c3a5bc04d
MD5 b24171022e954fe77279670810963da7
BLAKE2b-256 8d3e24e3982df15a47ca30dd0f8d5fcf961e9660ee574117fe4c4dd0de7e2694

See more details on using hashes here.

File details

Details for the file bayes_regression-0.1.7-py3-none-any.whl.

File metadata

File hashes

Hashes for bayes_regression-0.1.7-py3-none-any.whl
Algorithm Hash digest
SHA256 115d916751ff46b19a16161ff9bbca192aead09a2a08d08c805fabbc23384d46
MD5 10767a611354654c860c98bdeb75f6d4
BLAKE2b-256 8216cca8e75145ade4e6ec8a5a126d7d425fc84ba7773776039f767864d6e2d4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page