Shinylive Apps for Statistical Computation
    • All Apps

    • Inverse CDF Method for Generating Random Numbers
    • Newton-Raphson for the Cauchy Location Likelihood
    • Safeguarded Newton-Raphson for Logistic Regression
    • Gradient-Based Methods for Minimizing Test Functions
    • Gradient-Based Methods for Fitting a Gaussian Neural Network
    • Gradient-Based Methods for Fitting a Poisson Neural Network
    • Nelder–Mead Method for Derivative-Free Minimization
    • EM Algorithm for a Normal Mixture
    • EM Algorithm for a Bivariate Normal Mixture
    • Conjugate Updating for Bayesian Posteriors
    • Quadrature and Laplace Approximation for the Marginal Likelihood of a Normal Mean
    • Midpoint, Laplace and Laplace-Adapted Midpoint Rules for the Marginal Likelihood of Normal Data
    • Rejection Sampling with a Laplace Envelope for the Normal Distribution
    • Rejection Sampling with a Cauchy Envelope for the Gamma Distribution
    • Adaptive Rejection Sampling for the Truncated Normal Distribution
    • Adaptive Rejection Sampling on log X for the Truncated Gamma Distribution
    • Importance Sampling for a Bimodal Distribution (Failure Example)
    • Importance Sampling with a Normal Proposal for Student-t Probabilities
    • Gibbs Sampling for the Cauchy Model with Unknown Location and Scale
    • MCMC Simulators by Chi Feng (external)

Quadrature and Laplace Approximation for the Marginal Likelihood of a Normal Mean

Author

Longhai Li

Published

November 24, 2026

#| '!! shinylive warning !!': |
#|   shinylive does not work in self-contained HTML documents.
#|   Please set `embed-resources: false` in your metadata.
#| standalone: true
#| viewerHeight: 900
library(shiny)

### renderPlot replacement: Safari 27 (WebKit) cannot hold the call stack of
### shiny::renderPlot in webR ("Maximum call stack size exceeded"), so draw with
### renderImage instead, which nests about 45 fewer R calls
renderPlot <- function(expr, width = "auto", height = "auto", res = 72, ...,
                       env = parent.frame(), quoted = FALSE) {
    func <- shiny::exprToFunction(expr, env, quoted)
    shiny::renderImage({
        info <- shiny::getCurrentOutputInfo()
        w  <- if (is.numeric(width))  width  else info$width()
        h  <- if (is.numeric(height)) height else info$height()
        shiny::req(w > 0, h > 0)
        pr <- shiny::getDefaultReactiveDomain()$clientData$pixelratio
        if (is.null(pr)) pr <- 1
        f   <- tempfile(fileext = ".png")
        dev <- shiny:::startPNG(f, w * pr, h * pr, res = res * pr)
        on.exit(grDevices::dev.off(dev), add = TRUE)
        grDevices::dev.control(displaylist = "enable")
        v <- withVisible(func())
        if (v$visible) print(v$value)
        list(src = f, contentType = "image/png", width = w, height = h,
             coordmap = shiny:::getCoordmap(v$value, w * pr, h * pr, res * pr))
    }, deleteFile = TRUE)
}

ui <- fluidPage(
    wellPanel(
        fluidRow(
            column(6, sliderInput("mu_hat", "mu (data location)", min = -5, max = 25,
                                  value = 8, step = 0.5)),
            column(6, sliderInput("n_pts", "number of grid points in u (over 0 to 1)",
                                  min = 2, max = 25, value = 9, step = 1)))
    ),
    tags$style("#tab table { font-size: 85%; }"),
    fluidRow(
        column(9,
            fluidRow(
                column(6, plotOutput("mu_logit", height = "340px")),
                column(6, plotOutput("u_logit", height = "340px"))),
            fluidRow(
                column(6, plotOutput("mu_laplace", height = "340px")),
                column(6, plotOutput("u_laplace", height = "340px")))),
        column(3,
            h5("log P(y) by each method"),
            tableOutput("tab"))
    )
)

server <- function(input, output, session) {

    n_eff <- 3; sigma_prior <- 5                    # likelihood as if 3 obs, sigma = 1; prior N(0, 5^2)

    ### everything that depends on mu_hat: the kernel z, the true log P(y), and the two grid transforms
    setup <- function(mu_hat) {
        log_z <- function(mu) dnorm(mu_hat, mu, 1 / sqrt(n_eff), log = TRUE) +
            dnorm(mu, 0, sigma_prior, log = TRUE)
        z <- function(mu) exp(log_z(mu))
        ### normal-normal conjugate kernel: the exact log marginal likelihood, mu_hat ~ N(0, 1/n_eff + sigma_prior^2)
        ### (integrate() is no longer reliable once the narrow peak lies far out)
        log_marlik <- dnorm(mu_hat, 0, sqrt(1 / n_eff + sigma_prior^2), log = TRUE)
        ### Laplace approximation for THIS mu_hat: its mode and se define the second transform
        op <- nlm(function(mu) -log_z(mu), p = mu_hat, hessian = TRUE)
        m  <- op$estimate
        se <- 1 / sqrt(op$hessian[1, 1])
        log_lap <- -op$minimum + 0.5 * log(2 * pi) + log(se)   # Laplace approximation: log z(mode) + log of sqrt(2 pi) se
        list(z = z, log_z = log_z, log_marlik = log_marlik, log_lap = log_lap,
             logit = list(q = qlogis, p = plogis, d = dlogis,
                          lab = expression(u == 1 / (1 + e^-mu)),
                          main = "Logistic grid: mu = logit(u)"),
             laplace = list(q = function(u) qnorm(u, m, se), p = function(mu) pnorm(mu, m, se),
                            d = function(mu) dnorm(mu, m, se),
                            lab = expression(u == Phi((mu - hat(mu)[L]) / s[L])),
                            main = "Laplace-normalized grid: mu = mode + se * qnorm(u)"))
    }

    log_sum_exp <- function(lx) { m <- max(lx); m + log(sum(exp(lx - m))) }

    ### the midpoint rule in u with n points, mapped back to mu by the transform q; d = du/dmu
    log_midpoint <- function(S, tr, n) {
        u_pts <- (seq_len(n) - 0.5) / n
        mu_pts <- tr$q(u_pts)
        log_sum_exp(S$log_z(mu_pts) - log(tr$d(mu_pts))) + log(1 / n)
    }

    ### the grid is the midpoint rule in u, mapped back to mu by the transform q; d = du/dmu
    mu_plot <- function(type) {
        S <- setup(input$mu_hat); tr <- S[[type]]
        mu_grid <- seq(-20, 20, length.out = 500)          # fixed x-axis
        u_pts   <- (seq_len(input$n_pts) - 0.5) / input$n_pts
        mu_pts  <- tr$q(u_pts)
        log_quad <- log_midpoint(S, tr, input$n_pts)

        par(mar = c(4, 4, 2, 4))
        plot(mu_grid, S$z(mu_grid), type = "l", lwd = 3, col = "firebrick", main = tr$main,
             xlab = expression(mu), ylab = expression(z(mu) == pi(mu) * L(mu)))
        polygon(c(mu_grid, rev(mu_grid)), c(S$z(mu_grid), rep(0, length(mu_grid))),
                col = adjustcolor("firebrick", 0.15), border = NA)
        segments(mu_pts, 0, mu_pts, S$z(mu_pts), col = "gray30", lwd = 1.5)
        points(mu_pts, S$z(mu_pts), pch = 19, col = "gray30")

        par(new = TRUE)
        plot(mu_grid, tr$p(mu_grid), type = "l", lwd = 3, col = "steelblue",
             axes = FALSE, xlab = "", ylab = "", ylim = c(0, 1))
        axis(4, col.axis = "steelblue", col.ticks = "steelblue")
        mtext(tr$lab, side = 4, line = 2.5, col = "steelblue")

        guide_col <- adjustcolor("gray50", 0.6)
        segments(mu_pts, 0, mu_pts, u_pts, col = guide_col, lty = 3)
        segments(mu_pts, u_pts, max(mu_grid), u_pts, col = guide_col, lty = 3)
        points(mu_pts, u_pts, pch = 19, col = "gray30")

        legend("topleft", bty = "n", lwd = c(3, 3, NA, NA), col = c("firebrick", "steelblue", NA, NA),
               cex = 0.85,
               legend = c(expression(z(mu) == pi(mu) * L(mu)), tr$lab,
                          as.expression(bquote("true"~log~P(y) == .(round(S$log_marlik, 3)))),
                          as.expression(bquote("quadrature"~log~P(y) == .(round(log_quad, 3))))))
    }

    ### the function the midpoint rule integrates over u: g(u) = z(q(u)) / d(q(u)), with rectangles
    u_plot <- function(type) {
        S <- setup(input$mu_hat); tr <- S[[type]]
        g <- function(u) { mu <- tr$q(u); exp(S$log_z(mu) - log(tr$d(mu))) }
        n      <- input$n_pts
        h      <- 1 / n
        u_pts  <- (seq_len(n) - 0.5) / n
        g_pts  <- g(u_pts)
        u_fine <- seq(0.0005, 0.9995, length.out = 2000)
        g_fine <- g(u_fine)
        true_val <- exp(S$log_marlik)                      # the area is the same for every transform
        quad_val <- sum(g_pts) * h

        par(mar = c(4, 4, 2, 1))
        plot(u_fine, g_fine, type = "l", lwd = 3, col = "firebrick", main = "Integrand in u",
             ylim = c(0, max(g_fine, g_pts) * 1.45), xlab = expression(u),   # head room for the legend
             ylab = expression(g(u) == z(mu(u)) / (du / dmu)))
        rect(u_pts - h / 2, 0, u_pts + h / 2, g_pts,
             col = adjustcolor("gray50", 0.3), border = "gray30")
        points(u_pts, g_pts, pch = 19, col = "gray30")
        legend("topright", bty = "n", lwd = c(3, NA, NA), col = c("firebrick", NA, NA), cex = 0.85,
               legend = c(expression(g(u)),
                          as.expression(bquote("true area" == .(signif(true_val, 4)))),
                          as.expression(bquote("midpoint rule" == .(signif(quad_val, 4))))))
    }

    output$tab <- renderTable({
        S <- setup(input$mu_hat); n <- input$n_pts
        est <- c(S$log_marlik, S$log_lap, log_midpoint(S, S$logit, n), log_midpoint(S, S$laplace, n))
        data.frame(
            Method = c("True", "Laplace", sprintf("Logistic grid, n = %d", n),
                       sprintf("Laplace grid, n = %d", n)),
            Evals = c("-", "1", n, n),
            `log P(y)` = sprintf("%.3f", est),
            Error = c("", sprintf("%.3f", est[-1] - est[1])),
            check.names = FALSE)
    }, striped = TRUE, align = "lrrr")

    output$mu_logit   <- renderPlot(mu_plot("logit"))
    output$u_logit    <- renderPlot(u_plot("logit"))
    output$mu_laplace <- renderPlot(mu_plot("laplace"))
    output$u_laplace  <- renderPlot(u_plot("laplace"))
}

shinyApp(ui, server)

About the app

Shows how a fixed quadrature grid can miss the posterior mode entirely, so that the computed marginal likelihood is badly wrong. The app models a single unknown mean \(\mu\).

The problem. The data enter through a normal likelihood \(L(\mu)=N(\hat\mu\mid\mu,1/3)\), the likelihood of three observations with unit variance whose sample mean is the slider value \(\hat\mu\) (“data location”). The prior is \(\pi(\mu)=N(0,5^2)\). The marginal likelihood is \[P(y)=\int_{-\infty}^{\infty} z(\mu)\,d\mu,\qquad z(\mu)=\pi(\mu)L(\mu).\] To integrate over the whole real line with a fixed grid, the app maps \(\mu\) to the unit interval by \(u=1/(1+e^{-\mu})\), so \(\mu=\text{logit}(u)\), and applies the midpoint rule with \(n\) equally spaced points \(u_i=(i-0.5)/n\) on \((0,1)\): \[P(y)=\int_0^1 \frac{z(\text{logit}\,u)}{u(1-u)}\,du\;\approx\;\frac1n\sum_{i=1}^n \frac{z(\text{logit}\,u_i)}{u_i(1-u_i)}.\] The grid is fixed in advance, without looking at where the posterior mass is.

The Laplace-normalized grid. The second rule uses the same midpoint points \(u_i=(i-0.5)/n\) but a different map between \(u\) and \(\mu\), centred and scaled by the Laplace approximation of the posterior, \(\hat\mu_L\) (the mode of \(z\)) and \(s_L=\big(-\partial^2\log z(\hat\mu_L)\big)^{-1/2}\), recomputed for the current \(\hat\mu\): \(u=\Phi\big((\mu-\hat\mu_L)/s_L\big)\), so \(\mu_i=\hat\mu_L+s_L\,\Phi^{-1}(u_i)\) and \(du/d\mu=\varphi\big((\mu-\hat\mu_L)/s_L\big)/s_L\), where \(\varphi\) is the standard normal density. Changing variables gives \[P(y)=\int_0^1 \frac{z(\mu(u))}{\varphi\big((\mu(u)-\hat\mu_L)/s_L\big)/s_L}\,du\;\approx\;\frac1n\sum_{i=1}^n \frac{s_L\,z(\mu_i)}{\varphi\big(\Phi^{-1}(u_i)\big)}.\] Each term is the posterior kernel at the grid point divided by the Laplace (normal) density at that point, i.e. an importance-sampling-style ratio. Because \(z\) is close to \(\varphi\)-shaped around \(\hat\mu_L\), this ratio is nearly constant in \(u\) and the rule is accurate with few points. With the logistic map the same formula holds with \(du/d\mu=u(1-u)\) in place of the normal density.

What the plots show. Two grids are compared on the same data, one per row; the sliders are shared. In each row the left plot shows \(z(\mu)\) and the grid in \(\mu\), and the right plot shows the function the rule actually integrates over \(u\), with the midpoint rectangles.

  • Top row, logistic grid. \(\mu=\text{logit}(u)\), fixed in advance whatever the data. Left: \(z(\mu)\) (red), the map \(u=1/(1+e^{-\mu})\) (blue), and the grid points \(u_i\) with the \(\mu_i=\text{logit}(u_i)\) they correspond to. Equally spaced \(u_i\) are densely packed near \(\mu=0\) and spread very thinly far from it. Right: \(g(u)=z(\text{logit}\,u)/\{u(1-u)\}\); the gray rectangles are the midpoint rule, and their total area is the estimate.
  • Bottom row, Laplace-normalized grid. The transform is centred and scaled by the Laplace approximation recomputed for the current \(\hat\mu\): \(u=\Phi\big((\mu-\hat\mu_L)/s_L\big)\), where \(\hat\mu_L\) is the posterior mode and \(s_L\) the inverse square root of the curvature there. The midpoint grid in \(u\) is therefore uniform in Laplace-normalized space, so it concentrates where the posterior mass lives. Right: \(g(u)=z(\mu(u))\big/\,\phi\big((\mu(u)-\hat\mu_L)/s_L\big)\big/s_L\), which is nearly flat, so a few rectangles already give the right area.

What to try. At \(\hat\mu=0\) both grids work: the posterior mass sits under the logistic grid, and the two estimates agree with the true value. As \(\hat\mu\) moves to 8 or 20, the logistic grid fails: the mass is squeezed into a tiny interval of \(u\) near 1 that falls between grid points, so the rule sees essentially nothing and the estimate is wrong by many orders of magnitude, however many points you add. The Laplace-normalized grid follows the posterior wherever it sits, and its estimate stays close to the true value. The lesson is that a fixed grid that ignores the location of the mode can miss it, and that centring and scaling the grid with the Laplace approximation fixes this.

NoteR source for this app
library(shiny)

### renderPlot replacement: Safari 27 (WebKit) cannot hold the call stack of
### shiny::renderPlot in webR ("Maximum call stack size exceeded"), so draw with
### renderImage instead, which nests about 45 fewer R calls
renderPlot <- function(expr, width = "auto", height = "auto", res = 72, ...,
                       env = parent.frame(), quoted = FALSE) {
    func <- shiny::exprToFunction(expr, env, quoted)
    shiny::renderImage({
        info <- shiny::getCurrentOutputInfo()
        w  <- if (is.numeric(width))  width  else info$width()
        h  <- if (is.numeric(height)) height else info$height()
        shiny::req(w > 0, h > 0)
        pr <- shiny::getDefaultReactiveDomain()$clientData$pixelratio
        if (is.null(pr)) pr <- 1
        f   <- tempfile(fileext = ".png")
        dev <- shiny:::startPNG(f, w * pr, h * pr, res = res * pr)
        on.exit(grDevices::dev.off(dev), add = TRUE)
        grDevices::dev.control(displaylist = "enable")
        v <- withVisible(func())
        if (v$visible) print(v$value)
        list(src = f, contentType = "image/png", width = w, height = h,
             coordmap = shiny:::getCoordmap(v$value, w * pr, h * pr, res * pr))
    }, deleteFile = TRUE)
}

ui <- fluidPage(
    wellPanel(
        fluidRow(
            column(6, sliderInput("mu_hat", "mu (data location)", min = -5, max = 25,
                                  value = 8, step = 0.5)),
            column(6, sliderInput("n_pts", "number of grid points in u (over 0 to 1)",
                                  min = 2, max = 25, value = 9, step = 1)))
    ),
    tags$style("#tab table { font-size: 85%; }"),
    fluidRow(
        column(9,
            fluidRow(
                column(6, plotOutput("mu_logit", height = "340px")),
                column(6, plotOutput("u_logit", height = "340px"))),
            fluidRow(
                column(6, plotOutput("mu_laplace", height = "340px")),
                column(6, plotOutput("u_laplace", height = "340px")))),
        column(3,
            h5("log P(y) by each method"),
            tableOutput("tab"))
    )
)

server <- function(input, output, session) {

    n_eff <- 3; sigma_prior <- 5                    # likelihood as if 3 obs, sigma = 1; prior N(0, 5^2)

    ### everything that depends on mu_hat: the kernel z, the true log P(y), and the two grid transforms
    setup <- function(mu_hat) {
        log_z <- function(mu) dnorm(mu_hat, mu, 1 / sqrt(n_eff), log = TRUE) +
            dnorm(mu, 0, sigma_prior, log = TRUE)
        z <- function(mu) exp(log_z(mu))
        ### normal-normal conjugate kernel: the exact log marginal likelihood, mu_hat ~ N(0, 1/n_eff + sigma_prior^2)
        ### (integrate() is no longer reliable once the narrow peak lies far out)
        log_marlik <- dnorm(mu_hat, 0, sqrt(1 / n_eff + sigma_prior^2), log = TRUE)
        ### Laplace approximation for THIS mu_hat: its mode and se define the second transform
        op <- nlm(function(mu) -log_z(mu), p = mu_hat, hessian = TRUE)
        m  <- op$estimate
        se <- 1 / sqrt(op$hessian[1, 1])
        log_lap <- -op$minimum + 0.5 * log(2 * pi) + log(se)   # Laplace approximation: log z(mode) + log of sqrt(2 pi) se
        list(z = z, log_z = log_z, log_marlik = log_marlik, log_lap = log_lap,
             logit = list(q = qlogis, p = plogis, d = dlogis,
                          lab = expression(u == 1 / (1 + e^-mu)),
                          main = "Logistic grid: mu = logit(u)"),
             laplace = list(q = function(u) qnorm(u, m, se), p = function(mu) pnorm(mu, m, se),
                            d = function(mu) dnorm(mu, m, se),
                            lab = expression(u == Phi((mu - hat(mu)[L]) / s[L])),
                            main = "Laplace-normalized grid: mu = mode + se * qnorm(u)"))
    }

    log_sum_exp <- function(lx) { m <- max(lx); m + log(sum(exp(lx - m))) }

    ### the midpoint rule in u with n points, mapped back to mu by the transform q; d = du/dmu
    log_midpoint <- function(S, tr, n) {
        u_pts <- (seq_len(n) - 0.5) / n
        mu_pts <- tr$q(u_pts)
        log_sum_exp(S$log_z(mu_pts) - log(tr$d(mu_pts))) + log(1 / n)
    }

    ### the grid is the midpoint rule in u, mapped back to mu by the transform q; d = du/dmu
    mu_plot <- function(type) {
        S <- setup(input$mu_hat); tr <- S[[type]]
        mu_grid <- seq(-20, 20, length.out = 500)          # fixed x-axis
        u_pts   <- (seq_len(input$n_pts) - 0.5) / input$n_pts
        mu_pts  <- tr$q(u_pts)
        log_quad <- log_midpoint(S, tr, input$n_pts)

        par(mar = c(4, 4, 2, 4))
        plot(mu_grid, S$z(mu_grid), type = "l", lwd = 3, col = "firebrick", main = tr$main,
             xlab = expression(mu), ylab = expression(z(mu) == pi(mu) * L(mu)))
        polygon(c(mu_grid, rev(mu_grid)), c(S$z(mu_grid), rep(0, length(mu_grid))),
                col = adjustcolor("firebrick", 0.15), border = NA)
        segments(mu_pts, 0, mu_pts, S$z(mu_pts), col = "gray30", lwd = 1.5)
        points(mu_pts, S$z(mu_pts), pch = 19, col = "gray30")

        par(new = TRUE)
        plot(mu_grid, tr$p(mu_grid), type = "l", lwd = 3, col = "steelblue",
             axes = FALSE, xlab = "", ylab = "", ylim = c(0, 1))
        axis(4, col.axis = "steelblue", col.ticks = "steelblue")
        mtext(tr$lab, side = 4, line = 2.5, col = "steelblue")

        guide_col <- adjustcolor("gray50", 0.6)
        segments(mu_pts, 0, mu_pts, u_pts, col = guide_col, lty = 3)
        segments(mu_pts, u_pts, max(mu_grid), u_pts, col = guide_col, lty = 3)
        points(mu_pts, u_pts, pch = 19, col = "gray30")

        legend("topleft", bty = "n", lwd = c(3, 3, NA, NA), col = c("firebrick", "steelblue", NA, NA),
               cex = 0.85,
               legend = c(expression(z(mu) == pi(mu) * L(mu)), tr$lab,
                          as.expression(bquote("true"~log~P(y) == .(round(S$log_marlik, 3)))),
                          as.expression(bquote("quadrature"~log~P(y) == .(round(log_quad, 3))))))
    }

    ### the function the midpoint rule integrates over u: g(u) = z(q(u)) / d(q(u)), with rectangles
    u_plot <- function(type) {
        S <- setup(input$mu_hat); tr <- S[[type]]
        g <- function(u) { mu <- tr$q(u); exp(S$log_z(mu) - log(tr$d(mu))) }
        n      <- input$n_pts
        h      <- 1 / n
        u_pts  <- (seq_len(n) - 0.5) / n
        g_pts  <- g(u_pts)
        u_fine <- seq(0.0005, 0.9995, length.out = 2000)
        g_fine <- g(u_fine)
        true_val <- exp(S$log_marlik)                      # the area is the same for every transform
        quad_val <- sum(g_pts) * h

        par(mar = c(4, 4, 2, 1))
        plot(u_fine, g_fine, type = "l", lwd = 3, col = "firebrick", main = "Integrand in u",
             ylim = c(0, max(g_fine, g_pts) * 1.45), xlab = expression(u),   # head room for the legend
             ylab = expression(g(u) == z(mu(u)) / (du / dmu)))
        rect(u_pts - h / 2, 0, u_pts + h / 2, g_pts,
             col = adjustcolor("gray50", 0.3), border = "gray30")
        points(u_pts, g_pts, pch = 19, col = "gray30")
        legend("topright", bty = "n", lwd = c(3, NA, NA), col = c("firebrick", NA, NA), cex = 0.85,
               legend = c(expression(g(u)),
                          as.expression(bquote("true area" == .(signif(true_val, 4)))),
                          as.expression(bquote("midpoint rule" == .(signif(quad_val, 4))))))
    }

    output$tab <- renderTable({
        S <- setup(input$mu_hat); n <- input$n_pts
        est <- c(S$log_marlik, S$log_lap, log_midpoint(S, S$logit, n), log_midpoint(S, S$laplace, n))
        data.frame(
            Method = c("True", "Laplace", sprintf("Logistic grid, n = %d", n),
                       sprintf("Laplace grid, n = %d", n)),
            Evals = c("-", "1", n, n),
            `log P(y)` = sprintf("%.3f", est),
            Error = c("", sprintf("%.3f", est[-1] - est[1])),
            check.names = FALSE)
    }, striped = TRUE, align = "lrrr")

    output$mu_logit   <- renderPlot(mu_plot("logit"))
    output$u_logit    <- renderPlot(u_plot("logit"))
    output$mu_laplace <- renderPlot(mu_plot("laplace"))
    output$u_laplace  <- renderPlot(u_plot("laplace"))
}

shinyApp(ui, server)

This app accompanies Numerical Quadrature in the book.