





















Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Esta página não é visível na pré-visualização
Não perca as partes importantes!






















Tatev Karen Follow
Monte Carlo Simulation and Variants with
Python
Your Guide to Monte Carlo Simulation and Must Know Statistical
Sampling Techniques With Python Implementation
This is your last free member-only story this month. Sign up for Medium and get an extra one
onte Carlo Simulation is based on repeated random sampling. The underlying concept of Monte Carlo is to use randomness to solve problems that might be
deterministic in principle. Monte Carlo simulation is one of the most popular
techniques to draw inferences about a population without knowing the true underlying
population distribution. This sampling technique becomes handy especially when one
doesn’t have the luxury to repeatedly sample from the original population.
Applications of Monte Carlo Simulation range from solving problems in theoretical
physics to predicting trends in financial investments.
Monte Carlo has 3 main usages: estimate parameters or statistical measures, examine the properties of the estimates, approximate integrals
This article is about these 3 usages of the Monte Carlo procedures and about 3 Monte
Carlo variants, statistical sampling techniques, which can be used to generate
independent random samples. The article will cover the following topics:
This article is suited for readers who have prior Statistical knowledge since it will cover
medium-level statistical concepts and examples. If you want to learn essential statistical
concepts from scratch, you can check my previous article about Fundamentals Of
Statistics here.
Monte Carlo Simulation Introduction
Monte Carlo simulation was initially invented to solve Buffon’s needle problem, in which
π, pi, could be estimated by dropping needles on a floor made of parallel equidistant
strips. The modern version of Monte Carlo Simulation was invented by Stanislaw
Ulam, inventor of the modern version of the Markov Chain Monte Carlo technique
d i hi k l j d J h N h
Consequently, the idea behind Monte Carlo estimation is that when we obtain an
estimate for a parameter a large number of times, let’s say M = 10000 times, then the
mean of these estimates will form a Monte Carlo unbiased estimate for that parameter.
Monte Carlo Estimation: Python Implementation
Let’s say we want to estimate a causal effect between two variables, pair of
independent and dependent variables and we have some idea about possible values of
intercept alpha and slope parameter beta.
What we can do is we can randomly sample from normal distribution to generate error
terms, dependent and independent variable values. Then we can estimate the
coefficient of beta, beta_hat, and repeat this process M = 10000 times. Then by the
LLN, the sample mean of these 10000 beta_hats will be an unbiased estimate for the
true beta. That is:
1 import numpy as np 2 import statsmodels.api as sm 3 np random seed(2021)
MC_simulation_estimation.py hosted with ❤ by GitHub view raw
3 np.random.seed(2021) 4 mu = 0 5 sigma = 1 6 n = 100 7 # assumed population parameters 8 alpha = np.repeat(0.5, n) 9 beta = 1. 10 11 def MC_estimation_slope(M): 12 MC_betas = [] 13 MC_samples = {} 14 15 for i in range(M): 16 # randomly sampling from normal distribution as error terms 17 e = np.random.normal(mu, sigma, n) 18 # generating independent variable by making sure the variance in X is larger th 19 X = 9 * np.random.normal(mu, sigma, n) 20 # population distribution using the assumd parameter values alpha/beta 21 Y = (alpha + beta * X + e) 22 23 # running OLS regression for getting slope parameters 24 model = sm.OLS(Y.reshape((-1, 1)), X.reshape((-1, 1))) 25 ols_result = model.fit() 26 coeff = ols_result.params 27 28 MC_samples[i] = Y 29 MC_betas.append(coeff) 30 MC_beta_hats = np.array(MC_betas).flatten() 31 return(MC_samples, MC_beta_hats) 32 33 MC_samples, MC_beta_hats = MC_estimation_slope(M = 10000) 34 beta_hat_MC = np.mean(MC_beta_hats) 35 36 MC_beta_hats 37 [1.50017256 1.48787904 1.49935872 ... 1.51933708 1.49773307 1.4857404 ] 38 39 beta_hat_MC 40 1.
p p p
might not be very useful when examining the properties of Linear Regression estimates
since most of the statistical software packages already provide measures to examine
the estimates. However, in the case of other estimates using Monet Carlo Estimation
might be the only way to find out whether the estimator is unbiased, efficient, and
consistent.
Is the Estimate Unbiased?
The bias of an estimator is the difference between its expected value and the true value
of the parameter being estimated and can be expressed as follows:
When we state that the estimator is unbiased what we mean is that the bias is equal to
zero, which implies that the expected value of the estimator is equal to the true
parameter value, that is:
To check whether the estimator is unbiased, we can use the Monte Carlo samples of
beta_hats that we obtained in the previous step and draw this sampling distribution.
Then, if this sampling distribution is centered around the true parameter value, then
the estimator is unbiased.
From the figure we can see that, the sampling distribution of beta estimates that we
obtained using Monte Carlo simulation with 10000 iterations, is centered around the
true parameter beta. So, the Monte Carlo estimate of beta_hat is unbiased.
MC_simulation_unbiasedness.py hosted with ❤ by GitHub view raw
1 import matplotlib.pyplot as plt 2 3 counts, bins, ignored = plt.hist(MC_beta_hats, 20, density = True, color = 'purple', la 4 plt.title("Monte Carlo Simulation for LR beta estimate M = 10000") 5 plt.axvline(beta, 0,40, color = 'y', label = 'Population beta') 6 plt.xlabel("beta") 7 plt.ylabel("Probability") 8 plt.legend() 9 plt.show()
MC_simulation_consistency_efficiency.py hosted with ❤ by GitHub view raw
1 import matplotlib.pyplot as plt 2 MC_samples1000, MC_beta_hats1000 = MC_estimation_slope(M = 1000) 3 MC_samples10000, MC_beta_hats10000 = MC_estimation_slope(M = 10000) 4 5 # MC with M = 1000 6 counts, bins, ignored = plt.hist(MC_beta_hats1000, 20, density = True, color = 'purple 7 plt.title("Monte Carlo Simulation for LR beta estimate M = 1000") 8 plt.axvline(beta, 0,40, color = 'y', label = 'Population beta') 9 plt.xlabel("beta") 10 plt.ylabel("Probability") 11 plt.legend() 12 plt.show() 13 14 # MC with M = 10000 15 counts, bins, ignored = plt.hist(MC_beta_hats10000, 20, density = True, color = 'purpl 16 plt.title("Monte Carlo Simulation for LR beta estimate M = 10000") 17 plt.axvline(beta, 0,40, color = 'y', label = 'Population beta') 18 plt.xlabel("beta") 19 plt.ylabel("Probability") 20 plt.legend() 21 plt.show()
Approximating Integrals with Monte Carlo
For known functions such as the Normal distribution function, calculating integral
might be simple and would not require the usage of MC. However, for more
complicated functions computing integrals might be very hard and in those situations
using MC could be the only way to calculate this integral.
MC for approximating integrals is based on the LLN and the idea behind it is that if we
can generate random samples xi from a given distribution P(x), then we can estimate
the expected value of a function under this distribution by summation, rather than
integration. Stated differently, we can find the value of an integral by determining the
average value of its integrand, h(x). The MC is based on this principle, as we saw
earlier.
Importance Sampling
Importance sampling is one way to make Monte Carlo simulations converge much
faster. Moreover, Importance sampling results also in lower variance compared to the
naive Monte Carlo approach. It is used for estimating the expected value of a certain
h(x) function from target distribution g(x) while having access to some f(x) function.
The idea is to use some proposal distribution f(x) to sample from and using
importance weights w = g(x)/f(x) which mitigate this effect of overestimating or
underestimating the target distribution g(x).
MC_integral_approximation.py hosted with ❤ by GitHub view raw
16 MC_prob(M = 10000, mu = 10, sigma = 2)
Importance Sampling: Python Implementation
Let’s say we want to estimate the expected value of a random variable X which follows
Exponential Distribution. So, our target distribution is exponential , g(x) = Exp(1),
and the h(x) = exp(-X + cos(X)).
For Importance sampling we need to choose a proposal distribution that is as close as
possible to the target distribution, hence we choose f(x) = Exp(2). Given that the pdf
of the exponential function is exp(-lambda*x), then we have:
Following graph visualizes the h(x), the target distribution g(x) and the proposal
distribution f(x) plots. As we can see, the proposal distribution is very close to the
target distribution. The f(x) is used to randomly sample 1000 observations and
calculate each time the expression g(x)/f(x)*h(x), that is to calculate the importance
weight and multiply it with h(x). Then, we take the mean of these values which gives
us 1.52 which is the Expected Value we were looking for.
1 import numpy as np 2 import matplotlib.pyplot as plt 3 4 #function in the expected value
Importance_Sampling.py hosted with ❤ by GitHub view raw
5 def h(x): 6 value = np.exp(-1x + np.cos(x)) 7 return(value) 8 9 #proposal function which we have access to Exp(2) 10 def f(x): 11 value = np.exp(-2x) 12 return(value) 13 14 #target distribution function 15 def g(x): 16 value = np.exp(-1x) 17 return(value) 18 19 def Importance_sampling(M): 20 importance_samples = [] 21 for i in range(M): 22 #sampling from the proposal distribution f(x): Exp(2) 23 x = np.random.exponential(2) 24 importance_weight = g(x)/f(x) 25 importance_sample = importance_weighth(x) 26 importance_samples.append(importance_sample) 27 28 return(importance_samples) 29 30 importance_values = Importance_sampling(M = 1000) 31 Importance_Sampling_expected_value = np.mean(importance_values) 32 x_values = np.arange(0,2.5,0.001) 33 y_proposal = np.array(f(x_values)) 34 y_target = np.array(g(x_values)) 35 y_h = np.array(h(x_values)*g(x_values)) 36 plt.plot(x_values,y_proposal, color ='black',linewidth = 2,label = 'Proposal Distributi 37 plt.plot(x_values,y_target, color ='purple',linewidth = 2,label = 'Target Distribution 38 plt.plot(x_values,y_h, color ='orange',linewidth = 2,label = 'Function for Expected Val 39 plt.title("Importance Sampling with Exp(1)") 40 plt.xlabel("Expected Values = " + str(Importance_Sampling_expected_value)) 41 plt.legend() 42 plt.show()
Rejection Sampling
Rejection Sampling is usually used to generate independent samples from the
unnormalized target distribution. The idea behind this Monte Carlo sampling variant
is that if we want to generate random samples from target unnormalized distribution
P(x) then we can use some proposal distribution Q(x), a normalization constant c
such that cQ(x) is an upper bound for some auxiliary distribution P*(x) where P(x) =
P*(x) / c to come up with a list of samples from which the accepted values will form
independent samples from the target P(X) distribution.
1: Choose a proposal function Q(X) that is close to target distribution P(X)
2: Choose a normalization constant c such that P*(x) ≤ cQ(x)
3: Choose auxiliary distribution P(X) s.t. P(x) = P(x)/c
4: Generate random samples, x, from Q(X)
5: Generate random samples, u, from Unif(0 , cQ(x))
6: Repeat step 1 and 2 M times (e.g. 10000 times)
7: Accept x if u ≤ P*(x) and reject otherwise
Important Requirements for Rejection Sampling:
Proposal distribution Q(x) to sample from (Uniform or Gaussian)
Normalization constant c such that c*Q(x)
Auxiliary distribution P*(x)
Access to sampling from the proposal distribution
Rejection Sampling: Python Implementation
j p g y p
Let's say we want to generate independent samples from a mixture of Normal
Distributions, which we expect to have a distribution similar to p*(x) = N(30,10) +
N(80,20). We have access to Normal and Uniform distributions to sample from to
generate these target samples. We can use a proposal function Q(x) = N(50,30), with a
normalization constant c = max(P*(x)/Q(x)).
We then follow the steps described earlier to generate samples from which a very large
amount gets rejected and some get accepted. Following histogram visualizes the set of
accepted samples which are independent samples from a Mixture of Normal
distribution, while having access only to the Normal and Uniform random generators.
1 import numpy as np 2 from scipy.stats import norm 3 4 mu_ps = 30 5 sigma_ps = 10 6 mu_ps2 = 80 7 sigma_ps2 = 20 8 9 mu q = 50