Probability

Monte Carlo Estimation and Importance Sampling

Monte Carlo turns expectations into sample averages; importance sampling changes where samples come from and uses p/q weights, so proposal choice controls variance.

status: reviewimportance: importantdifficulty 4/5math: graduateread: 20mlive demo

Concept Structure

Monte Carlo Estimation and Importance Sampling

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

3prerequisites
3next concepts
3related links

Learner Contract

What this page should let you do.

You are here becauseMonte Carlo turns expectations into sample averages; importance sampling changes where samples come from and uses p/q weights, so proposal choice controls variance.

This Probability concept is the current idea: keep the same invariant visible across Intuition, Math, Code, Interactive Demo.

By the end4/4 sections ready | runnable code expected | live demo

Explain the mechanism, trace the main notation, and test one prediction in the live demo.

Do this firstIntuition

Read the intuition before the notation; the math should name a mechanism you already felt.

Test the linkManipulate one control and predict the visible change.Then continue to MCMC: Metropolis-Hastings and Gibbs Sampling (review)

Claim/source review status

Substantive review recorded

1/1 claims have bounded review metadata; still check caveats and source scope.Metadata-derived; review may be AI-assisted. Not a human certification.
Claims1/1 reviewed
Sources5 cited
Codeattached
Demolive
Reviewed2026-07-02
Updatedpage 2026-07-02

Learning item flow

4/4 sections readyAsk about thisResearch room
ConceptMonte Carlo Estimation and Importance SamplingProbability
5 sources attachedLocal snapshot ready
concept:probability/monte-carlo-importance-sampling
01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

Section prompt

Monte Carlo estimation starts with a simple promise:

Ep[f(X)]\mathbb E_p[f(X)]

can be estimated by drawing samples and averaging the values of ff.

That is already powerful. If pp is a model distribution and ff is a quantity we care about, sampling can replace an impossible sum or integral with a procedure we can run.

The catch is variance. A sample average is not just "more samples means better." It also asks whether the samples visit the parts of the space that matter for the expectation. If rare states carry large values of f(x)f(x), ordinary samples can spend most of the budget watching unimportant states.

Importance sampling changes the question:

What if we sample from a different distribution qq, then correct the accounting?

Each sample gets an importance weight

w(x)=p(x)q(x).w(x)=\frac{p(x)}{q(x)}.

If qq samples a point too often compared with pp, the weight shrinks it. If qq samples a point too rarely, the weight amplifies it. The identity is clean, but the experience can be brutal: a bad proposal can make one sample carry most of the estimate.

The learner move is to separate three ideas:

  1. the target distribution pp defines the expectation;
  2. the proposal qq defines where samples come from;
  3. the weighted contribution f(x)p(x)/q(x)f(x)p(x)/q(x) defines the estimator variance.

Good importance sampling makes those weighted contributions stable. Bad importance sampling creates heavy weights and low effective sample size.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

Section prompt

Let XX be a random variable with target probability mass or density p(x)p(x), and let f(x)f(x) be an integrable function. The target quantity is

I=EXp[f(X)]=xf(x)p(x),I = \mathbb E_{X\sim p}[f(X)] = \sum_x f(x)p(x),

or an integral in the continuous case.

The direct Monte Carlo estimator draws x1,,xTpx_1,\ldots,x_T \sim p and uses

I^MC=1Tt=1Tf(xt).\hat I_{\mathrm{MC}} = \frac{1}{T}\sum_{t=1}^T f(x_t).

When the samples are iid and the variance is finite,

E[I^MC]=I,Var(I^MC)=Varp(f(X))T.\mathbb E[\hat I_{\mathrm{MC}}]=I, \qquad \mathrm{Var}(\hat I_{\mathrm{MC}}) = \frac{\mathrm{Var}_p(f(X))}{T}.

Importance sampling chooses a proposal q(x)q(x) such that q(x)>0q(x)>0 whenever f(x)p(x)f(x)p(x) can be nonzero. Then

I=xf(x)p(x)=xf(x)p(x)q(x)q(x)=EXq[f(X)w(X)],\begin{aligned} I &= \sum_x f(x)p(x) \\ &= \sum_x f(x)\frac{p(x)}{q(x)}q(x) \\ &= \mathbb E_{X\sim q}\left[f(X)w(X)\right], \end{aligned}

where

w(x)=p(x)q(x).w(x)=\frac{p(x)}{q(x)}.

The standard importance-sampling estimator is

I^IS=1Tt=1Tf(xt)w(xt),xtq.\hat I_{\mathrm{IS}} = \frac{1}{T}\sum_{t=1}^T f(x_t)w(x_t), \qquad x_t\sim q.

It is unbiased under the support and integrability assumptions above. Its variance is

Var(I^IS)=1T(Eq[f(X)2w(X)2]I2).\mathrm{Var}(\hat I_{\mathrm{IS}}) = \frac{1}{T} \left( \mathbb E_q[f(X)^2w(X)^2]-I^2 \right).

This equation is the whole design problem. A proposal can be algebraically valid and still terrible if f(x)w(x)f(x)w(x) has heavy tails.

For nonnegative ff, the ideal proposal is proportional to the target contribution:

q(x)=f(x)p(x)zf(z)p(z).q^\star(x) = \frac{f(x)p(x)}{\sum_z f(z)p(z)}.

Then f(x)p(x)/q(x)f(x)p(x)/q^\star(x) is constant on contributing states, so the estimator has zero variance in the finite toy case. In real problems we usually cannot sample exactly from this proposal because its normalizer is the target expectation or something equally hard. But it tells us the direction: sample where the contribution lives, not merely where pp is large.

When pp is known only up to a normalizing constant, or when estimating posterior ratios, a self-normalized estimator is common:

I^SNIS=t=1Twˉtf(xt),wˉt=wtj=1Twj.\hat I_{\mathrm{SNIS}} = \sum_{t=1}^T \bar w_t f(x_t), \qquad \bar w_t = \frac{w_t}{\sum_{j=1}^T w_j}.

Self-normalization is generally biased at finite TT, but it is consistent under standard assumptions and often useful in approximate inference.

A quick diagnostic is effective sample size:

ESS=(t=1Twt)2t=1Twt2.\mathrm{ESS} = \frac{\left(\sum_{t=1}^T w_t\right)^2} {\sum_{t=1}^T w_t^2}.

ESS is high when weights are balanced and low when a few weights dominate. It is a warning light, not the full variance formula: if q=pq=p, all weights equal one and ESS is maximal, but f(X)f(X) itself may still vary a lot.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

Section prompt
import numpy as np

x = np.arange(-4, 5)
p = np.array([.02, .05, .10, .17, .22, .18, .13, .08, .05])
f = np.maximum(.15, 1 + .38 * x + .10 * x**2)
true_value = np.sum(p * f)

proposals = {
    "target": p,
    "matched": p * f / true_value,
    "too_central": np.array([.003, .006, .02, .11, .48, .27, .08, .021, .01]),
}
proposals["too_central"] /= proposals["too_central"].sum()

u_trials = np.array([
    [.03, .11, .19, .28, .36, .44, .52, .61, .70, .79, .88, .97],
    [.06, .14, .22, .35, .46, .55, .64, .71, .83, .91, .95, .99],
    [.01, .08, .18, .27, .39, .47, .59, .68, .75, .84, .93, .985],
])

def draw(q, u):
    return np.searchsorted(np.cumsum(q), u)

for name, q in proposals.items():
    estimates = []
    for us in u_trials:
        i = draw(q, us)
        w = p[i] / q[i]
        estimates.append(np.mean(f[i] * w))
    print(name, "true", round(true_value, 3),
          "estimates", np.round(estimates, 3).tolist())

The three proposals estimate the same target value. The difference is stability. The matched proposal is close to f(x)p(x)f(x)p(x), so the weighted contributions become nearly constant. The too_central proposal undersamples the right tail; when a tail point appears, its weight is large enough to move the whole estimate.

04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

Section prompt

The lab below hides the exact value, the trial estimates, and the ESS ledger until you commit.

Pick which proposal you think gives the lowest repeated-trial variance. Then reveal the ledger and compare three quantities:

  1. the exact target value Ep[f(X)]E_p[f(X)];
  2. the trial-to-trial variance of the weighted estimator;
  3. the ESS of the first sample batch.

The trick is that sample from p has perfect weight ESS, but it is not the lowest-variance estimator here. ESS only watches the weights. The actual estimator variance watches the weighted payoff f(x)p(x)/q(x)f(x)p(x)/q(x).

Live Concept Demo

Explore Monte Carlo Estimation and Importance Sampling

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 4/5graduatecode-aligned
Demo Prediction Checkpoint

Manipulate one control and predict the visible change.

Commit to what Monte Carlo Estimation and Importance Sampling should make visible before reading the result.

After The First Pass

Turn the concept into an inspected object.

Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.

Mechanism Storyboard

See the idea move before the page explains it

Monte Carlo turns expectations into sample averages; importance sampling changes where samples come from and uses p/q weights, so proposal choice controls variance.

Prediction open01 / Intuition
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Monte Carlo Estimation and Importance Sampling should make visible.

Visual Inquiry

Make the image answer a mathematical question

Monte Carlo turns expectations into sample averages; importance sampling changes where samples come from and uses p/q weights, so proposal choice controls variance.

4/4 stages readyLive demo connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Monte Carlo Estimation and Importance Sampling easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

course-notes · 2026CS228 Notes: Sampling MethodsStanford CS228

Grounds Monte Carlo expectation estimation, the importance-sampling p/q identity, estimator variance, normalized importance sampling, and the proposal-shape warning.

Open source
book · 2016Deep Learning, Chapter 17: Monte Carlo MethodsGoodfellow, Bengio, and Courville

Deep-learning textbook anchor for Monte Carlo methods as expectation approximation in ML.

Open source
book · 2013Monte Carlo Theory, Methods and Examples: Importance SamplingArt B. Owen

Supports the variance-reduction framing, self-normalized importance sampling, and importance-sampling diagnostics.

Open source
paper · 2017Effective Sample Size for Importance Sampling based on discrepancy measuresMartino, Elvira, and Louzada

Supports the normalized-weight ESS diagnostic and its role in importance sampling and sequential Monte Carlo.

Open source
book · 2023Probabilistic Machine Learning: Advanced TopicsKevin P. Murphy

Curriculum anchor for modern approximate inference topics that use Monte Carlo and importance sampling.

Open source

Claim Review

Monte Carlo turns expectations into sample averages; importance sampling changes where samples come from and uses p/q weights, so proposal choice controls variance.

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources5 references

cs228-sampling-notes, goodfellow-2016-deep-learning-monte-carlo, owen-2013-importance-sampling, martino-2017-ess, murphy-2023-probml-advanced

Local checks4 local checks

Use equations, runnable code, and demos to check whether the source support is operational.

Substantively reviewedImportance sampling estimates E_p[f(X)] by drawing from a proposal q, multiplying each sampled contribution by w(x)=p(x)/q(x), and inspecting variance or weight degeneracy because a poor proposal can make a few weighted samples dominate even though the identity is algebraically correct.Claim metadata: source checked

The sources support Monte Carlo as expectation approximation, standard importance sampling as q-sampling plus p/q weights, proposal-dependent variance, normalized importance sampling for posterior/marginal-ratio style estimates, and ESS as a diagnostic for concentrated normalized weights.

Sources: CS228 Notes: Sampling Methods, Deep Learning, Chapter 17: Monte Carlo Methods, Monte Carlo Theory, Methods and Examples: Importance Sampling, Effective Sample Size for Importance Sampling based on discrepancy measures, Probabilistic Machine Learning: Advanced TopicsFinite discrete witness only; does not cover continuous measure-theoretic support pathologies, adaptive/sequential importance sampling, bridge sampling, annealed importance sampling, rare-event asymptotics, or a GPT Pro publication pass.A bounded review summary is present; still check caveats and exact reference scope.

Checked CS228 sampling notes for Monte Carlo expectation estimation, the p/q reweighting identity, variance formula, normalized importance sampling, and the ideal proposal proportional to |f|p; checked Owen's Monte Carlo book table of contents and importance-sampling chapter anchor for diagnostics and self-normalized IS; checked Martino et al. for the common normalized-weight ESS diagnostic. GPT Pro publication critique remains pending.

Reviewer: codex-local-source-review; reviewed 2026-07-02

Practice Loop

Try the idea before it explains itself

Monte Carlo turns expectations into sample averages; importance sampling changes where samples come from and uses p/q weights, so proposal choice controls variance.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in Monte Carlo Estimation and Importance Sampling.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Grounded research drawerClose
ConceptMonte Carlo Estimation and Importance SamplingProbability

Research Room

Attach the question to a claim, equation, code, or demo

Pick the concept, equation, source, runnable code, claim, misconception, or demo state before asking for help. The handoff keeps that page item in context.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptProbability

Monte Carlo Estimation and Importance Sampling

Attached question

What is the smallest example that makes Monte Carlo Estimation and Importance Sampling click without losing the math?

Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays in this browser, attached to the selected learning item.

No local draft saved.
Evidence to inspect
  • References to inspect: attached references on this page.
  • Definition, prerequisite, and contrast concept links
  • The equation or runnable code that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Grounded AI handoff

I am working in Continuous Function's research reading room. Object: concept - Monte Carlo Estimation and Importance Sampling Selected item key: recorded for copy. Context: Probability Page anchor: recorded for copy. Open question: What is the smallest example that makes Monte Carlo Estimation and Importance Sampling click without losing the math? Evidence to inspect: - References to inspect: attached references on this page. - Definition, prerequisite, and contrast concept links - The equation or runnable code that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.

View it in context
concept/concept-notebook/probability/monte-carlo-importance-sampling concept:probability/monte-carlo-importance-sampling