Advanced Monte Carlo I: variance reduction
Monte Carlo error is σ/√N, so reducing it tenfold requires a hundredfold increase in computation unless σ is reduced. Build classical variance-reduction methods and apply them to rare-event simulation, accounting for their assumptions, bias and cost.
After this lesson you can
- Prove when antithetic variates reduce variance and measure the efficiency gain in variance per cost.
- Derive the optimal control-variate coefficient and its regression relationship, extending it to multiple controls.
- Implement stratified sampling with proportional and Neyman allocation, and Latin hypercube sampling.
- Apply conditional Monte Carlo when part of a problem admits an analytic solution.
- Design rare-event importance proposals using exponential tilting and cross-entropy, and diagnose infinite variance.
Before you start
- 29Taxonomy of simulation uncertainty sourcesGillespie stochastic simulation algorithm
- 09Monte Carlo estimatorMonte Carlo error and confidence intervalsHeavy tails and Monte Carlo failureInverse transform samplingRejection sampling
- 04Law of total varianceConditional expectation
- 11Linear regression model and least-squares fitting
- 05Gaussian linear model
- 14Self-normalized importance samplingImportance-sampling effective sample size
- 07Kullback-Leibler divergence (relative entropy)
Accuracy per unit of work
For independent samples with finite variance, the standard error of a mean is . Reducing it tenfold requires one hundred times as many samples if everything else stays equal. Estimator efficiency combines variance and cost: for a fixed budget, compare approximately . Include pilots, generation, evaluation and wall time when they affect the decision. Variance does not measure bias or by itself detect an importance proposal that fails to cover the event.
The functions are , and a localized Gaussian peak, on the unit square. We evaluate 200 independent replicates per method and budget. The control uses with mean one, with coefficient estimated in an independent 5000-point pilot; stratification divides each axis into the same number of intervals. Bands show empirical dispersion and do not guarantee 95% coverage for a skewed distribution. Latin hypercube and strata include additional operations; the plotted budget counts function calls, not measured time.
Pairs and controls
Antithetic variates pair and . If is increasing, is decreasing and their covariance is nonpositive: using an independent copy ,
At the same cost of two evaluations, the pair average has variance no greater than the average of two independent samples. For , however, : the two evaluations are identical and the average’s variance doubles relative to two independent ones. Monotonicity, correlation and cost matter.
For a control variate with known mean , use . Its expectation matches that of if is fixed, and
The optimum is the regression slope with an intercept. For multiple controls solve if the matrix is invertible; redundant controls require regularization or dimension reduction. Estimating with the same data can introduce finite-sample bias. An independent pilot or cross-fitting can separate fitting from estimation; pilot cost counts.
Strata, hypercubes and conditioning
Stratification divides space into regions with probabilities and estimates each mean. With independent samples within each stratum, variance is . If costs are equal and is known, Neyman allocation minimizes this variance for a given total; proportional allocation uses . Unknown variances are estimated with a pilot and each stratum needs enough samples. With different costs the optimal allocation changes.
Latin hypercube sampling places one observation in each interval of each marginal and permutes coordinates. It often helps when low-dimensional additive effects dominate; interactions may reduce the gain. Points within a design are not independent, so the naive IID standard error is invalid. Repeat randomized designs independently and calculate uncertainty across their estimates.
Conditional Monte Carlo replaces with . The law of total variance ensures provided the second moment exists. Gain per unit time also depends on the cost of computing that expectation. For independent normal and event , conditioning on replaces the indicator with .
Importance sampling and rare events
Importance sampling generates and estimates with . It needs wherever is nonzero, and a finite second moment for usual intervals. For an indicator, the ideal proposal would give zero variance, but depends on the unknown probability. Gaussian tilting toward the tail is a practical approximation.
A narrow proposal can have infinite variance despite producing an apparently stable sample. For , and event , makes the estimator’s second moment diverge. In the boundary case the mean and tail also matter; we do not generalize the strict inequality to the boundary. Weight ESS does not guarantee finite variance or automatically measure tail accuracy. In the figure the finite second moment is numerically integrated over a truncated region; divergence is determined analytically.
Cross-entropy approximates the event’s conditional distribution within a chosen family. When initial events are insufficient, intermediate quantile levels gradually move the proposal closer; elites are weighted by . Fitting and the final sample are independent in the lab. The method depends on family, levels and support; it does not promise an error tolerance in every realization. Splitting and subset simulation are alternatives using successive survival levels, with their own dependencies and diagnostics. The review by Kroese, Rubinstein and Glynn develops these ideas.
Lab: reproducible tools
The following functions implement pairs, control, strata, hypercube, Asian option, Gaussian tilting and cross-entropy. Standard errors are calculated across independent units: pairs for antithetics, samples within each stratum, or complete-design replicates for the hypercube.
"""Estimadores de Monte Carlo, controles independientes y eventos raros."""
import numpy as np
from scipy.special import ndtr,ndtri
def antithetic(f,n,rng):
"""n pares: devuelve media, error estándar entre pares y coste 2n."""
if n<2:raise ValueError('se necesitan al menos dos pares')
u=rng.random(n);z=(f(u)+f(1-u))/2
return float(z.mean()),float(z.std(ddof=1)/np.sqrt(n)),2*n
def control_estimate(y,c,mu_c,beta):
"""beta fijado antes de obtener (y,c); sin sesgo si mu_c es exacta."""
z=np.asarray(y)-beta*(np.asarray(c)-mu_c)
return float(z.mean()),float(z.std(ddof=1)/np.sqrt(len(z)))
def stratified(f,n_per,rng):
"""Estratos de igual tamaño con n_per muestras independientes en cada uno."""
if len(n_per)<1 or np.any(np.asarray(n_per)<2):raise ValueError('se requieren al menos dos muestras por estrato')
k=len(n_per);values=[f((i+rng.random(int(n)))/k) for i,n in enumerate(n_per)]
estimate=np.mean([v.mean() for v in values])
se=np.sqrt(sum(v.var(ddof=1)/len(v) for v in values))/k
return float(estimate),float(se)
def latin_hypercube(n,d,rng):
return np.column_stack([(rng.permutation(n)+rng.random(n))/n for _ in range(d)])
def asian_pair(n,rng,S0=100.,K=100.,r=.03,sigma=.2,T=1.,m=12):
dt=T/m;Z=rng.standard_normal((n,m))
logS=np.log(S0)+np.cumsum((r-sigma**2/2)*dt+sigma*np.sqrt(dt)*Z,axis=1)
paths=np.exp(logS);discount=np.exp(-r*T)
return discount*np.maximum(paths.mean(axis=1)-K,0),discount*np.maximum(np.exp(logS.mean(axis=1))-K,0)
def asian_geometric_price(S0=100.,K=100.,r=.03,sigma=.2,T=1.,m=12):
mean=np.log(S0)+(r-sigma**2/2)*T*(m+1)/(2*m)
var=sigma**2*T*(m+1)*(2*m+1)/(6*m*m);sd=np.sqrt(var)
d2=(mean-np.log(K))/sd;d1=d2+sd
return np.exp(-r*T)*(np.exp(mean+var/2)*ndtr(d1)-K*ndtr(d2))
def gaussian_tail(a,n,rng,mu=None,sigma=1.):
"""IS ordinario no autonormalizado; pesos y contribuciones para diagnóstico."""
if mu is None:mu=a
x=rng.normal(mu,sigma,n)
logw=np.log(sigma)-.5*x*x+.5*((x-mu)/sigma)**2
z=np.exp(logw)*(x>a);w=np.exp(logw)
return float(z.mean()),float(z.std(ddof=1)/np.sqrt(n)),float(w.sum()**2/np.sum(w*w)),z
def cross_entropy_is(log_target_indicator,family,n_iter,rho):
"""Ajuste de media gaussiana en covarianza identidad para un score creciente.
log_target_indicator(x) devuelve (score, log_indicador), con cero en el
evento final y -inf fuera. family contiene mean, n, rng y threshold.
Los umbrales intermedios usan cuantiles; las élites se ponderan p/q.
Se devuelve una propuesta; la estimación usa una muestra independiente.
"""
mean=np.array(family['mean'],dtype=float);n=int(family['n']);rng=family['rng'];threshold=float(family['threshold'])
if n<10 or not 0<rho<1 or n_iter<1:raise ValueError('parámetros inválidos')
history=[]
for _ in range(n_iter):
x=rng.normal(size=(n,len(mean)))+mean
score,log_indicator=log_target_indicator(x)
level=min(threshold,float(np.quantile(score,1-rho)))
elite=(score>=level)
if level>=threshold:elite &= np.isfinite(log_indicator)
logw=-x@mean+.5*(mean@mean)
lw=logw[elite];w=np.exp(lw-lw.max())
mean=np.sum(x[elite]*w[:,None],axis=0)/w.sum()
history.append((level,mean.copy()))
return mean,history
def tandem_score(x):
"""Máximo tiempo total de un trabajo en dos servidores FIFO."""
arrival=np.cumsum(x[:,:,0],axis=1);end1=np.zeros(len(x));end2=np.zeros(len(x));largest=np.zeros(len(x))
for j in range(x.shape[1]):
end1=np.maximum(arrival[:,j],end1)+x[:,j,1]
end2=np.maximum(end1,end2)+x[:,j,2]
largest=np.maximum(largest,end2-arrival[:,j])
return largest
def tandem_occupancy(x):
"""Mayor número simultáneo en la red al llegar un trabajo."""
arrival=np.cumsum(x[:,:,0],axis=1);end1=np.zeros(len(x));end2=np.zeros(len(x));departures=[]
for j in range(x.shape[1]):
end1=np.maximum(arrival[:,j],end1)+x[:,j,1]
end2=np.maximum(end1,end2)+x[:,j,2];departures.append(end2.copy())
departure=np.stack(departures,axis=1)
return np.max(np.sum((arrival[:,None,:]<=arrival[:,:,None])&(departure[:,None,:]>arrival[:,:,None]),axis=2),axis=1)
def queue_ce(threshold=15.,jobs=10,n=4000,iterations=5,rho=.1,seed=42,score_fn=tandem_score):
"""Ajusta tasas exponenciales por élites ponderadas; muestra final independiente."""
rng=np.random.default_rng(seed);target=np.array([1.,1.5,1.5]);rates=target.copy();history=[]
for _ in range(iterations):
x=rng.exponential(1/rates,size=(n,jobs,3));score=score_fn(x);level=min(threshold,float(np.quantile(score,1-rho)))
elite=score>=level;logw=np.sum(np.log(target/rates)+(rates-target)*x,axis=(1,2))
lw=logw[elite];w=np.exp(lw-lw.max());means=np.sum(x[elite]*w[:,None,None],axis=(0,1))/(jobs*w.sum())
proposed=np.clip(1/means,.2*target,1.8*target);rates=.3*rates+.7*proposed
history.append((level,rates.copy()))
return target,rates,history
def queue_estimate(target,rates,threshold,n=20000,jobs=10,seed=123,score_fn=tandem_score):
rng=np.random.default_rng(seed);x=rng.exponential(1/rates,size=(n,jobs,3))
hit=score_fn(x)>=threshold
logw=np.sum(np.log(target/rates)+(rates-target)*x,axis=(1,2))
z=np.exp(logw)*hit
return float(z.mean()),float(z.std(ddof=1)/np.sqrt(n)),int(hit.sum())rng=np.random.default_rng(42);f=lambda x:np.exp(x)
u=rng.random(2000);plain=(f(u).mean(),f(u).std(ddof=1)/np.sqrt(len(u)))
print('IID estimación y error estándar',plain)
print('antitético 1000 pares',antithetic(f,1000,rng))
print('estratos de igual peso',stratified(f,np.full(10,200),rng))
rep=np.array([np.exp(latin_hypercube(200,1,rng)[:,0]).mean() for _ in range(100)])
print('hipercubo 100 diseños: media y error estándar entre diseños',rep.mean(),rep.std(ddof=1)/np.sqrt(len(rep)))
print('integral exacta',np.e-1)The first position in the figure is reproduced with 200 replicates of 64 evaluations per method and an independent pilot. The five estimates in each replicate use their own samples; pilot cost is separate.
rng=np.random.default_rng(41);fun=lambda x:np.exp(x[:,0]+x[:,1])
pilot=rng.random((5000,2));v=fun(pilot);c=pilot.sum(axis=1)
beta=np.cov(v,c,ddof=1)[0,1]/np.var(c,ddof=1)
m=8;n=m*m;rep={key:[] for key in ('plain','anti','control','strat','lhs')}
for _ in range(200):
x=rng.random((n,2));rep['plain'].append(fun(x).mean())
rep['control'].append(np.mean(fun(x)-beta*(x.sum(axis=1)-1)))
x=rng.random((n//2,2));rep['anti'].append(np.mean((fun(x)+fun(1-x))/2))
x=np.array([(np.array([i,j])+rng.random(2))/m for i in range(m) for j in range(m)])
rep['strat'].append(fun(x).mean())
rep['lhs'].append(fun(latin_hypercube(n,2,rng)).mean())
for key,v in rep.items():print(key,'media',np.mean(v),'desviación entre réplicas',np.std(v,ddof=1))The Asian option uses twelve observations of a geometric Brownian path, , , , , with no dividends. The geometric mean of prices has a normal logarithm, so its option price is known; that price controls the arithmetic payoff. The pilot is discarded and does not contribute to the final sample.
rng=np.random.default_rng(42);yp,cp=asian_pair(5000,rng)
beta=np.cov(yp,cp,ddof=1)[0,1]/np.var(cp,ddof=1)
y,c=asian_pair(20000,rng);known=asian_geometric_price()
controlled=y-beta*(c-known)
print('precio geométrico analítico',known,'beta piloto',beta)
print('aritmética IID, SE',y.mean(),y.std(ddof=1)/np.sqrt(len(y)))
print('control, SE',controlled.mean(),controlled.std(ddof=1)/np.sqrt(len(y)))
print('reducción de varianza observada',np.var(y,ddof=1)/np.var(controlled,ddof=1))rng=np.random.default_rng(123);x=rng.normal(size=20000);y=rng.normal(size=20000);a=3.
raw=(x+y>a).astype(float);conditional=ndtr(x-a)
print('directo',raw.mean(),'SE',raw.std(ddof=1)/np.sqrt(len(raw)))
print('condicional',conditional.mean(),'SE',conditional.std(ddof=1)/np.sqrt(len(raw)))
print('referencia normal',ndtr(-a/np.sqrt(2)))A controlled cross-entropy test uses a normal tail of probability . The proposal is fitted with pilot samples and estimated with 10000 subsequent samples; the normal reference allows this realization to be checked, but an error below 5% for one seed is not a probabilistic guarantee for every run.
rng=np.random.default_rng(7);a=ndtri(1-1e-8)
target=lambda x:(x[:,0],np.where(x[:,0]>a,0.,-np.inf))
family={'mean':np.zeros(1),'n':3000,'rng':rng,'threshold':a}
mu,history=cross_entropy_is(target,family,5,.1)
estimate,se,ess,z=gaussian_tail(a,10000,rng,float(mu[0]))
print('niveles y medias',history)
print('estimación, SE, ESS pesos',estimate,se,ess,'error relativo',abs(estimate/1e-8-1))The next synthetic network has ten jobs, exponential arrivals of rate one and two FIFO servers with exponential service of rate 1.5. The event is that some job spends at least 15 time units in the network. The algorithm adapts rates using elites and weights, then estimates with another seed. The proposal is limited to less than twice each original rate, a sufficient condition for a finite second moment of the full weight in this exponential model. The IID comparison uses 100000 replicates and may contain very few events.
target,rates,history=queue_ce()
print('tasas adaptadas',rates,'niveles',[h[0] for h in history])
print('IS: estimación, SE, eventos bajo propuesta',queue_estimate(target,rates,15.,n=20000))
print('IID: estimación, SE, eventos',queue_estimate(target,target,15.,n=100000))As a different overflow criterion, consider a capacity of nine jobs across the network and count whether ten coexist. Occupancy can increase only on an arrival; compare the maximum with the threshold. This realization does not reach the final level during five fitting steps, but still uses the resulting proposal and independent samples to estimate the event; the proposal is not claimed to be optimal.
target,rates,history=queue_ce(threshold=10,score_fn=tandem_occupancy)
print('tasas',rates,'niveles',[h[0] for h in history])
print('IS',queue_estimate(target,rates,10,n=20000,score_fn=tandem_occupancy))
print('IID',queue_estimate(target,target,10,n=20000,score_fn=tandem_occupancy))For an illustrative reliability model, failure means with and . It does not represent a real structure. Compare a tilted proposal with IID; if no IID failures occur, a zero result does not prove zero probability.
rng=np.random.default_rng(42);a=ndtri(1-1e-6)
estimate,se,ess,z=gaussian_tail(a,10000,rng)
naive=(rng.normal(size=100000)>a)
print('umbral',a,'IS',estimate,'SE',se,'ESS pesos',ess,'eventos ponderados',np.count_nonzero(z))
print('IID',naive.mean(),'fallos',naive.sum(),'referencia 1e-6')Exercises
Step 1 of 3. What is the sign of (f(U)−f(V))(f(1−U)−f(1−V))?
Step 1 of 3. What is the variance as a function of β?
import numpy as np
def cross_entropy_is(log_target_indicator,family,n_iter,rho):
pass