liveBook · Manning

Monte Carlo simulation

As explained in Causal AI

A Monte Carlo method is a randomized computational technique that estimates quantities by repeatedly sampling from a probability distribution.

Monte Carlo simulation estimates an expectation by repeatedly generating samples from a distribution, applying a function to each sample, and averaging the results. It works for discrete and continuous random variables. section 2.2.4

A practical workflow is:

  • Generate samples with a probabilistic model or random process. section 2.2.4
  • Apply the desired function to every sample, then average the transformed values. section 2.2.4
  • Represent probabilities with indicator values: average 1 when a condition holds and 0 otherwise. section 2.2.4
  • Expect slightly different estimates across runs because random samples vary. section 2.2.4

Estimating a conditional expectation

A Pyro process generates z from a Gamma distribution, x from a Poisson distribution, and y from repeated Bernoulli draws. After generating 1,000 outcomes, averaging z estimates E(Z). Filtering to outcomes with y = 3 and averaging the retained z values estimates E(Z | Y = 3). This accept/reject approach becomes inefficient when the condition is rare. section 2.2.5

Listing 2.9 Monte Carlo estimation in Pyro
import torch
import pyro
from pyro.distributions import Bernoulli, Gamma, Poisson
def random_process():
    z = pyro.sample("z", Gamma(7.5, 1.0))
    x = pyro.sample("x", Poisson(z))
    y = torch.tensor(0.0)
    for i in range(int(x)):



        y += pyro.sample(f"{i}", Bernoulli(.5))
    return z, y    #1

generated_samples = [random_process() for _ in range(1000)]     #2
z_mean = torch.stack([z for z, _ in generated_samples]).mean()     #3
print(z_mean)

Use the Pyro listing to trace random-process generation, tensor stacking, and Monte Carlo averaging. section 2.2.5

How Causal AI covers it

How deep it goes
Defines sampling and averaging, demonstrates Python implementations, and stops short of detailed inference algorithms.
Examples
Uses indicator averages, squared samples, pgmpy data frames, and Pyro Gamma–Poisson–Bernoulli processes.
What it assumes
Assumes familiarity with random variables and expectations while demonstrating sample generation and averaging operationally.
What you can do after
Apply it via Pyro or pgmpy to estimate expectations and probabilities from generated samples.
How it connects
Connects expectations with probability distributions, conditional probability, probabilistic inference, and importance sampling.

Also explained in

Compare how 8 books explain Monte Carlo simulation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Causal AI. The section links point to the parts of the book it draws on.