Bayesian inverse PINN: a coefficient with its uncertainty
Bayesian bayesian_inverse_coefficient.py
A field is measured at a few noisy sensors, and the reaction coefficient of the equation behind it is unknown. The answer is not one number but a posterior: a value and an honest credible interval.

Left: the sensors and the fitted surrogate. Middle: four NUTS chains of \(k\) with the 90 % band and the truth. Right: the posterior.
The problem
A steady reaction–diffusion equation on the unit line with a known forcing and an unknown coefficient \(k\):
with sensor data \(u^\text{obs}=\sin\pi x+\text{noise}\) and the true \(k=2\). The posterior is \(p(k\mid u^\text{obs})\propto\exp\!\big(-\lVert(-\lambda u''+ku-f)/\sigma\rVert^2/2\big)\), following the B-PINN of Yang, Meng & Karniadakis (2021).
The jNO code
The recipe has two stages. First a neural surrogate is fitted to the sensors. Then u_net.freeze() turns it into a
fixed forward map, and NUTS samples the single scalar \(k\) through the physics residual. A fixed target is what makes
the sampler's adaptation well-defined:
u_net.freeze()
k = jno.np.parameter((1,), name="k").initialize(jax.nn.initializers.constant(1.0))
k.bayesian(blackjax.nuts, step_size=1e-2, warmup=300, keep=600, num_chains=4, init_jitter=0.5)
u = (u_net(x) * x * (1 - x)).scalar.bind(x=x)
jno.core([((-LAMBDA * u.xx + k * u - f) / SIGMA_PHYS).mse]).solve(900) # -λ u'' + k u - f = 0
.bayesian(...) attaches a blackjax sampler to the parameter, and crux.solve runs it. The samples are
k.posterior_samples, shape (num_chains, keep, 1); four chains make R-hat meaningful.
Result
| posterior of \(k\) | \(1.948\pm0.048\) |
| 90 % credible interval | \([1.867,\ 2.026]\), contains the true 2 |
| R-hat, ESS | 1.002, 440 |
| surrogate against \(\sin\pi x\) | rel. \(L^2\) \(1.6\times10^{-2}\) |
Full script
The whole script, as it runs in the tests
"""Bayesian inverse PINN: the reaction coefficient k in -λ u'' + k u = f on (0, 1), u(0) = u(1) = 0, from noisy sensors.
Phase 1 fits a neural surrogate of u to the data; phase 2 freezes it, so NUTS samples a fixed-target posterior of
the single scalar k through the physics residual. SIGMA_PHYS budgets for the surrogate's model error as well as the
sensor noise: that is what keeps the truth inside the credible interval.
"""
import blackjax
import foundax
import jax
import jax.numpy as jnp
import numpy as np
import optax
import jno
run = jno.setup(__file__)
π = jno.np.pi
LAMBDA, K_TRUE, SIGMA_U, SIGMA_PHYS = 1.0, 2.0, 0.02, 0.05 # known diffusivity, the truth, sensor noise, physics scale
d = jno.Path(0.0, 0.0).line_to(1.0, 0.0).curve(size=0.02).domain()
x, _ = d.variable("interior")
x_np = np.asarray(d.context["interior"]).reshape(-1, 1)
u_obs = jnp.asarray(np.sin(π * x_np) + SIGMA_U * np.random.default_rng(0).normal(size=x_np.shape)) # u* = sin(πx)
f = (LAMBDA * π**2 + K_TRUE) * jno.np.sin(π * x) # the known forcing that makes u* the solution
# Phase 1: a surrogate fitted to the noisy sensors.
u_net = jno.nn(foundax.mlp(1, output_dim=1, hidden_dims=32, num_layers=3, key=jax.random.PRNGKey(0)))
u_net.optimizer(optax.adam(2e-3))
u_fit = u_net(x) * x * (1 - x) # hard u(0) = u(1) = 0
fit = jno.core([(u_fit - u_obs).mse])
fit.solve(5000)
u_hat, u_star = fit.eval([u_fit, jno.np.sin(π * x)])
fit_err = float(jnp.linalg.norm(u_hat - u_star) / jnp.linalg.norm(u_star))
print(f"surrogate rel-L2 vs sin(πx): {fit_err:.3e}")
# Phase 2: freeze the surrogate, then NUTS on k.
u_net.freeze()
k = jno.np.parameter((1,), name="k").initialize(jax.nn.initializers.constant(1.0))
k.bayesian(blackjax.nuts, step_size=1e-2, warmup=300, keep=600, num_chains=4, init_jitter=0.5)
u = (u_net(x) * x * (1 - x)).scalar.bind(x=x)
jno.core([((-LAMBDA * u.xx + k * u - f) / SIGMA_PHYS).mse]).solve(900) # -λ u'' + k u - f = 0
chain = k.posterior_samples # (num_chains, keep, 1)
mean, std = float(jnp.mean(chain)), float(jnp.std(chain))
lo, hi = (float(q) for q in jnp.quantile(chain.reshape(-1), jnp.array([0.05, 0.95])))
rhat, ess = (float(m(chain).reshape(-1)[0]) for m in (jno.bayesian.rhat, jno.bayesian.ess))
print(
f"k = {mean:.4f} ± {std:.4f} 90% CI = [{lo:.4f}, {hi:.4f}] truth = {K_TRUE} R-hat = {rhat:.4f} ESS = {ess:.0f}"
)
assert fit_err < 0.03, f"surrogate fit poor: rel-L2 = {fit_err:.3e}"
assert abs(mean - K_TRUE) / K_TRUE < 0.08, f"posterior-mean k off: {mean:.4f}"
assert rhat < 1.1, f"chains not mixed: R-hat = {rhat:.4f}"
assert ess > 100, f"effective sample size too low: {ess:.0f}"
assert lo <= K_TRUE <= hi, f"truth {K_TRUE} outside the 90% CI [{lo:.4f}, {hi:.4f}]"