Tutorials › Optimal Design and Model-Informed Dosing › Numerical Stability in Sparse-Data Posterior Computation

Bayesian Forecasting and Dose Adaptation · Tutorial 350 of 497

Numerical Stability in Sparse-Data Posterior Computation

You will learn practical checks and stable computations for nonlinear individual posteriors when sparse observations make numerical errors consequential.

Advanced 13 min read

What You'll Learn

  • Recognize underflow, overflow, cancellation, and scaling problems in posterior calculations.
  • Evaluate likelihoods and normalize posterior weights on the log scale.
  • Transform constrained parameters while accounting for the Jacobian.
  • Check analytic gradients against finite differences at multiple step sizes.
  • Distinguish numerical failure from genuine posterior uncertainty or weak identification.

Why Numerical Stability Matters

With sparse individual data, a posterior calculation may depend strongly on a few likelihood contributions and on the tails of the prior. A computation can therefore return a plausible-looking estimate even when intermediate values have underflowed, a parameter transformation was handled incorrectly, or a gradient is inaccurate. These are numerical failures, not evidence that the data support a precise individual parameter estimate.

The target is the individual posterior density, formed by multiplying the likelihood of the observed data by the prior density and normalizing. Numerical methods often work with its logarithm, because logarithms turn products into sums and avoid unnecessarily forming extremely small numbers. The introductory material on multimodal and boundary individual posteriors distinguishes posterior shape problems from numerical pathologies; here the focus is checking and stabilizing the computation itself.

Definition: For individual parameter vector \(\theta\), observations \(y\), and prior density \(p(\theta)\), the posterior density is \(p(\theta\mid y)=p(y\mid\theta)p(\theta)/p(y)\), where \(p(y)=\int p(y\mid\theta)p(\theta)\,d\theta\). The unnormalized log posterior is \(\ell(\theta)+\log p(\theta)\), where \(\ell(\theta)=\log p(y\mid\theta)\). Numerical stability means evaluating and optimizing or integrating this target with errors small enough not to materially change the result.

This formulation assumes that the likelihood and prior describe the intended data-generating and parameter models, that the posterior normalizing integral is finite, and that numerical evaluations use consistent units and parameter definitions. A stable algorithm cannot repair a misspecified observation model or create information absent from sparse data. It can, however, prevent arithmetic errors from masquerading as statistical conclusions.

Log-Scale Likelihoods and Normalization

For conditionally independent observations, the likelihood is a product of individual observation densities. If those densities are small, their product can underflow to zero even when each factor is representable. Instead calculate \(\ell(\theta)=\sum_i\log p(y_i\mid\theta)\). Constants may be omitted only when they do not depend on parameters being optimized; retain them when an absolute likelihood or model comparison requires them.

Key result: For real log values \(a_1,\ldots,a_K\), the log of their exponentiated sum can be evaluated as \(\log\sum_k e^{a_k}=a_{\max}+\log\sum_k e^{a_k-a_{\max}}\), where \(a_{\max}=\max_k a_k\). Every exponent in the second sum is at most zero, so this form avoids overflow and preserves relative contributions.

The identity follows by factoring the largest exponential out of the sum: \(\sum_k e^{a_k}=e^{a_{\max}}\sum_k e^{a_k-a_{\max}}\). Taking the logarithm gives the stated expression. Posterior weights from a grid, quadrature rule, or set of particles can be normalized in the same way: subtract the largest log weight, exponentiate the differences, and divide by their sum. This stabilizes arithmetic, but does not guarantee that a grid or particle approximation adequately represents the posterior.

Worked Example: Stable Normalization of Sparse Posterior Contributions

Suppose a hypothetical sparse-data calculation gives three quadrature contributions with log weights \(-1001\), \(-1003\), and \(-1010\). Directly exponentiating these values may produce extremely small numbers. Compute their normalized weights using the log-sum-exp approach.

The largest log weight is \(a_{\max}=-1001\). Subtracting it gives \(0,-2,-9\), so the unnormalized stable weights are \(1,e^{-2},e^{-9}\). Their sum is \(1+0.135335+0.00012341=1.135458\).

$$ w_1=\frac{1}{1.135458}=0.8807,\qquad w_2=\frac{0.135335}{1.135458}=0.1192,\qquad w_3=\frac{0.00012341}{1.135458}=0.0001087. $$

The weights sum to approximately 1, allowing for rounding. The first contribution carries about 88.1% of the normalized quadrature weight and the third about 0.0109%. These are numerical weights for the specified approximation, not probabilities that the associated parameter values are true. If all log weights were instead exponentiated before normalization, finite-precision arithmetic could return zeros and lose the relative information.

Transformations for Constrained Parameters

Many pharmacokinetic parameters, including clearance and volume, must be positive. A common strategy is to calculate on an unconstrained scale, such as \(\eta=\log\theta\), and recover the original parameter as \(\theta=e^\eta\). This prevents an optimizer from proposing negative values and can improve scaling when plausible parameter values span orders of magnitude.

The density transformation must be handled correctly. If the target is a density with respect to \(\theta\), then the density with respect to \(\eta\) is \(p_\eta(\eta\mid y)=p_\theta(e^\eta\mid y)e^\eta\). Thus the log density in \(\eta\) includes the Jacobian term \(\eta\). Omitting it changes the density being integrated or sampled. A transformation also changes the numerical location of a density mode; a mode is a feature of a density relative to its stated coordinate measure.

Worked Example: Transforming a Positive Clearance and Its Gradient

Consider a hypothetical single log-concentration observation \(y=\log(2.5)=0.916291\). Let \(\theta>0\) be a clearance-like parameter, let the observation model be \(Y\mid\theta\sim N(m(\theta),0.2^2)\), with \(m(\theta)=\log(10)-0.3\theta\), and let the prior on \(\theta\) be exponential with rate \(0.2\). Evaluate the log-posterior derivative on \(\eta=\log\theta\) at \(\eta=\log 2\), so \(\theta=2\).

At \(\theta=2\), the predicted mean is \(m=\log(10)-0.3(2)=2.302585-0.6=1.702585\), and the residual is \(r=y-m=0.916291-1.702585=-0.786294\). Since \(d\theta/d\eta=\theta\), the mean derivative is \(dm/d\eta=-0.3\theta=-0.6\). The log likelihood, apart from constants, is \(\ell=-r^2/(2(0.2)^2)\). Differentiating, with \(dr/d\eta=-dm/d\eta\), gives \(\frac{d\ell}{d\eta}=r\frac{dm}{d\eta}/(0.2)^2\).

$$ \frac{d\ell}{d\eta} =\frac{(-0.786294)(-0.6)}{0.04} =11.7944. $$

The log prior on the original scale is \(\log(0.2)-0.2\theta\). After transformation, its log density includes the Jacobian: \(\log(0.2)-0.2e^\eta+\eta\). Its derivative is \(1-0.2e^\eta\), which at \(\theta=2\) equals \(0.6\). The full transformed log-posterior derivative is therefore \(11.7944+0.6=12.3944\). Omitting the Jacobian would give a prior derivative of \(-0.4\), targeting a different transformed density.

Gradient Checks and a Finite-Difference Derivation

Gradient-based optimization and sampling methods can fail silently if an analytic gradient is wrong. A finite-difference check compares the implemented derivative with a derivative estimated from nearby evaluations of the same log target. For a scalar function \(g(\eta)\), the central-difference estimate is \([g(\eta+h)-g(\eta-h)]/(2h)\). It is generally more accurate than a one-sided difference for a smooth function because the leading first-order error terms cancel.

Worked Example: Checking a Nonlinear Likelihood Derivative

Use the same hypothetical observation and normal error scale as above, but define \(\eta\) as a multiplicative perturbation of the nominal parameter value 2: \(\theta=2\eta\). At \(\eta=1\), \(m(\eta)=\log(10)-0.3(2\eta)\). The residual is still \(-0.786294\), and \(dm/d\eta=-0.6\). Check the likelihood derivative numerically with \(h=0.001\).

The analytic derivative is \(\ell'(\eta)=r\,m'(\eta)/(0.2)^2=(-0.786294)(-0.6)/0.04=11.7944\). At \(\eta=1.001\), \(m=1.701985\), \(r=-0.785694\), and \(\ell(1.001)=-(-0.785694)^2/0.08\approx-7.7164\). At \(\eta=0.999\), \(m=1.703185\), \(r=-0.786894\), and \(\ell(0.999)=-(-0.786894)^2/0.08\approx-7.7400\).

$$ \frac{\ell(1.001)-\ell(0.999)}{2(0.001)} \approx \frac{-7.7164-(-7.7400)}{0.002} =11.8. $$

This agrees with the analytic value to the displayed precision. A useful check repeats the calculation with more than one step size: a step that is too large has truncation error, while a step that is too small can be dominated by rounding error. For a vector parameter, check each component and, where practical, compare directional derivatives along several scaled directions.

Gradient-check principle: Compare analytic and numerical derivatives of the same scalar target, in the same parameterization and with the same constants and transformations. A discrepancy is a prompt to inspect the model, derivatives, units, and step size; it is not resolved merely by increasing optimizer iterations.

Diagnostics, Failure Modes, and Alternatives

Numerical diagnostics should be interpreted alongside statistical diagnostics. A posterior can be broad because the data are sparse; that is not itself numerical instability. Conversely, a sharply concentrated answer is not reassuring if it changes materially with arithmetic precision, starting values, parameter scaling, or a modest change in integration resolution.

  • Underflow or overflow: Likelihood products become zero, or exponentials become infinite. Evaluate sums of log densities and use log-sum-exp for sums of exponentials.
  • Unstable subtraction: Nearly equal large numbers are subtracted, losing significant digits. Reformulate the expression algebraically or use a numerically stable library function.
  • Invalid parameter proposals: A proposed negative value for a positive parameter can make the model undefined. Use a suitable transformation or a constrained method, and verify that the transformed target includes the required Jacobian.
  • Gradient disagreement: Analytic and finite-difference derivatives differ beyond expected numerical tolerance. Check signs, chain-rule factors, the observation likelihood, and whether the prior is expressed on the same scale.
  • Scale imbalance: Parameters with very different magnitudes can make optimization poorly conditioned. Rescale parameters and inspect whether results are stable under reasonable alternative scales.
  • False convergence: An optimizer reports convergence while gradients remain appreciable or results depend strongly on initialization. Examine gradient norms and objective values from multiple starts; a convergence flag alone does not establish a reliable posterior calculation.

Log-scale evaluation is usually preferable to direct likelihood multiplication. A log transformation is useful for positive parameters, while a constrained optimizer may be preferable when transformations make the posterior geometry difficult. Automatic differentiation can reduce hand-coded derivative errors, but it still requires checks against independent calculations: it differentiates the programmed function, including any programming mistake. Higher precision may help diagnose rounding problems, but it does not fix an incorrect model, omitted Jacobian, or inadequate approximation.

Sparse observations make these checks especially important because a small numerical error in a likelihood or gradient can shift an individual posterior noticeably. Yet numerical stability has limits: it cannot make weakly identified parameters precise, ensure that a posterior approximation explores every relevant region, or validate the clinical assumptions behind a dose forecast. The practical goal is a calculation whose results are reproducible under justified numerical refinements and whose uncertainty remains visible.

Common Pitfall

A frequent mistake is to exponentiate each log likelihood, multiply the resulting values, and conclude that the posterior is zero when a computer underflows. The correction is to retain the log target, add log likelihood and log prior contributions, and use log-sum-exp when normalizing. Another common mistake is to transform a positive parameter but omit the Jacobian. The correction is to identify the density's coordinate scale explicitly and include the Jacobian when changing the density's variable. Neither correction substitutes for checking that the model and approximation are appropriate.

Check Your Understanding

Answer each question, then compare your reasoning with the solutions below.

  1. Why can multiplying several valid observation likelihoods result in a computed value of zero?
  2. For log weights \(-50\) and \(-52\), what stable unnormalized weights result after subtracting the maximum?
  3. If \(\theta=e^\eta\), what Jacobian term is added to the log density when changing from a density in \(\theta\) to one in \(\eta\)?
  4. What does disagreement between an analytic gradient and a central-difference estimate indicate, and what should be checked first?
  5. Does agreement of a gradient check prove that a sparse-data posterior is statistically well identified? Explain.

Solutions. (1) Each likelihood can be small, and their product can fall below the smallest representable positive number even though the factors are nonzero. Summing their logarithms avoids forming that product. (2) Subtracting \(-50\) gives \(0\) and \(-2\), so the stable unnormalized weights are \(1\) and \(e^{-2}\approx0.1353\). (3) Since \(d\theta/d\eta=e^\eta\), the log-Jacobian is \(\eta\). (4) It indicates a possible derivative, implementation, scale, or finite-difference step-size problem; check that both calculations use the same target and parameterization, then inspect chain-rule factors and repeat with reasonable step sizes. (5) No. It supports the correctness of a local derivative calculation, but a posterior may remain broad or poorly identified because the observations contain limited information.

Clinical Biostats