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)

Importance Sampling for a Bimodal Distribution (Failure Example)

Author

Longhai Li

Published

November 27, 2026

#| '!! shinylive warning !!': |
#|   shinylive does not work in self-contained HTML documents.
#|   Please set `embed-resources: false` in your metadata.
#| standalone: true
#| viewerHeight: 790
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)
}
library(latex2exp)

d <- 5

log_f <- function(th, d) {
    a <- dnorm(th, -d, log = TRUE); b <- dnorm(th, d, log = TRUE)
    m <- pmax(a, b)
    m + log(exp(a - m) + exp(b - m)) - log(2)
}

log_Ew2 <- function(d, sg) {
    A <- 2 - 1 / sg^2
    if (A <= 0) return(Inf)
    lterm <- function(a, b) {
        m <- (a + b) / 2
        B <- 2 * m + d / sg^2
        C <- 2 * m^2 - d^2 / sg^2
        dnorm(a, b, sqrt(2), log = TRUE) + log(sg) + 0.5 * log(2) +
            0.5 * log(2 * pi / A) - 0.5 * (C - B^2 / A)
    }
    lv <- c(lterm(-d, -d), log(2) + lterm(-d, d), lterm(d, d))
    m  <- max(lv)
    m + log(sum(exp(lv - m))) - log(4)
}

ui <- fluidPage(
    wellPanel(
        fluidRow(
            column(4, sliderInput("sg", HTML("proposal sd &sigma;"), min = 0.25, max = 8,
                                  value = 1, step = 0.05)),
            column(4, sliderInput("S", "sample size  S", min = 100, max = 20000,
                                  value = 2000, step = 100)),
            column(2, numericInput("seed", "seed", value = 11, min = 1, step = 1)),
            column(2, br(), actionButton("new", "New sample")))
    ),
    fluidRow(
        column(8, plotOutput("panels", height = "600px")),
        column(4,
            tags$style("#tab td, #tab th { white-space: nowrap; }"),
            h5("Estimates"),
            tableOutput("tab"))
    )
)

server <- function(input, output) {

    sim <- reactive({
        S  <- as.integer(input$S); sg <- input$sg
        set.seed(input$seed + 1000 * input$new)

        th   <- rnorm(S, -d, sg)
        logw <- log_f(th, d) - dnorm(th, -d, sg, log = TRUE)
        mx   <- max(logw); v <- exp(logw - mx)
        wn   <- v / mean(v)                  # normalized weights, mean 1

        list(th = th, wn = wn, S = S, sg = sg,
             Chat = mean(v) * exp(mx),
             se   = sd(v) / sqrt(S) * exp(mx),
             ess  = S / mean(wn^2),
             Ehat = mean(wn * th),
             lsum = mx + log(mean(v)),
             ess_x = 100 * exp(-log_Ew2(d, sg)))
    })

    output$panels <- renderPlot({
        s  <- sim(); th <- s$th; sg <- s$sg
        xr <- c(-15, 15)                                  # fixed x-axis
        xs <- seq(xr[1], xr[2], length.out = 1000)
        fx <- exp(log_f(xs, d)); gx <- dnorm(xs, -d, sg)
        lwc <- log_f(xs, d) - dnorm(xs, -d, sg, log = TRUE) - s$lsum

        layout(matrix(1:2, 2), heights = c(3, 2))

        par(mar = c(0.4, 5, 3, 1))
        plot(xs, fx, type = "n", ylim = c(0, max(fx, gx) * 1.1), xlim = xr, xaxt = "n",
             xlab = "", ylab = "density",
             main = "bimodal target and a proposal centred on one mode")
        lines(xs, fx, lwd = 4, col = "red")
        lines(xs, gx, lwd = 3, col = "grey60")
        rug(th, col = adjustcolor("grey45", 0.35))
        legend("top", bty = "n", cex = 1.05, text.col = "navy",
               lwd = c(4, 3), col = c("red", "grey60"),
               legend = TeX(c(
                   r"(target $f$)",
                   sprintf(r"(proposal $g$, sd $= %.2f$)", sg))))

        par(mar = c(4.5, 5, 0.4, 1))
        wn <- s$wn
        wl <- c(min(wn) / 5, max(wn) * 5)
        plot(th, wn, type = "n", log = "y", ylim = wl, xlim = xr,
             xlab = expression(theta), ylab = "normalized weight, mean 1 (log scale)")
        lines(xs, exp(pmin(lwc, 700)), lwd = 2, col = "grey25")
        segments(th, wl[1], th, wn, col = adjustcolor("grey45", 0.5))
        abline(h = 1, lty = 2, col = "grey55", lwd = 2)
        legend("bottomright", bty = "n", cex = 1.05, text.col = "navy",
               lty = c(2, 1), lwd = c(2, 2), col = c("grey55", "grey25"),
               legend = TeX(c(r"($1$)", r"(normalized weight function $w^{*}(\theta)$)")))
    })

    output$tab <- renderTable({
        s <- sim()
        data.frame(
            Quantity = c("C_f / C_g", "95% CI for C_f / C_g", "E_f(theta)", "observed ESS (% of S)",
                         "exact ESS (% of S)", "Var_f(w)"),
            True = c("1", "", "0", "", "", ""),
            Estimate = c(sprintf("%.4f", s$Chat),
                         sprintf("(%.4f, %.4f)", s$Chat - 1.96 * s$se, s$Chat + 1.96 * s$se),
                         sprintf("%.4f", s$Ehat),
                         sprintf("%.4g", 100 * s$ess / s$S),
                         sprintf("%.4g", s$ess_x),
                         if (s$sg <= 1 / sqrt(2)) "infinite" else "finite"))
    }, striped = TRUE, align = "lrr", width = "100%")
}

shinyApp(ui, server)

About the app

Illustrates how importance sampling can fail without warning when the proposal is too narrow to cover the target. The proposal’s standard deviation \(\sigma\) is under slider control and both panels are redrawn for each setting. For \(\sigma \le 1/\sqrt{2}\) the weight variance is infinite; near \(\sigma = 1\) the failure is silent, with the observed effective sample size close to \(S\) while the estimate of \(C_f/C_g\) sits at one half; past \(\sigma \approx 4\) the proposal reaches the second mode, the observed effective sample size falls, and the estimate moves onto the truth.

The target \(f\) and the proposal \(g\). The target is a normalized, equally weighted mixture of two unit-variance normals, with the modes at \(\pm d\) and \(d=5\), \[f(\theta)=\tfrac12\,N(\theta\mid -d,\,1)+\tfrac12\,N(\theta\mid d,\,1),\] and the proposal is a single normal centred on one of the modes, with the standard deviation \(\sigma\) set by the slider, \[g(\theta)=N(\theta\mid -d,\,\sigma^2).\] Draw \(\theta_1,\ldots,\theta_S\sim g\) and form the importance weights \(w_s=f(\theta_s)/g(\theta_s)\). Because both densities are normalized, \(C_f/C_g=1\), and \[\widehat{C_f/C_g}=\frac1S\sum_{s=1}^S w_s,\qquad \widehat{E_f(\theta)}=\frac{\sum_s w_s\theta_s}{\sum_s w_s},\] with true values \(1\) and \(0\). The 95% interval for \(C_f/C_g\) is \(\hat C\pm1.96\,s_w/\sqrt S\), where \(s_w\) is the sample standard deviation of the weights. The quality of the draws is summarized by the effective sample size \(S_{\text{eff}}=S\big/\tfrac1S\sum_s(\hat w^\star_s)^2\) with the normalized weights \(\hat w^\star_s=w_s\big/\tfrac1S\sum_j w_j\) (mean 1, estimating \(w^\star(\theta_s)\)), reported as a percentage of \(S\) (“observed”), and by its exact value \(S/E_g(w^2)\). The second moment \(E_g(w^2)=\int f^2/g\) is finite only when \(\sigma>1/\sqrt2\), so for smaller \(\sigma\) the weight variance is infinite. The sample size \(S\), the seed and a new sample are set in the control panel at the top; the estimates are listed in a table to the right of the plots, and the horizontal axis of both plots is fixed at \([-15,15]\). The top plot shows \(f\) and \(g\) on the density scale, and the bottom plot the normalized weights of the draws (log scale), with the dashed line at \(1\) marking perfectly balanced weights.

The app above varies \(\sigma\) with everything else held fixed. Three regimes appear. Below \(\sigma=1/\sqrt{2}\) the variance is infinite and the exact effective fraction is reported as zero. Between there and roughly \(\sigma=3\) the failure is silent in the sense above: observed \(S_{\text{eff}}\) near \(S\), estimate near \(\tfrac12\). Past \(\sigma\approx4\) the proposal is over-dispersed enough to place draws near \(+d\); the observed \(S_{\text{eff}}\) then drops, which looks like deterioration and is in fact the diagnostic finally working, and the estimate moves onto the truth. The cure for a missed mode is a proposal that is too diffuse rather than too well matched.

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)
}
library(latex2exp)

d <- 5

log_f <- function(th, d) {
    a <- dnorm(th, -d, log = TRUE); b <- dnorm(th, d, log = TRUE)
    m <- pmax(a, b)
    m + log(exp(a - m) + exp(b - m)) - log(2)
}

log_Ew2 <- function(d, sg) {
    A <- 2 - 1 / sg^2
    if (A <= 0) return(Inf)
    lterm <- function(a, b) {
        m <- (a + b) / 2
        B <- 2 * m + d / sg^2
        C <- 2 * m^2 - d^2 / sg^2
        dnorm(a, b, sqrt(2), log = TRUE) + log(sg) + 0.5 * log(2) +
            0.5 * log(2 * pi / A) - 0.5 * (C - B^2 / A)
    }
    lv <- c(lterm(-d, -d), log(2) + lterm(-d, d), lterm(d, d))
    m  <- max(lv)
    m + log(sum(exp(lv - m))) - log(4)
}

ui <- fluidPage(
    wellPanel(
        fluidRow(
            column(4, sliderInput("sg", HTML("proposal sd &sigma;"), min = 0.25, max = 8,
                                  value = 1, step = 0.05)),
            column(4, sliderInput("S", "sample size  S", min = 100, max = 20000,
                                  value = 2000, step = 100)),
            column(2, numericInput("seed", "seed", value = 11, min = 1, step = 1)),
            column(2, br(), actionButton("new", "New sample")))
    ),
    fluidRow(
        column(8, plotOutput("panels", height = "600px")),
        column(4,
            tags$style("#tab td, #tab th { white-space: nowrap; }"),
            h5("Estimates"),
            tableOutput("tab"))
    )
)

server <- function(input, output) {

    sim <- reactive({
        S  <- as.integer(input$S); sg <- input$sg
        set.seed(input$seed + 1000 * input$new)

        th   <- rnorm(S, -d, sg)
        logw <- log_f(th, d) - dnorm(th, -d, sg, log = TRUE)
        mx   <- max(logw); v <- exp(logw - mx)
        wn   <- v / mean(v)                  # normalized weights, mean 1

        list(th = th, wn = wn, S = S, sg = sg,
             Chat = mean(v) * exp(mx),
             se   = sd(v) / sqrt(S) * exp(mx),
             ess  = S / mean(wn^2),
             Ehat = mean(wn * th),
             lsum = mx + log(mean(v)),
             ess_x = 100 * exp(-log_Ew2(d, sg)))
    })

    output$panels <- renderPlot({
        s  <- sim(); th <- s$th; sg <- s$sg
        xr <- c(-15, 15)                                  # fixed x-axis
        xs <- seq(xr[1], xr[2], length.out = 1000)
        fx <- exp(log_f(xs, d)); gx <- dnorm(xs, -d, sg)
        lwc <- log_f(xs, d) - dnorm(xs, -d, sg, log = TRUE) - s$lsum

        layout(matrix(1:2, 2), heights = c(3, 2))

        par(mar = c(0.4, 5, 3, 1))
        plot(xs, fx, type = "n", ylim = c(0, max(fx, gx) * 1.1), xlim = xr, xaxt = "n",
             xlab = "", ylab = "density",
             main = "bimodal target and a proposal centred on one mode")
        lines(xs, fx, lwd = 4, col = "red")
        lines(xs, gx, lwd = 3, col = "grey60")
        rug(th, col = adjustcolor("grey45", 0.35))
        legend("top", bty = "n", cex = 1.05, text.col = "navy",
               lwd = c(4, 3), col = c("red", "grey60"),
               legend = TeX(c(
                   r"(target $f$)",
                   sprintf(r"(proposal $g$, sd $= %.2f$)", sg))))

        par(mar = c(4.5, 5, 0.4, 1))
        wn <- s$wn
        wl <- c(min(wn) / 5, max(wn) * 5)
        plot(th, wn, type = "n", log = "y", ylim = wl, xlim = xr,
             xlab = expression(theta), ylab = "normalized weight, mean 1 (log scale)")
        lines(xs, exp(pmin(lwc, 700)), lwd = 2, col = "grey25")
        segments(th, wl[1], th, wn, col = adjustcolor("grey45", 0.5))
        abline(h = 1, lty = 2, col = "grey55", lwd = 2)
        legend("bottomright", bty = "n", cex = 1.05, text.col = "navy",
               lty = c(2, 1), lwd = c(2, 2), col = c("grey55", "grey25"),
               legend = TeX(c(r"($1$)", r"(normalized weight function $w^{*}(\theta)$)")))
    })

    output$tab <- renderTable({
        s <- sim()
        data.frame(
            Quantity = c("C_f / C_g", "95% CI for C_f / C_g", "E_f(theta)", "observed ESS (% of S)",
                         "exact ESS (% of S)", "Var_f(w)"),
            True = c("1", "", "0", "", "", ""),
            Estimate = c(sprintf("%.4f", s$Chat),
                         sprintf("(%.4f, %.4f)", s$Chat - 1.96 * s$se, s$Chat + 1.96 * s$se),
                         sprintf("%.4f", s$Ehat),
                         sprintf("%.4g", 100 * s$ess / s$S),
                         sprintf("%.4g", s$ess_x),
                         if (s$sg <= 1 / sqrt(2)) "infinite" else "finite"))
    }, striped = TRUE, align = "lrr", width = "100%")
}

shinyApp(ui, server)

This app accompanies Importance Sampling in the book.