Chapter 4: Probability & Statistics
Deep dive into probability theory, statistical distributions, estimation, hypothesis testing, Bayesian inference, and sampling methods for machine learning.
Chapter Overview
Probability and statistics are the mathematical language of uncertainty — and uncertainty is everywhere in machine learning. Every prediction carries a confidence level, every dataset is a sample from an unknown distribution, and every training procedure is an optimization over a probabilistic objective.
The Mathematical Foundations chapter introduced probability basics: distributions, Bayes' theorem, and expectation. This chapter takes you much deeper. You will build rigorous foundations in probability theory, master the full family of distributions that appear throughout ML, and learn the statistical tools that let you draw reliable conclusions from data.
We start with the axioms that make probability logically consistent, then systematically build up to the tools that practicing ML engineers use daily:
- Probability Fundamentals: The axiomatic foundation — sample spaces, conditional probability, independence, and the law of total probability
- Discrete Distributions: Bernoulli, Binomial, Poisson, and Geometric — the building blocks of classification, counting, and sequential models
- Continuous Distributions: Gaussian, Exponential, Beta, Gamma, and the Central Limit Theorem — why the bell curve appears everywhere
- Joint & Marginal Distributions: How multiple random variables interact — the theory behind multivariate models
- Statistical Estimation: Point estimators, confidence intervals, and bootstrap — quantifying uncertainty in your estimates
- Hypothesis Testing: P-values, significance tests, and A/B testing — making data-driven decisions with statistical rigor
- Bayesian Inference: The full Bayesian framework — priors, posteriors, conjugate families, and the MAP-regularization connection
- Sampling Methods: Monte Carlo, importance sampling, and MCMC — computational tools for intractable distributions
Chapter Roadmap
Click any topic to jump in
Fundamentals
Sample spaces, axioms, conditional probability, independence — the rules everything builds on.
Discrete counts and continuous measurements
Discrete Distributions
Bernoulli, binomial, Poisson, geometric — modeling countable outcomes.
Continuous Distributions
PDFs, uniform, exponential, beta, gamma, CLT — modeling continuous variables.
Joint & Marginal
Joint distributions, marginalization, conditioning, multivariate Gaussian — reasoning about multiple variables.
Estimation and testing
Estimation
Point estimators, bias-variance, confidence intervals, MLE vs MAP — learning from data.
Hypothesis Testing
P-values, type I/II errors, t-tests, A/B testing — rigorous decisions from experiments.
Bayesian thinking and computational methods
Bayesian Inference
Prior, likelihood, posterior, conjugate priors, MAP — updating beliefs with evidence.
Sampling Methods
Monte Carlo, rejection/importance sampling, MCMC — approximating intractable distributions.
A spam filter sees the word "winner" in an email. How worried should it be? The useful number is not the fraction of spam emails that contain "winner". It is the fraction of emails containing "winner" that turn out to be spam, and those two numbers can differ by a factor of ten. Confusing them is one of the most common reasoning errors in medicine, law, and machine learning. Avoiding it takes a precise language for uncertainty: which outcomes are possible, how probability is spread over them, and how that spread changes when new information arrives.
The previous chapter, Mathematical Foundations, used probabilities informally for expectation, variance, and entropy. This chapter rebuilds that material from the ground up. A classifier's softmax, a language model's next-token distribution, and a Bayesian posterior all obey the same three axioms.
We begin with sample spaces and events, state Kolmogorov's axioms, define conditional probability, separate independence from conditional independence, and finish with the law of total probability, which splits a hard probability into easy cases.
Definition
A probability space has three parts: a sample space of outcomes, a collection of events that are subsets of , and a probability measure . The measure assigns each event a number between 0 and 1, gives probability 1, and adds over disjoint events. The conditional probability of given is whenever .
In this topic
Sample Spaces & Events
Before you can assign a probability, you must say what could happen. The sample space in the formula is the set of all outcomes of an experiment, and an event is any subset of it, such as "the die shows an even number", which is . Events combine with set operations. The complement is everything outside , the union means A or B, and the intersection means both. says some outcome always happens. The usual failure is a badly chosen , such as counting "two heads, one of each, two tails" as three equally likely cases.
The sample space is the universal set in measure theory — every probability statement is a measure on subsets of . In ML, feature spaces are high-dimensional sample spaces where each point is one possible input configuration.
A card is drawn from a standard 52-card deck. Define the sample space and find P(drawing a face card).
Axioms of Probability
Why only three rules? Kolmogorov showed in 1933 that non-negativity, normalization, and additivity over disjoint events are enough to derive everything else. In the formula, and are events, is the sample space, and is the empty event. Additivity gives the complement rule and . Splitting into disjoint pieces gives inclusion-exclusion, . A softmax layer satisfies the axioms by construction, because exponentials are positive and the outputs are normalized. Independent sigmoid scores do not, since their class scores need not sum to 1.
Kolmogorov's axioms define probability as a measure with total mass 1. The additivity axiom generalizes to countable unions (-additivity), which is why we need -algebras. Softmax enforces axioms 1-2 by construction: and sums to 1.
Verify the axioms for a fair six-sided die. Then use inclusion-exclusion: P(even OR greater than 4)?
Conditional Probability
Learning that happened shrinks the world to the outcomes inside . The formula renormalizes: is the share of 's probability that also lies in , and it is defined only when . Rearranging gives the product rule , which the rest of the chapter uses constantly. Every classifier estimates a conditional probability such as , and a language model estimates . The classic failure is swapping for , the prosecutor's fallacy from the spam example in the introduction.
Conditioning is geometrically a projection: you collapse the probability mass onto the subspace where holds, then renormalize. In neural nets, attention scores are conditional probabilities — each token attends to others proportionally to .
In a class of 100 students: 40 study math, 30 study CS, 10 study both. If a student studies math, what is P(they also study CS)?
Independence & Conditional Independence
Independence means one event carries no information about another. In the formula, holds exactly when the joint probability factors as , which is equivalent to . Conditional independence applies the same test inside a context : . Neither kind implies the other. Two symptoms can be dependent overall yet independent given the disease that causes both. Naive Bayes assumes words are conditionally independent given the class, which cuts its parameter count from exponential to linear in the vocabulary. A frequent error is confusing independent with disjoint: disjoint events with positive probability are always dependent.
Independence means the joint distribution factors: . This is a massive dimensionality reduction — from parameters to . Naive Bayes exploits this: reduces exponential parameter space to linear.
A fair coin is flipped twice. Are the two flips independent? Verify using the definition.
Law of Total Probability
Some probabilities are hard to compute directly but easy once you know which case you are in. If partition the sample space, meaning they are disjoint and together cover it, the formula writes as a weighted average of the case probabilities , with weights . It follows from the product rule of conditional probability plus additivity. The same move marginalizes a latent variable, , which is how mixture models score data, and it produces the denominator of Bayes' theorem. The failure mode is a set of cases that overlap or leave gaps, so the weights no longer sum to 1.
Total probability is marginalization in disguise: is just in continuous form. In mixture models like GMMs, this is exactly how you compute the data likelihood — sum over all cluster assignments weighted by mixing coefficients.
Factory has 3 machines: M1 (50% of output, 2% defect), M2 (30%, 3% defect), M3 (20%, 5% defect). Find P(defective item).
Theory Exercise
Problem:
A medical test has 95% sensitivity (P(+|disease) = 0.95) and 90% specificity (P(-|healthy) = 0.90). The disease prevalence is 1%. Using the law of total probability, find P(+). Then use Bayes' theorem to find P(disease|+).
Hints:
- P(+) = P(+|disease)P(disease) + P(+|healthy)P(healthy)
- P(+|healthy) = 1 - specificity = 0.10
- P(disease|+) = P(+|disease)P(disease) / P(+)
Coding Exercise
Problem:
Verify Bayes' theorem and the law of total probability by Monte Carlo simulation. A disease has 1% prevalence. A test has 95% sensitivity and 90% specificity. Simulate 1,000,000 patients, then empirically estimate P(disease | positive test) and compare it to the analytic Bayes answer.
Hints:
- Draw the disease status with np.random.rand(N) < 0.01.
- Generate test results conditionally: sick patients test positive with prob 0.95, healthy with prob 0.10 (1 - specificity).
- P(disease | +) is simply the fraction of positive testers who are actually sick.
Related Problems on PixelBank
The axioms alone do not tell you how likely it is that a 90%-accurate model gets exactly 18 of 20 predictions right. Nor do they say how often a server averaging 5 requests per second sees more than 7 in the next second. Working such questions out from first principles every time would be slow and error-prone. Instead, a few named distributions describe the counting patterns that keep recurring: a single yes-or-no trial, the number of successes in n trials, the count of rare events in an interval, and the wait until the first success.
The previous topic, Probability Fundamentals, gave the axioms, conditional probability, and independence. Every distribution here is built from independent trials, so those tools do the work. Each one is described by a probability mass function (PMF), which gives the probability of each value, and a cumulative distribution function (CDF), which accumulates it.
We move from the Bernoulli trial to the Binomial count, take the rare-event limit to reach the Poisson, study the memoryless Geometric waiting time, and close with PMFs and CDFs, the two views every later topic reuses.
Definition
A discrete random variable takes values in a countable set. Its probability mass function is non-negative and sums to 1 over all values. Its cumulative distribution function rises from 0 to 1 and never decreases. The expectation is , and the variance is .
In this topic
Bernoulli Distribution
The Bernoulli distribution models a single trial with two outcomes, coded 1 for success and 0 for failure. In the formula, is the success probability and , so the expression returns when and when . The mean is and the variance is , which peaks at 0.25 when , the point of greatest uncertainty. A sigmoid output is exactly a Bernoulli parameter, binary cross-entropy is its negative log-likelihood, and dropout masks units with Bernoulli draws. The model breaks down when outcomes are not binary, or when trials share a hidden cause such as one spam campaign.
The Bernoulli is the exponential family member with sufficient statistic . Binary cross-entropy is the negative log-likelihood of . Maximum variance at explains why balanced datasets are hardest to classify — maximum uncertainty.
A spam filter classifies an email with P(spam) = 0.8. Model this as Bernoulli and find the mean and variance.
Binomial Distribution
Count the successes in independent Bernoulli trials that share the same success probability , and you get the Binomial distribution. In the formula, counts the orderings with exactly successes, is the probability of those successes, and covers the failures. The mean is and the variance is . The shape is symmetric at and approaches a Gaussian as grows. The number of correct predictions on a test set of examples is a Binomial count. The model fails when trials are dependent, for example when near-duplicate test images make errors arrive in clusters.
The binomial coefficient counts lattice paths — it is the number of ways to arrange successes in slots. As , the binomial approaches by CLT. In ensemble learning, majority voting among independent classifiers each with accuracy has error that decays exponentially with .
A model has 90% accuracy. In a batch of 20 predictions, find P(exactly 18 correct) and E[correct].
Poisson Distribution
Many events are individually rare but have many chances to happen: requests hitting a server, typos on a page, photons striking a sensor pixel. The Poisson distribution counts such events in a fixed interval. In the formula, is the average number of events per interval, is the observed count, and accounts for orderings. Both the mean and the variance equal , and independent Poisson counts add their rates. It is the limit of a Binomial with large and small , with . The telltale failure is overdispersion: if the observed variance far exceeds the mean, events are clustered and a Poisson model underestimates spikes.
The Poisson is the limit of as — many rare independent events. Its mean equals its variance (), making overdispersion () a diagnostic for model misspecification. The Poisson process gives inter-arrival times that are exponential, connecting discrete counts to continuous waiting times.
A server receives an average of 5 requests per second. Find P(exactly 3 requests) and P(more than 7).
Geometric Distribution
How many attempts until the first success? If each independent trial succeeds with probability , the formula says the first success lands on trial after failures, each with probability . The mean is , the variance is , and the CDF is . The Geometric is the only discrete distribution that is memoryless: , so ten failed trials do not bring success any closer. Watch the convention. Some libraries count the failures before the first success, which shifts the mean to .
The geometric distribution is memoryless: . This means past failures carry no information — each trial is a fresh start. In random search for hyperparameters, geometric waiting times justify the strategy: if , then after trials you have 95% coverage.
A random search finds a good hyperparameter with P = 0.1 per trial. Find E[trials to first success] and P(success within 5 trials).
PMFs and CDFs
The PMF answers point questions, and the CDF in the formula answers "at most" questions by summing the PMF up to . Each can be recovered from the other: , and any interval probability is a difference, . A CDF never decreases and climbs from 0 to 1. Percentiles, p-values, and calibration curves are all CDF lookups. The standard off-by-one error is using for , which silently drops the mass at for a discrete variable.
The CDF is a right-continuous non-decreasing step function for discrete variables. The quantile function inverts it — this is the basis of the probability integral transform: if , then has CDF , enabling sampling from any distribution.
X ~ Binomial(3, 0.5). Compute the full PMF and CDF. Find P(1 ≤ X ≤ 2).
Theory Exercise
Problem:
A quality control process inspects items with a 5% defect rate. In a batch of 20 items: (a) What is the probability of finding exactly 2 defective items? (b) What is the expected number of defective items? (c) What is the probability of finding the first defective item on the 4th inspection?
Hints:
- Part (a): Use Binomial with n=20, p=0.05
- Part (c): Use Geometric with p=0.05
- For Geometric: P(X=k) = (1-p)^(k-1) × p
Coding Exercise
Problem:
Demonstrate the Poisson approximation to the Binomial. Take n=1000 trials with success probability p=0.005 (so lambda = np = 5). Compare the exact Binomial PMF, the Poisson(lambda=5) PMF, and an empirical histogram from 100,000 simulated Binomial draws for k = 0..15.
Hints:
- Use scipy.stats.binom.pmf and scipy.stats.poisson.pmf over the range of k values.
- Simulate with np.random.binomial(n, p, size=100000) and bin the counts.
- When n is large and p is small, the two PMFs should nearly coincide.
Related Problems on PixelBank
How likely is a model weight to be exactly 0.3172? For a quantity that can take any real value, the answer is zero, and so is the answer for every other single value. Yet weights, latencies, and pixel intensities clearly have typical and atypical values. Measurements on a continuum need a different description: probability spread thinly over intervals rather than stacked on points.
The previous topic, Discrete Distributions, handled countable outcomes with probability mass functions. Here the sum becomes an integral and the PMF becomes a probability density function, whose area over an interval gives that interval's probability. Several continuous distributions mirror discrete ones. The Exponential is the waiting time in a Poisson process, just as the Geometric counts trials until a success.
We start with densities and their CDFs. Then come the Uniform for bounded ignorance, the Exponential for waiting times, the Beta for uncertainty about probabilities themselves, and the Gamma for positive totals. We finish with the Central Limit Theorem, which explains why the Gaussian appears whenever many small effects add up.
Definition
A continuous random variable has a probability density function with total area 1, and . Its cumulative distribution function is continuous and satisfies . Single points carry zero probability, and a density can exceed 1 because it measures probability per unit length.
In this topic
Probability Density Functions
A density is probability per unit length. The first line of the formula says an interval's probability is the area under between and . The other two lines are the density's rules: is never negative, and its total area is 1. Because a single point has zero width, , which is why densities compare relative likelihoods rather than giving probabilities. The CDF accumulates area, and differentiating it recovers . The common error is reading as a probability. A Gaussian with standard deviation 0.1 has a peak density of about 4, which is perfectly valid.
A PDF is not a probability — it can exceed 1. The probability lives in areas: . Think of as the probability mass in a thin slice. In kernel density estimation, you sum bumps centered at data points to approximate the true PDF from samples.
Given for (zero elsewhere), verify it is a valid PDF and find P(0.5 ≤ X ≤ 0.8).
Uniform Distribution
When all you know is that a value lies between and , the Uniform distribution spreads density evenly. The formula gives height inside the interval and zero outside, so the area is 1. The mean is the midpoint , the variance is , and the CDF is linear, . Among distributions confined to it has the maximum entropy. Random crops, random hyperparameter search, and Glorot initialization all use it. The trap is scale. A uniform range over a quantity spanning several orders of magnitude, such as a learning rate, puts almost all samples in the top decade.
The uniform distribution maximizes entropy among all distributions on — it is the "most ignorant" prior. Noise injection with is used in dequantization to convert discrete data to continuous for normalizing flows. The probability integral transform maps any continuous distribution to .
Random search samples learning rate from Uniform(0.001, 0.1). What is P(rate < 0.01)?
Exponential Distribution
In a Poisson process with rate events per unit time, the wait until the next event follows an Exponential distribution. The density in the formula starts at height and decays, so short waits are the most common. The CDF is , the mean is , and the variance is . Like the Geometric, the Exponential is memoryless: . That fits radioactive decay and request arrivals. It does not fit hardware that wears out, where an old part is more likely to fail soon, so Weibull or Gamma models are used there.
The exponential is the continuous analogue of geometric — memoryless with . Its hazard rate is constant, meaning failure is equally likely at any moment. In ML, exponential learning rate decay gives diminishing step sizes for convergence.
Server requests arrive at rate λ=2 per minute. Find P(wait > 1 min) and the expected wait.
Beta Distribution
How do you describe uncertainty about a probability itself, such as a click-through rate? The Beta distribution lives on . In the formula, and act like counts of successes and failures, and the beta function normalizes the area to 1. The mean is . is uniform, equal parameters above 1 peak at 0.5, and parameters below 1 give a U shape. After successes and failures, a Beta prior updates to . A trap is reading the mean alone: and share it, but their standard deviations differ threefold.
The beta distribution is the conjugate prior for the Bernoulli likelihood. After observing successes and failures, the posterior is . The mean acts like a smoothed frequency estimate — Thompson sampling in bandits draws from this posterior to balance exploration and exploitation.
Prior: Beta(2, 2). After observing 7 heads and 3 tails, find the posterior and its mean.
Gamma Distribution
The Gamma distribution models positive quantities built from several waits or small contributions, such as the time until the fifth phone call. In the formula, is the shape, is the rate, and normalizes the area. The mean is and the variance is . With it reduces to the Exponential, and for integer it is the sum of independent Exponential waits with rate . The chi-squared distribution is a special case, and the Gamma is the conjugate prior for a Poisson rate. The main pitfall is parameterization: NumPy and SciPy take a scale , not a rate.
The gamma distribution generalizes the exponential () and is conjugate to the Poisson rate parameter. The sum of independent exponentials is . In Bayesian neural networks, the gamma prior on precision (inverse variance) yields analytically tractable posterior updates.
Call center: calls arrive at rate 3/hour. Model the wait for the 5th call using Gamma(5, 3). Find E[wait].
Central Limit Theorem
Why is the Gaussian everywhere? The Central Limit Theorem says that the average of independent draws with mean and finite variance becomes approximately normal, with mean and variance , whatever the original distribution looks like. The arrow marked in the formula means convergence in distribution. The spread shrinks like , so four times the data halves the error bar. This justifies Gaussian confidence intervals for test accuracy and the Gaussian model of mini-batch gradient noise. It fails for heavy-tailed data without a finite variance, such as the Cauchy, and converges slowly for strongly skewed data.
The CLT states regardless of the original distribution. The convergence rate is by Berry-Esseen. In SGD, each mini-batch gradient is an average of samples, so gradient noise is approximately Gaussian — this justifies using Gaussian noise analysis for SGD convergence proofs.
Exponential(λ=1) has mean 1 and variance 1. For the average of n=36 samples, find P(average > 1.2).
Theory Exercise
Problem:
A battery lifetime follows Exponential(λ=0.5 per year). (a) Find P(lasts more than 3 years). (b) Given it lasted 2 years, find P(lasts 2 more years). (c) If you have 10 batteries, what is the approximate distribution of their average lifetime?
Hints:
- Part (a): P(X > t) = e^(-λt) for Exponential
- Part (b): Use the memoryless property
- Part (c): Apply the Central Limit Theorem
Coding Exercise
Problem:
Demonstrate the Central Limit Theorem from a heavily skewed source. Draw samples from an Exponential(scale=1) distribution (mean 1, variance 1). For sample sizes n = 1, 5, 30, repeatedly compute the sample mean over 50,000 trials, then compare the empirical mean and standard deviation of those sample means to the CLT prediction N(1, 1/n).
Hints:
- np.random.exponential(scale=1.0, size=(trials, n)).mean(axis=1) gives one array of sample means per n.
- CLT predicts the sample mean has mean mu=1 and standard deviation sigma/sqrt(n) = 1/sqrt(n).
- The distribution of means should look more Gaussian (less skewed) as n grows.
Related Problems on PixelBank
A dataset of houses records floor area and price, and the two clearly move together. Modeling each column separately with the distributions from the previous topics throws that relationship away. You could not say how price changes for a larger house, or which combinations are unusual. Supervised learning is this problem at scale: it asks what the label is likely to be given the features, and that requires describing several random variables at once.
The previous topic, Continuous Distributions, described one variable at a time. This topic works with a joint distribution, which assigns probability to combinations of values. Two operations then do most of the work. Marginalization sums out a variable you do not care about, and conditioning fixes a variable you have observed. The chain rule factors any joint distribution into a product of conditionals, which is how GPT-style models generate text one token at a time.
We start with joint PMFs and densities, derive marginals and conditionals from them, factor with the chain rule, and end with the multivariate Gaussian, whose covariance matrix captures linear dependence.
Definition
The joint distribution of random variables and gives for discrete variables, or a joint density for continuous ones, and it sums or integrates to 1. The marginal of sums or integrates out . The conditional distribution of given divides the joint by that marginal. and are independent exactly when the joint equals the product of the marginals.
In this topic
Joint Probability Distributions
A joint distribution assigns probability to every combination of values. For two discrete variables it is a table of , and for continuous variables it is a density surface . The formula states the two requirements: every entry is non-negative, and the double sum over and equals 1. The joint contains everything, since marginals, conditionals, and correlations all follow from it. In supervised learning, the training data are samples from an unknown joint . The cost is size. A joint table over 20 binary features needs about a million entries, which is why later concepts factor it into smaller pieces.
A joint distribution lives on the product space . The joint contains strictly more information than the marginals — you can always recover marginals from the joint, but not vice versa (unless independent). Copulas separate the marginal behavior from the dependency structure.
Joint PMF: P(X=0,Y=0)=0.2, P(X=0,Y=1)=0.1, P(X=1,Y=0)=0.3, P(X=1,Y=1)=0.4. Verify it sums to 1.
Marginal Distributions
Often you care about one variable, but the model is written for several. Marginalizing sums the joint over the variable you want to ignore. As the formula shows, adds across every , and for densities an integral over does the same job. This is the law of total probability from the first topic, written for random variables. It is the operation behind a mixture model's likelihood, where the hidden cluster is summed out, and behind a VAE's evidence , where the latent code is integrated out. The warning is that marginals lose information, because many different joint tables share the same marginals.
Marginalization projects the joint onto one axis by integrating out the other variable. Geometrically, it collapses a 2D density onto a 1D shadow. In latent variable models, marginalizes over latent codes — this integral is often intractable, motivating variational inference.
From the joint PMF above, compute P(X=0), P(X=1), P(Y=0), P(Y=1).
Conditional Distributions
Observing picks out one slice of the joint table, the row where . That slice does not sum to 1, so the formula divides it by the marginal to renormalize. The result, , is a full distribution over for that fixed . A classifier learns exactly this object, and regression learns its mean, . Comparing conditionals across values of is a direct test of dependence: if every slice has the same shape, is independent of . The division fails when , which is why unseen feature combinations need smoothing.
The conditional is a slice of the joint, normalized. For a bivariate Gaussian, conditioning on yields a Gaussian whose mean shifts linearly with — this is exactly linear regression. Neural networks learn nonlinear conditional distributions .
From the joint PMF: find P(Y=0 | X=1) and P(Y=1 | X=1).
Chain Rule of Probability
Any joint distribution can be written as a product of conditionals, one variable at a time. In the formula, each is conditioned on every earlier variable . This is an identity, not an assumption. It follows from applying the product rule repeatedly. Autoregressive language models use it directly, scoring a sentence as the product of next-token probabilities. Assumptions enter only when you drop conditioning variables, as a Bayesian network or a Markov chain does. Any variable ordering is valid, but some make the conditionals much easier to learn. For long products, multiply in log space to avoid underflow.
The chain rule decomposes any joint into a product of conditionals — no approximation needed. Autoregressive models (GPT, WaveNet) directly parameterize each conditional with a neural network. The order of factorization matters for efficiency but not for correctness.
Factor P(A, B, C) using the chain rule. Then simplify if B is independent of A.
Multivariate Gaussian
The multivariate Gaussian extends the bell curve to dimensions. In the formula, is the mean vector, is the covariance matrix, and is its determinant, which scales the normalizer. The exponent is a squared Mahalanobis distance, so contours of equal density are ellipses aligned with the eigenvectors of . Diagonal entries are variances, and off-diagonal entries are covariances. Marginals and conditionals are Gaussian again, which makes Gaussian processes and Kalman filters tractable. The model fails when data are multimodal or heavy-tailed, and a nearly singular makes the inverse numerically unstable.
The multivariate Gaussian is fully characterized by first and second moments. The covariance matrix encodes all pairwise linear dependencies. Its inverse (precision matrix) reveals conditional independencies: , which is the foundation of Gaussian graphical models.
2D Gaussian: μ = [0, 0], Σ = [[1, 0.8], [0.8, 1]]. What does the correlation 0.8 tell us?
Theory Exercise
Problem:
Given a joint PMF table:
| | Y=0 | Y=1 | Y=2 | |---|---|---|---| | X=0 | 0.10 | 0.15 | 0.05 | | X=1 | 0.20 | 0.25 | 0.25 |
(a) Find marginal distributions P(X) and P(Y). (b) Find P(Y=2|X=1). (c) Are X and Y independent?
Hints:
- Sum rows for P(X), sum columns for P(Y)
- P(Y=2|X=1) = P(X=1,Y=2) / P(X=1)
- Independent if P(X=x,Y=y) = P(X=x)P(Y=y) for ALL x,y
Coding Exercise
Problem:
Sample from a bivariate Gaussian with correlation rho=0.8 and verify the key marginal/conditional facts: (1) each marginal is Gaussian with the right variance, (2) the empirical covariance matrix recovers the true Sigma, and (3) the conditional mean E[Y | X=x] follows the linear rule rho * (sigma_y/sigma_x) * x.
Hints:
- Build Sigma = [[1, 0.8], [0.8, 1]] and use np.random.multivariate_normal(mean, Sigma, size=200000).
- np.cov(samples.T) recovers the covariance matrix.
- Bin X around a target value (e.g. x=1.0) and average the corresponding Y values to estimate the conditional mean.
Related Problems on PixelBank
A model scores 87% on a test set of 500 images. Is its true accuracy 87%? Probably not exactly, because a different 500 images would give a different number. Every quantity you compute from data, whether a mean, a variance, an accuracy, or a trained weight, is a random variable, since the sample it came from was random. Reporting it without saying how much it would move is only half an answer.
The previous topic, Joint & Marginal Distributions, described how several random variables behave together. Estimation turns the question around. Given samples, we want to infer the parameters of the distribution that produced them. An estimator is a rule for doing that, and it has a bias, a variance, and a sampling distribution of its own.
We define point estimators and the properties that make them good, split their error into bias and variance, and quantify uncertainty with confidence intervals. The bootstrap then replaces formulas with resampling. We finish by comparing maximum likelihood with maximum a posteriori estimation, which reveals regularization as a prior in disguise.
Definition
An estimator is a function of the sample used to guess an unknown parameter . Its bias is , its variance measures how much it changes from sample to sample, and its mean squared error equals the squared bias plus the variance. A confidence interval is a random interval built so that it covers in a stated fraction of repeated samples.
In this topic
Point Estimators
A point estimator turns a sample into a single guess. In the formula, is any function of the observations . The sample mean estimates , the sample proportion estimates , and the sample variance estimates . Three properties judge an estimator. It is unbiased if it is right on average, consistent if it converges to as grows, and efficient if its variance is low. The appears because deviations are measured from , which is fitted to the same data and so sits closer to the points than does.
An estimator is itself a random variable — it has a sampling distribution. The Cramér-Rao lower bound sets a fundamental limit on estimator precision, where is Fisher information. MLE achieves this bound asymptotically — it is efficient.
Why does sample variance use n-1 instead of n? Show the bias of the n-denominator version.
Bias-Variance of Estimators
An estimator can miss in two ways. Bias is systematic: is the gap between its average and the truth. Variance is noise, meaning how far scatters around its own average across samples. The formula shows that mean squared error adds the squared bias and the variance, so the two can be traded. A slightly biased estimator with much smaller variance can win on MSE, and that is the case for regularization: ridge regression shrinks coefficients toward zero, which adds bias but cuts variance. The trap is judging estimators by unbiasedness alone, which can select a far noisier one.
MSE decomposes as . This is the estimation-theoretic root of the bias-variance tradeoff in ML. Regularization (L2, dropout) intentionally introduces bias to reduce variance. The sample variance uses (Bessel's correction) to eliminate bias — losing one degree of freedom for the estimated mean.
Estimator A: bias=2, variance=1. Estimator B: bias=0, variance=9. Which has lower MSE?
Confidence Intervals
A confidence interval turns an estimate into a range. In the formula, is the sample mean, is the normal critical value (1.96 for 95%), and is the standard error. With unknown and small , you use the sample and a critical value with degrees of freedom. The 95% describes the procedure: across repeated samples, 95% of intervals built this way cover the true mean. It does not mean this particular interval contains with probability 0.95, which is a Bayesian credible-interval statement. The width scales as , so halving it takes four times the data.
A 95% confidence interval means: if you repeated the experiment infinitely, 95% of computed intervals would contain the true parameter. It is a statement about the procedure, not the parameter. The width scales as , so quadrupling data halves the interval — diminishing returns on data collection.
Sample: n=100, mean=72.3, std=8.1. Construct a 95% confidence interval for the true mean.
Bootstrap Method
For many statistics, such as a median, a ratio, or an F1 score, there is no convenient formula for the standard error. The bootstrap estimates it by simulation. Treat the observed sample as a stand-in for the population, draw resamples of size with replacement, and recompute the statistic on each. In the formula, is the value from resample . The spread of these replicates approximates the sampling distribution, and their 2.5th and 97.5th percentiles give a percentile interval. Efron introduced the method in 1979. It fails for extreme statistics such as the maximum, and for dependent data unless you resample whole blocks.
The bootstrap approximates the sampling distribution by resampling with replacement from the data itself — treating the empirical distribution as a stand-in for the true distribution. This works by the Glivenko-Cantelli theorem: the empirical CDF converges uniformly to the true CDF. In random forests, bagging (bootstrap aggregating) reduces variance by averaging over bootstrap samples.
You have 50 test scores and want a 95% CI for the median. Why is bootstrap better than a formula here?
MLE vs MAP Estimation
Maximum likelihood picks the parameter under which the observed data are most probable, . MAP multiplies the likelihood by a prior before maximizing, as the formula shows. Taking logs turns the prior into an additive penalty. A Gaussian prior on weights gives an L2 penalty, as in ridge regression, and a Laplace prior gives L1, as in the lasso. A uniform prior makes MAP identical to MLE. With little data the prior matters a great deal, and with lots of data the likelihood dominates and the two agree. The failure mode of pure MLE is overfitting small samples.
MLE maximizes while MAP maximizes . Taking logs, MAP = MLE + log-prior. A Gaussian prior adds an penalty — weight decay is Bayesian. A Laplace prior gives (lasso). MLE is MAP with a uniform (improper) prior.
Coin: 3 heads in 3 flips. Compare MLE vs MAP with Beta(2,2) prior.
Theory Exercise
Problem:
A sample of 50 exam scores has mean 72.3 and standard deviation 8.1. (a) Construct a 95% confidence interval for the true mean. (b) How many students would you need to achieve a CI width less than 2? (c) If you used n-denominator for variance, what would the bias be?
Hints:
- 95% CI uses z = 1.96 for large samples
- CI width = 2 × margin = 2 × z × σ/√n. Set 2 × 1.96 × 8.1/√n < 2
- Bias of n-denominator: E[S²_n] = (n-1)/n × σ²
Coding Exercise
Problem:
Compute a bootstrap confidence interval for the median, a statistic with no simple closed-form CI. Generate one sample of 50 observations from an Exponential(scale=2) population, then resample with replacement 10,000 times, compute the median each time, and report the 95% percentile bootstrap interval. Confirm the true population median (2 * ln 2) usually falls inside.
Hints:
- True median of Exponential(scale=2) is 2*ln(2) ~ 1.386.
- Resample indices with np.random.randint(0, n, size=n) or np.random.choice(data, size=n, replace=True).
- The 95% percentile interval is np.percentile(boot_medians, [2.5, 97.5]).
Related Problems on PixelBank
Model B scores 88% on a test set and model A scores 85%. Should you ship B? The gap could be real, or it could be the luck of which 1,000 examples landed in the test set. The previous topic, Statistical Estimation, showed that every accuracy carries sampling noise, and confidence intervals measured how much. Hypothesis testing turns that noise into a decision rule. Assume there is no real difference, and ask how surprising the observed gap would be if that were true.
The framework has a fixed structure. You state a null hypothesis and an alternative, choose a test statistic, compute a p-value, and compare it with a significance level fixed in advance. Each decision can go wrong in two ways, a false alarm or a missed effect, and designing an experiment means trading one against the other.
We define null and alternative hypotheses, interpret p-values, count Type I and Type II errors and power, and apply the t-test to small samples and the chi-squared test to counts. We close with A/B testing, where peeking and multiple comparisons quietly inflate false positives.
Definition
A hypothesis test decides between a null hypothesis , a default claim such as no difference, and an alternative . It computes a test statistic from the data and a p-value, the probability of a statistic at least as extreme as the observed one if were true. is rejected when the p-value falls below a significance level fixed in advance.
In this topic
Null & Alternative Hypotheses
A test starts by naming what counts as no effect. The null hypothesis fixes the parameter at , and the alternative describes the effect you want to detect. The formula shows the two-sided alternative , which catches differences in either direction. A one-sided alternative such as looks in one direction only and has more power there. The null is what you try to reject, so failing to reject it is not evidence that it is true. Choose the direction before seeing the data, because picking the side after a peek halves the p-value dishonestly.
Hypothesis testing is a decision problem: reject or fail to reject. The asymmetry is deliberate — is the conservative default, and we demand strong evidence () to overturn it. In ML model comparison, the null hypothesis is "the new model is no better than baseline." The Neyman-Pearson lemma shows the likelihood ratio test is the most powerful test at any significance level.
A model claims 85% accuracy. You test on 200 samples and get 80% accuracy. Set up the hypotheses.
P-Values
The p-value in the formula is the probability, computed as if were true, of a test statistic at least as extreme as the observed one. A small value means the data would be surprising under the null, so you reject when the p-value is below , conventionally 0.05. Three misreadings are common. The p-value is not the probability that is true, it is not the chance of an error, and it says nothing about effect size, since a huge sample makes a trivial difference significant. The American Statistical Association's 2016 statement lists these points. Report effect sizes and intervals alongside p-values.
The p-value measures how extreme the observed statistic is under the null. It is NOT — that requires Bayes' theorem with a prior on hypotheses. Small p-values mean the data is unlikely under , but "unlikely" is not "impossible." Multiple testing inflates false positives: testing 20 features at expects 1 false positive. Bonferroni correction divides by the number of tests.
Test H₀: μ=100 with n=25, sample mean=105, σ=10. Compute the z-score and p-value (two-sided).
Type I & Type II Errors
Every test can err in two ways. A Type I error rejects a true null, a false positive, and happens with probability . A Type II error keeps a false null, a missed effect, and happens with probability . Power, , is the probability of detecting a real effect. Lowering reduces false positives but raises unless the sample grows. Power increases with sample size, effect size, and , and falls as noise grows. In model evaluation, a Type I error ships a model that is no better, while a Type II error discards a real improvement. Run the power analysis before the experiment, not after.
Type I (false positive, rate ) and Type II (false negative, rate ) trade off: decreasing one increases the other at fixed sample size. Power is the probability of correctly detecting a real effect. In ML: Type I = false alarm in anomaly detection; Type II = missed anomaly. The ROC curve traces this tradeoff as you vary the decision threshold.
α=0.05, and the test has 80% power. In 1000 experiments where H₁ is true, how many Type II errors?
T-Test
When is unknown, you estimate it with the sample standard deviation , which adds noise. The formula's statistic divides the difference by and follows a -distribution with degrees of freedom. That distribution has heavier tails than the normal, so small samples need larger statistics to reach significance, and it approaches the normal as grows. The one-sample form compares a mean with , the two-sample form compares two groups, and the paired form tests differences within pairs. It assumes roughly normal, independent observations, and strong skew in tiny samples breaks it.
The t-test uses which follows a -distribution with degrees of freedom. The t-distribution has heavier tails than the Gaussian, accounting for uncertainty in the estimated variance. As , . The paired t-test removes between-subject variability, increasing power — analogous to comparing model A vs B on the same test set rather than different sets.
Two models: A has accuracy [0.82, 0.85, 0.81, 0.84, 0.83], B has [0.86, 0.88, 0.85, 0.87, 0.89]. Is B significantly better?
Chi-Squared Test
The chi-squared test compares observed counts with the counts expected under . Each term in the formula squares the gap and divides by , so a miss of 5 matters more when only 10 were expected than when 1,000 were. The statistic is never negative, and large values are evidence against the null. For goodness of fit across categories there are degrees of freedom, and for independence in an table there are . Use it to check whether class frequencies drifted or whether two categorical features are related. The approximation breaks when expected counts fall below about 5.
The chi-squared statistic measures the discrepancy between observed and expected counts. It follows a distribution with degrees of freedom (goodness-of-fit) or (independence). In ML feature selection, the chi-squared test identifies features with statistically significant association with the target — a filter method that avoids expensive wrapper approaches.
Die rolled 60 times: {1:8, 2:12, 3:9, 4:11, 5:10, 6:10}. Expected: 10 each. Is it fair?
A/B Testing in ML
A/B testing applies the two-proportion z-test to live traffic. The formula divides the difference in success rates by a standard error built from the pooled rate and the group sizes and . The statistics are simple, and most mistakes happen in the experiment design. Checking results daily and stopping at the first significant value inflates the false-positive rate well above . Testing variants calls for a correction, such as the Bonferroni threshold . A significant 0.1% gain may not be worth deploying. Fix the metric, sample size, and stopping rule in advance, and report an interval for the lift.
A/B testing is hypothesis testing applied to product decisions: split users randomly, measure a metric, test : no difference. The minimum detectable effect (MDE) determines sample size: . Sequential testing (spending functions) allows early stopping without inflating Type I error — critical for ML deployments where waiting for full sample size wastes resources.
Model A: 850/1000 correct. Model B: 880/1000 correct. Is B significantly better?
Theory Exercise
Problem:
A model claims 85% accuracy. You test on 200 samples and observe 160 correct (80%). At α=0.05, is there evidence the true accuracy is below 85%?
Hints:
- One-sided test: H₀: p=0.85, H₁: p<0.85
- z = (p̂ - p₀) / √(p₀(1-p₀)/n)
- For one-sided test, critical value is z = -1.645
Coding Exercise
Problem:
Run a permutation test to compare two models without distributional assumptions, then validate the Type I error rate by simulation. Given two accuracy arrays, estimate the p-value for 'B is better than A' by shuffling the group labels. Separately, when both groups come from the SAME distribution, confirm that a permutation test rejects at alpha=0.05 about 5% of the time.
Hints:
- The observed statistic is mean(B) - mean(A).
- For each permutation, shuffle the pooled data, split into two groups of the original sizes, and recompute the mean difference.
- Two-sided p-value = fraction of permuted |diffs| >= |observed diff|.
Related Problems on PixelBank
A new classifier gets the first 3 test examples it sees right. Maximum likelihood, from the Statistical Estimation topic, would put its accuracy at 100%, which nobody believes. What you should believe after three examples depends on what you believed before them. A principled method should say how far three examples move that belief, and how uncertain you should remain afterwards.
The previous topic, Hypothesis Testing, treated parameters as fixed unknowns and asked how surprising the data would be. Bayesian inference treats the parameter itself as uncertain. It puts a probability distribution on the parameter and updates that distribution with Bayes' theorem as data arrive. The output is not one number but a whole posterior distribution, which answers every question about the parameter at once, including how sure you should be.
We start with the prior, likelihood, and posterior, and use conjugate priors to update in closed form. Next we extract a single MAP estimate and see why it matches regularization, then average over the posterior to make predictions. Finally we compare the Bayesian and frequentist readings of the same data.
Definition
Bayesian inference treats an unknown parameter as a random variable. Starting from a prior and a likelihood , Bayes' theorem gives the posterior , normalized by the evidence . Point estimates, credible intervals, and predictions for new data are all computed from this posterior distribution.
In this topic
Prior, Likelihood & Posterior
Bayes' theorem in the formula combines two ingredients. The prior is what you believe about the parameter before seeing data, and the likelihood says how probable the data are under each parameter value. Their product, normalized by the evidence , is the posterior . The evidence is the law of total probability applied over , and it is often the hard part to compute. Updates chain, so today's posterior becomes tomorrow's prior. Thompson sampling uses posteriors to decide which option to explore. The failure mode is a prior that rules out the truth, because zero prior probability stays zero whatever the data say.
Bayes' theorem is a change-of-variable formula on hypothesis space. The prior encodes domain knowledge before seeing data; the likelihood measures data compatibility. In ML, the prior acts as regularization — penalty is equivalent to a Gaussian prior on weights, and the MAP estimate balances data fit against prior preference.
A coin might be fair (θ=0.5) or biased (θ=0.7). Prior: P(fair)=0.6, P(biased)=0.4. You flip 3 heads in a row. Find the posterior P(biased|HHH).
Conjugate Priors
A prior is conjugate to a likelihood when the posterior stays in the prior's family, so updating reduces to arithmetic on parameters. The formula shows the main example: a prior and successes in Binomial trials give , so the prior parameters act as pseudo-counts. Other standard pairs are a Gamma prior with Poisson counts, which adds the total count to the shape and to the rate; a Normal prior with a Normal likelihood of known variance; and a Dirichlet prior with Multinomial counts, used in LDA topic models. Conjugacy is a convenience, not a truth, and it can misstate beliefs.
A conjugate prior yields a posterior in the same family: , . This makes the posterior update a simple parameter update rather than a full integral. The conjugate prior's hyperparameters act as "pseudo-counts" — behaves as if you have already seen successes and failures before any data.
You start with Beta(2, 2) prior for a coin's bias. After 8 heads and 2 tails, find the posterior and MAP estimate.
Maximum A Posteriori (MAP) Estimation
Often you want one number rather than a whole posterior. MAP estimation picks the posterior's mode, the parameter value with the highest posterior density. Because the evidence does not depend on , the formula maximizes likelihood times prior, and taking logs turns the product into a sum. A Gaussian prior contributes , an L2 penalty, and a Laplace prior contributes an L1 penalty. A regularized network is therefore doing MAP estimation, and a tighter prior means stronger regularization. MAP discards uncertainty, and the mode changes under reparameterization, so it can land on an unrepresentative spike.
MAP finds . The log-prior acts as a penalty term. With Gaussian prior: , recovering ridge regression. As data grows (), the likelihood dominates the prior, so MAP MLE — the data "overwhelms" prior beliefs.
Derive the MAP estimator for the mean of a Normal distribution with known σ=1, data x₁...xₙ, and prior μ ~ N(0, τ²).
Posterior Predictive Distribution
To predict a new observation, you could plug in one estimate of , but that ignores how unsure you are about . The posterior predictive in the formula averages the prediction over every parameter value, weighted by the posterior . Its spread therefore includes both the noise in the data and the uncertainty in the parameter. It is wider than a plug-in prediction when data are scarce and matches it when data are plentiful. Bayesian optimization and active learning use this predictive uncertainty to choose where to sample next. Outside conjugate models the integral rarely has a closed form, so it is estimated by sampling.
The posterior predictive averages predictions over all plausible parameter values weighted by their posterior probability. Unlike point estimates, this naturally captures uncertainty: predictions near sparse data regions have wider predictive distributions. This integral is often intractable, motivating Monte Carlo approximation.
With a Beta(10, 4) posterior for coin bias, what is P(next flip = heads)?
Bayesian vs Frequentist Inference
The two schools answer different questions. Frequentists treat as fixed and reason about , how the data would vary over repeated experiments, using estimators, confidence intervals, and p-values. Bayesians treat as uncertain and report , using priors, posteriors, and credible intervals. A 95% credible interval contains with posterior probability 0.95. A 95% confidence interval comes from a procedure that covers in 95% of repetitions. With lots of data the numbers usually agree. With little data a good prior helps and a poor one misleads. Deep learning mixes both, since SGD with weight decay finds MAP estimates.
Frequentists treat as fixed and reason about repeated sampling; Bayesians treat as random and condition on observed data. Credible intervals (Bayesian) directly state , while confidence intervals (frequentist) are about coverage over repeated experiments. In practice, Bayesian methods naturally handle uncertainty quantification, small samples, and sequential updating — critical for active learning and online ML systems.
You flip a coin 10 times and get 7 heads. Compare the frequentist and Bayesian 95% intervals for the true bias θ.
Theory Exercise
Problem:
A factory uses two machines. Machine A (60% of production) has a 3% defect rate. Machine B (40%) has a 7% defect rate. (a) You pick a random item and it is defective. What is P(Machine B | defective)? (b) You use a Beta(1,1) prior for Machine B's defect rate θ_B and observe 5 defective items out of 50 from Machine B. Find the posterior and the MAP estimate for θ_B.
Hints:
- Part (a): Use Bayes' theorem with P(defect|A)=0.03, P(defect|B)=0.07
- Part (b): Beta(1,1) + Binomial(50,5) gives Beta(1+5, 1+45)
- MAP for Beta(α,β) = (α-1)/(α+β-2)
Coding Exercise
Problem:
Implement sequential Beta-Binomial conjugate updating for a coin with true bias 0.7. Start from a Beta(2, 2) prior and feed in flips one at a time, updating the posterior to Beta(alpha + heads, beta + tails). Track how the posterior mean and a 95% credible interval converge to 0.7 as data accumulates, and verify the analytic update matches a grid-computed posterior.
Hints:
- Each heads increments alpha, each tails increments beta.
- Posterior mean is alpha/(alpha+beta); use scipy.stats.beta.ppf([0.025, 0.975], alpha, beta) for the credible interval.
- Cross-check by evaluating likelihood * prior on a fine grid and normalizing.
Related Problems on PixelBank
The posteriors in the previous topic, Bayesian Inference, came out in closed form because the priors were conjugate. Make the likelihood a neural network and the evidence integral runs over millions of weights, with no formula in sight. The same wall appears when you compute an expected reward over all trajectories, a VAE's marginal likelihood, or the normalizing constant of an energy-based model. The quantities you need are expectations, and the integrals behind them cannot be done by hand or on a grid. A grid with 10 points per axis in 100 dimensions has 10¹⁰⁰ cells.
Sampling methods replace the integral with an average over random draws, and their error depends on the number of samples rather than the dimension. The difficulty moves elsewhere: you need samples from a distribution that you can often evaluate only up to a constant.
We start with plain Monte Carlo averaging, then rejection sampling and importance sampling, which borrow draws from a simpler proposal. Markov chain Monte Carlo builds a random walk whose long-run visits follow the target. The final concept covers the diagnostics that tell you whether a chain can be trusted.
Definition
Sampling methods estimate an expectation by averaging over random draws. Plain Monte Carlo draws from directly. Rejection and importance sampling draw from a simpler proposal and then accept or reweight the draws. Markov chain Monte Carlo builds a Markov chain whose stationary distribution is , so it needs only up to a normalizing constant.
In this topic
Monte Carlo Estimation
Monte Carlo estimation replaces an expectation with a sample average. In the formula, are independent draws from and is the quantity being averaged. The estimate is unbiased, and by the Central Limit Theorem its standard error is , where is the standard deviation of . That rate does not depend on the dimension of , which is why sampling beats grids in high dimensions. Mini-batch gradients, policy-gradient returns, and ELBO estimates are all Monte Carlo averages. The catch is the slow rate: each extra digit of accuracy costs 100 times more samples, and rare events need far more.
Monte Carlo estimates with error regardless of dimension — this is why MC methods dominate in high dimensions where grid methods suffer the curse of dimensionality. The variance of the estimator is , so reducing through control variates or importance sampling improves convergence.
Estimate π using Monte Carlo: sample points uniformly in [0,1]² and count the fraction inside a quarter circle of radius 1.
Rejection Sampling
Suppose you can evaluate a target density but cannot sample from it. Rejection sampling draws from an easy proposal and keeps it with probability , where is chosen so that everywhere. Geometrically, you scatter points uniformly under the envelope and keep those that fall under , so the kept points follow exactly. For a normalized the acceptance rate is , so a tight envelope matters. In high dimensions the gap between and compounds and the acceptance rate collapses exponentially, which limits rejection sampling to low-dimensional building blocks.
Rejection sampling generates proposals from an easy distribution and accepts with probability where . The acceptance rate is , which decays exponentially with dimension — in dimensions, you might need proposals per accepted sample. This makes rejection sampling impractical for high-dimensional posterior inference.
Sample from f(x) ∝ x²(1-x)² on [0,1] using Uniform(0,1) as proposal. Find M and the acceptance rate.
Importance Sampling
Importance sampling draws from a proposal that is easy to sample and corrects with weights . The formula shows the identity behind it: an expectation under equals a weighted expectation under , so the average of is unbiased as long as is positive wherever is nonzero. A good proposal puts samples where is large, which can cut variance dramatically for rare events. When is known only up to a constant, divide by the sum of the weights. Off-policy RL and prioritized replay rely on these weights. A proposal with lighter tails than yields rare, enormous weights.
Importance sampling rewrites where are importance weights. The optimal proposal minimizes variance: . In practice, high-variance weights indicate poor proposal-target overlap. Self-normalized importance sampling divides by , which introduces bias but reduces variance — this is the foundation of particle filters used in sequential Bayesian inference.
Estimate P(X > 3) where X ~ N(0,1) using importance sampling with proposal N(3, 1).
Markov Chain Monte Carlo (MCMC)
MCMC samples a distribution known only up to a constant by running a random walk designed to spend time in each region in proportion to its probability. In Metropolis-Hastings, you propose from and accept it with the probability in the formula. The unknown normalizer cancels in the ratio , which is the whole trick, and with a symmetric random-walk proposal the terms cancel too. A rejected proposal repeats the current state, and that repetition is what corrects the bias. Gibbs sampling updates one coordinate at a time from its conditional and always accepts. Chains mix slowly between well-separated modes.
MCMC constructs a Markov chain whose stationary distribution is the target . Metropolis-Hastings accepts proposals with probability . The key insight: you only need up to a normalizing constant, since it cancels in the ratio. This is why MCMC works for Bayesian posteriors where is intractable. Hamiltonian Monte Carlo uses gradient information to make distant proposals with high acceptance rates.
Describe how Metropolis-Hastings would sample from a bimodal distribution p(x) ∝ exp(-x²/2) + 2exp(-(x-5)²/2).
MCMC Diagnostics & Practical Considerations
An MCMC chain always produces numbers, and nothing warns you when they are wrong. Diagnostics check two things: whether the chain has forgotten its starting point, and how much independent information its correlated samples carry. The in the formula runs several chains from dispersed starts and compares a pooled variance estimate with the average within-chain variance . Values below about 1.01 suggest the chains agree. Effective sample size discounts autocorrelation, so 5,000 sticky draws may be worth only 50 independent ones. Discard a warm-up period, and prefer longer runs to thinning. HMC and NUTS use gradients to make distant moves that are still accepted.
Burn-in discards initial samples before the chain reaches stationarity. The effective sample size (ESS) accounts for autocorrelation: where is the lag- autocorrelation. The Gelman-Rubin diagnostic () compares within-chain and between-chain variance — indicates convergence. In practice, run multiple chains from dispersed starting points and check that they agree.
You run 2 MCMC chains of length 5000 for a parameter θ. Chain 1 mean: 2.3, variance: 0.5. Chain 2 mean: 3.1, variance: 0.4. Has the sampler converged?
Theory Exercise
Problem:
You want to estimate E[X²] where X ~ Beta(2, 5). (a) Compute the exact answer analytically. (b) Describe how you would estimate it using simple Monte Carlo with N=10,000 samples. (c) Design an importance sampling scheme with proposal q(x) = Uniform(0,1) and derive the importance weights.
Hints:
- For Beta(α,β): E[X²] = α(α+1)/((α+β)(α+β+1))
- Monte Carlo: Sample x_i ~ Beta(2,5), compute (1/N)Σx_i²
- IS weights: w(x) = Beta_pdf(x; 2,5) / Uniform_pdf(x) = Beta_pdf(x; 2,5) / 1
Coding Exercise
Problem:
Implement Metropolis-Hastings from scratch to sample a bimodal target p(x) proportional to exp(-x^2/2) + 2*exp(-(x-5)^2/2), using only the unnormalized density. Run a random-walk chain, discard burn-in, and verify the sampler by comparing the empirical mean to a high-resolution numerical integral of the true normalized density.
Hints:
- Work with log-density for numerical stability; the acceptance ratio for a symmetric proposal is min(1, p(x')/p(x)).
- Propose x' = x + normal(0, step) and accept with probability exp(logp(x') - logp(x)).
- Estimate the true mean by numerically integrating x*p(x) and p(x) on a fine grid.