Skip to content

Uncertainty, structured prediction, and causal learning · Uncertainty, structured prediction, and causal learning · UNC005 · Training method

Bayes by Backprop

Learn a distribution over network weights with a differentiable variational objective. Weight sampling and the reparameterization trick make stochastic gradient training possible.

Runs in CodeSplash Component demo, not a trained model CodeSplash's run and the reference's record

In CodeSplash

A CodeSplash method runs this entry in Python and R. Set it up from the method's page.

Do it in CodeSplash Run it on your own data, in Python or R.

Availability
Runs in CodeSplash
Code example
Component demo, not a trained model
Who ran it
CodeSplash's run and the reference's record
CodeSplash's run
Verified in Python and R through learn.torch_mlp. The reference's example ran in Python and R here, and they agree.
The reference's record
Python: Ran in the reference's review. The report doesn't record which version of the code ran. R: Reviewed but not run: R wasn't available to the reference's authors.

Purpose

Learn a distribution over network weights with a differentiable variational objective. Weight sampling and the reparameterization trick make stochastic gradient training possible. This is more specific than adding deterministic weight decay and more approximate than exact posterior inference.

Question / hypotheses

Which tractable weight distribution balances data fit against departure from a prior? Predictive inference averages likelihoods over that fitted distribution; a posterior mean weight vector alone discards the requested weight uncertainty.

Architecture / computational structure

Replace each selected scalar weight by a mean and scale parameter. Draw Gaussian noise and construct sampled weights for a forward pass; optimize Monte Carlo likelihood terms and a KL penalty. Original work also considers scale-mixture priors; the teaching example uses a simpler Gaussian prior with an analytic KL.

Assumptions

The prior, likelihood and variational family are substantive assumptions. Mean-field factorization can miss correlations and modes; poor posterior approximations can be confidently wrong. Minibatch scaling must correspond to a single full-data objective.

Formula / computational definition

Minimize F=Eqϕ(w)[−log⁡p(D∣w)]+KL⁡(qϕ(w)∥p(w))\mathcal F=\mathbb E_{q_\phi(w)}[-\log p(\mathcal D\mid w)]+\operatorname{KL}(q_\phi(w)\|p(w)). For a diagonal Gaussian, w=μ+softplus⁡(ρ)⊙ϵw=\mu+\operatorname{softplus}(\rho)\odot\epsilon, ϵ∼N(0,I)\epsilon\sim N(0,I). A mean-per-observation loss uses KL⁡/n\operatorname{KL}/n; it must not inadvertently count the prior once per datum.

Parameters and notation

Learned: variational means μ and raw scales ρ, plus any deterministic or likelihood parameters. Hyperparameters: prior scale/family, network structure, samples per update/prediction, learning rate, KL schedule and variance floors. A nonunit KL multiplier defines a modified objective and should be reported.

Fitting, fine-tuning, and adaptation

For sequential adaptation, using the previous posterior as a new prior is an explicit approximation requiring non-overlapping new likelihood data. Alternatively refit a variational model jointly on old/new data. Fine-tuning only means while freezing scales changes the uncertainty interpretation and needs a new calibration audit.

How to use and calibrate

Check a small analytic or low-dimensional benchmark before scaling. Compare predictive NLL, coverage, sharpness and approximate-posterior sensitivity to the prior. Inspect whether posterior scales collapse or explode. Use multiple weight samples to estimate predictive distributions and Monte Carlo variability.

Example application

Regress a small noisy physical response surface and visualize posterior function samples. Compare samples from the prior and fitted approximation to reveal strong prior assumptions.

Interpretation / pitfalls

Watch out

Variational standard deviations are not standard errors of deterministic weights. Mean-field KL minimization can underrepresent posterior tails. A favorable ELBO can coexist with poor predictive calibration; distinguish optimization convergence from Bayesian adequacy.

Python and R code examples

Scope: One reparameterized Gaussian variational objective evaluation with analytic Gaussian-prior KL. It illustrates loss scaling and finite values, not a trained Bayesian network.

Dependencies / validation: use the shared NumPy/SciPy or base-R setup above. Python executed successfully with assertions; R reviewed but not executed.

Python and R

The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.

Python

Component demo, not a trained model — One reparameterized Gaussian variational objective evaluation with analytic Gaussian-prior KL. It illustrates loss scaling and finite values, not a trained Bayesian network.

Shared setup for this chapter
import numpy as np
from scipy.special import logsumexp, gammaln
from scipy.linalg import expm
from itertools import product

def rbf(a, b, ell=1.0):
    a, b = np.atleast_2d(a), np.atleast_2d(b)
    return np.exp(-np.sum((a[:, None, :] - b[None, :, :])**2, axis=2)/(2*ell**2))
X = np.array([[1.,0.],[1.,1.],[1.,2.]])
y = np.array([.2,.9,1.7]); mu = np.array([.1,.7]); rho = np.array([-2.,-1.5])
sd = np.logaddexp(0,rho); eps = np.array([.3,-.4]); w = mu+sd*eps
noise_sd = .3; prior_sd = 1.
nll = .5*np.mean(np.log(2*np.pi*noise_sd**2)+(y-X@w)**2/noise_sd**2)
kl = .5*np.sum((sd**2+mu**2)/prior_sd**2-1+2*np.log(prior_sd/sd))
objective = nll+kl/len(y)
assert kl>=0 and np.isfinite(objective)
print({'mean_nll':float(nll),'kl':float(kl),'per_observation_objective':float(objective)})
R

Component demo, not a trained model — One reparameterized Gaussian variational objective evaluation with analytic Gaussian-prior KL. It illustrates loss scaling and finite values, not a trained Bayesian network.

X <- cbind(1,c(0,1,2)); y <- c(.2,.9,1.7)
mu <- c(.1,.7); rho <- c(-2,-1.5); sdw <- log1p(exp(rho))
w <- mu+sdw*c(.3,-.4); noise_sd <- .3; prior_sd <- 1
nll <- .5*mean(log(2*pi*noise_sd^2)+(y-as.vector(X%*%w))^2/noise_sd^2)
kl <- .5*sum((sdw^2+mu^2)/prior_sd^2-1+2*log(prior_sd/sdw))
objective <- nll+kl/length(y)
stopifnot(kl>=0,is.finite(objective))
print(c(mean_nll=nll,kl=kl,per_observation_objective=objective))

Sources

From the CodeSplash reference, entry UNC005.