


























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



























1 What Do We Mean by “Simulation”? 2
2 How Do We Simulate Stochastic Models? 2 2.1 Chaining Together Random Variables............... 2 2.2 Random Variable Generation.................... 3 2.2.1 Transformations....................... 3 2.2.2 Quantile Method....................... 3 2.2.3 Rejection Method...................... 4 2.2.4 The Metropolis Algorithm and Markov Chain Monte Carlo 7 2.2.5 Mixtures and Kernel Density Estimates.......... 8 2.2.6 Generating Uniform Random Numbers........... 9
3 Why Simulate? 13 3.1 Understanding the Model...................... 13 3.2 Checking the Model......................... 18
4 The Method of Simulated Moments 25 4.1 The Method of Moments....................... 25 4.2 Adding in the Simulation...................... 26 4.3 An Example: Moving Average Models and the Stock Market.. 26
5 Exercises 32
A Some Design Notes on the Method of Moments Code 33 As you may have noticed, we are now seven lectures into a statistics class and have said almost nothing, so far, about uncertainty. The next lecture will in fact be about a general and powerful way of quantifying uncertainty in data analysis, called “bootstrapping”, but we need to do some preliminary work first today. You will recall from your previous statistics courses that quantifying uncer- tainty in statistical inference requires us to get at the sampling distributions
of things like estimators. When the very strong simplifying assumptions of ba- sic statistics courses do not apply^1 , or when estimators are themselves complex objects, like kernel regression curves or histograms, there is little hope of being able to write down sampling distributions in closed form. We get around this by using simulation to approximate the sampling distributions we can’t calculate. Today’s lecture, therefore, is all about simulating stochastic models.
A stochastic model is a mathematical story about how the data could have been generated. Simulating the model means implementing it, step by step, in order to produce something which should look like the data — what’s sometimes called synthetic data, or surrogate data, or a realization of the model. In a stochastic model, some of the steps we need to follow involve a random component, and so multiple simulations starting from exactly the same initial conditions will not give exactly the same outputs or realizations. Rather, will be a distribution over the realizations. Doing large numbers of simulations gives us a good estimate of this distribution. For a trivial example, consider a model with three random variables, X 1 ∼ N (μ 1 , σ^21 ), X 2 ∼ N (μ 2 , σ 22 ), with X 1 |= X 2 , and X 3 = X 1 + X 2. Simulating from this model means drawing a random value from the first normal distribution for X 1 , drawing a second random value for X 2 , and adding them together to get X 3. The marginal distribution of X 3 , and the joint distribution of (X 1 , X 2 , X 3 ), are implicit in this specification of the model, and we can find them by running the simulation. In this particular case, we could also find the distribution of X 3 , and the joint distribution, by probability calculations of the kind you learned how to do in 36-225 and 36-226. For instance, X 3 is N (μ 1 + μ 2 , σ^21 + σ^22 ). These analytical probability calculations can usually be thought of as just short-cuts for exhaustive simulations.
Stochastic models are usually specified by sets of conditional distributions for one random variable, given some other variable or variables. For instance, a simple linear regression model might have the specification
X ∼ N (μx, σ 12 ) (1) Y |X ∼ N (β 0 + β 1 X, σ 22 ) (2) (^1) In 36-401, you will have seen results about the sampling distribution of linear regression coefficients when the linear model is true, and the noise is Gaussian with constant variance. As an exercise, try to get parallel results when the noise has a t distribution with 10 degrees of freedom.
Example. The CDF of the exponential distribution with rate λ is 1 − e−λx. The quantile function Q(p) is thus − log (1 λ− p). (Notice that this is positive, because 1 − p < 1 and so log (1 − p) < 0, and that it has units of 1/λ, which are the units of x, as it should.) Therefore, if U Unif(0, 1), then − log (1 λ− U^ )∼ Exp(λ). This is the method used by rexp(). Example. The Pareto distribution or power law is a two-parameter fam-
ily, f (x; α, x 0 ) = α x− 01
x x 0
)−α if x ≥ x 0 , with density 0 otherwise. Integration
shows that the cumulative distribution function is F (x; α, x 0 ) = 1 −
x x 0
)−α+ .
The quantile function therefore is Q(p; α, x 0 ) = x 0 (1 − p)−^ α^1 − 1
. (Notice that this has the same units as x, as it should.) Example. The standard Gaussian N (0, 1) does not have a closed form for its quantile function, but there are fast and accurate ways of calculating it numerically (they’re what stand behind qnorm), so the quantile method can be used. In practice, there are other transformation methods which are even faster, but rely on special tricks. Since QZ (U ) has the same distribution function as X, we can use the quantile method, as long as we can calculate QZ. Since QZ always exists, in principle this solves the problem. In practice, we need to calculate QZ before we can use it, and this may not have a closed form, and numerical approximations may be in tractable.^3
2.2.3 Rejection Method
Another general approach, which avoids needing the quantile function, is the rejection method. Suppose that we want to generate Z, with probability density function fZ , and we have a method to generate R, with p.d.f. ρ, called the proposal distribution. Also suppose that fZ (x) ≤ ρ(x)M , for some constant M > 1. For instance, if fZ has a limited range [a, b], we could take ρ to be the uniform distribution on [a, b], and M the maximum density of fZ. The rejection method algorithm then goes as follows.
If ρ is uniform, this just amounts to checking whether M U < fZ (R), with M the maximum density of Z. Computationally, the idea looks like Example 1. (^3) In essence, we have to solve the nonlinear equation FZ (x) = p for x over and over — and that assumes we can easily calculate FZ.
rrejection.1 <- function(dtarget,dproposal,rproposal,M) { rejected <- TRUE while(rejected) { R <- rproposal(1) U <- runif(1) rejected <- (MUdproposal(R) < dtarget(R)) } return(R) }
rrejection <- function(n,dtarget,dproposal,rproposal,M) { replicate(n,rrejection.1(dtarget,dproposal,rproposal,M)) }
Code Example 1: An example of how the rejection method would be used. The arguments dtarget, dproposal and rproposal would all be functions. This is not quite industrial-strength code, because it does not let us pass argu- ments to those functions flexibly. See online code for comments.
One way to understand the rejection method is as follows. Imagine drawing the curve of fZ (x). The total area under this curve is 1, because
dxfZ (x) = 1.
The area between any two points a and b on the horizontal axis is
∫ (^) b a dxfZ^ (x) = FZ (b)−FZ (a). It follows that if we could uniformly sample points from the area between the curve and the horizontal axis, their x coordinates would have ex- actly the distribution function we are looking for. If ρ is a uniform distribution, then we are drawing a rectangle which just encloses the curve of fZ , sampling points uniformly from the rectangle (with x coordinates R and y coordinates M U ), and only keeping the ones which fall under the curve. When ρ is not uni- form, but we can sample from it nonetheless, then we are uniformly sampling from the area under M ρ, and keeping only the points which are also below fZ. Example. The beta distribution, f (x; a, b) = (^) Γ(Γ(aa)Γ(+bb)) xa−^1 (1 − x)b−^1 , is de-
fined on the unit interval^4. While its quantile function can be calculated and so we could use the quantile method, we could also use the reject method, taking the uniform distribution for the proposals. Figure 1 illustrates how it would go for the Beta(5,10) distribution The rejection method’s main drawback is speed. The probability of accepting on any given pass through the algorithm is 1/M. (Exercise: Why?) Thus produce n random variables from it takes, on average, nM cycles. (Exercise: Why?) Clearly, we want M to be as small, which means that we want the proposal distribution ρ to be close to the target distribution fZ. Of course
(^4) Here Γ(a) = R^ ∞ 0 dxe −xxa− (^1). It is not obvious, but for integer a, Γ(a) = (a − 1)!. The
distribution gets its name because (^) Γ(Γ(aa)Γ(+bb)) is called the beta function of a and b, a kind of
continuous generalization of
`a+b a
´
. The beta distribution arises in connection with problems about minima and maxima, and inference for binomial distributions.
if we’re using the rejection method because it’s hard to draw from the target distribution, and the proposal distribution is close to the target distribution, it may be hard to draw from the proposal.
2.2.4 The Metropolis Algorithm and Markov Chain Monte Carlo
One very important, but tricky, way of getting past the limitations of the re- jection method is what’s called the Metropolis algorithm. Once again, we have a density fZ from which we wish to sample. Once again, we introduce a distribution for “proposals”, and accept or reject proposals depending on the density fZ. The twist now is that instead of making independent proposals each time, the next proposal depends on the last accepted value — the proposal distribution is a conditional pdf ρ(r|z). Assume for simplicity that ρ(r|z) = rho(z|r). (For instance, we could have a Gaussian proposal distribution centered on z.) Then the Metropolis algorithm goes as follows.
Mostly simply, the algorithm is run until t = n, at which point it returns Z 1 , Z 2 ,... Zn. In practice, better results are obtained if it’s run for n + n 0 steps, and the first n 0 values of Z are discarded — this is called “burn-in”. Notice that if fZ (R) > fZ (Zt), then R is always accepted. The algorithm always accepts proposals which move it towards places where the density is higher than where it currently is. If fZ (R) < fZ (Zt), then the algorithm accepts the move with some probability, which shrinks as the density at R gets lower. It should not be hard to persuade yourself that the algorithm will spend more time in places where fZ is high. It’s possible to say a bit more. Successive values of Zt are dependent on each other, but Zt+1 |= Zt− 1 |Zt — this is a Markov process. The target distribution fZ is in fact exactly the stationary distribution of the Markov process. If the proposal distributions have broad enough support that the algorithm can get from any z to any z′^ in a finite number of steps, then the process will “mix”. (In fact we only need to be able to visit points where fZ > 0.) This means that if we start with an arbitrary distribution for Z 0 , the distribution of Zt approaches fZ and stays there — the point of burn-in is to give this convergence time to happen. The fraction of time Zt is close to x is in fact proportional to fZ (x), so
we can use the output of the algorithm as, approximately, so many draws from that distribution.^5 It would seem that the Metropolis algorithm should be superior to the rejec- tion method, since to produce n random values we need only n steps, or n + n 0 to handle burn-in, not nM steps. However, this is deceptive, because if the proposal distribution is not well-chosen, the algorithm ends up staying stuck in the same spot for, perhaps, a very long time. Suppose, for instance, that the distribution is bimodal. If Z 0 starts out in between the modes, it’s easy for it to move rapidly to one peak or the other, and spend a lot of time there. But to go from one mode to the other, the algorithm has to make a series of moves, all in the same direction, which all reduce fZ , which happens but is unlikely. It thus takes a very long time to explore the whole distribution. The “best” optimal proposal distribution is make ρ(r|z) = fZ (r), i.e., to just sample from the target distribution. If we could do that, of course, we wouldn’t need the Metropolis algorithm, but trying to make ρ close to fZ is generally a good idea. The original Metropolis algorithm was invented in the 1950s to facilitate designing the hydrogen bomb. It relies on the assumption that the proposal distribution is symmetric, ρ(r|z) = ρ(z|r). It is sometimes convenient to allow
an asymmetric proposal distribution, in which case one accepts R if U ρ ρ((RZt|Z|Rt)) ≤ fZ (R) fZ (Zt). This is called^ Metropolis-Hastings. Both are examples of the broader class of Markov Chain Monte Carlo algorithms, where we give up on getting independent samples from the target distribution, and instead make the target the invariant distribution of a Markov process.
2.2.5 Mixtures and Kernel Density Estimates
Some probability distributions can be written as mixtures of other distribu- tions. That is, the pdf can be written in the form
fZ (x) =
∑^ m
j=
wj fj (x) (7)
where the mixing weights are non-negative and add up to 1. In this case, the problem of generating a random variable from fZ can be decomposed into two steps. First, pick a random integer J between 1 and m, with probabilities given by the wj ; then draw from fJ. Notice that kernel density estimates all have the mixture form, but with all weights equal to each other. Thus one simulates from a kernel density estimate by first picking a training point, uniformly at random, and then drawing from the kernel distribution centered on that training point. Notice also that histogram estimates have this form, with fj being the uni- form distribution on the jth^ bin, and wj the total probability of that bin.
(^5) And if the dependence between Zt and Zt+1 bothers us, we can always randomly permute them, once we have them.
arnold.map <- function(v) { theta <- v[1] phi <- v[2] theta.new <- (theta+phi)%% phi.new <- (theta+2*phi)%% return(c(theta.new,phi.new)) }
rarnold <- function(n,seed) { z <- vector(length=n) for (i in 1:n) { seed <- arnold.map(seed) z[i] <- seed[1] } return(z) }
Code Example 2: A function implementing the Arnold cat map (Eq. 10), and a second function which uses it as a pseudo-random number generator. See online version for comments.
pings. Take the system
θt+1 = θt + φt mod 1 (9) φt+1 = θt + 2φt mod 1
This is known as “Arnold’s cat map”, after the great Soviet mathematician V. I. Arnold, and Figure 2. We can think of this as the second-hand θt advancing not by a fixed amount α every second, but by a varying amount φt. The variable φt, meanwhile, advances by the amount φt + θt. The effect of this is that if we look at only one of the two coordinates, say θt, we get a sequence of numbers which, while deterministic, is uniformly distributed, and very hard to predict (Figure 3).
Figure 2: Effect of the Arnold cat map. The original image is 300 × 300, and mapped into the unit square. The cat map is then applied to the coordinates of each pixel separately, giving a new pixel which inherits the old color. (This can most easily seen in the transition from the original to time 1.) The original image re-assembles itself at time 300 because all the original coordinates we multiples of 1/300. If we had sampled every, say, 32 time-steps, it would have taken much longer to see a repetition. In the meanwhile, following the x coordinate of a single pixel from the original image would provide a very creditable sequence of pseudo-random values. (Figure from Wikipedia, s.v. “Arnold’s cat map”. See also http://math.gmu.edu/~sander/movies/arnold.html.)
There are three major uses for simulation: to understand a model, to check it, and to fit it.
We understand a model by seeing what it predicts about the variables we care about, and the relationships between them. Sometimes those predictions are easy to extract from a mathematical representation of the model, but often they aren’t. With a model we can simulate, however, we can just run the model and see what happens. For instance, at the end of the last set of notes I used kernel density esti- mation to find the joint density of population growth rates (call that X) and investment rates (call that Y ) from the oecdpanel data:
library(np) data(oecdpanel) popinv2 <- npudens(~exp(popgro)+exp(inv),data=oecdpanel)
(See Figure 4 for a visualization.) Since this is a joint distribution, it implies a certain expected value for Y /X, the ratio of investment rate to population growth rate^7. Extracting this by direct calculation from popinv2 would not be easy; we’d need to do the integral
∫ (^1)
x=
dx
y=
dy
y x
f (x, y) (10)
To find E [Y /X] by simulation, however, we just need to generate samples from the joint distribution, say ( X˜ 1 , Y˜ 1 ), ( X˜ 2 , Y˜ 2 ),... ( X˜T , Y˜T ), and average:
i=
Y^ ˜i X^ ˜i
= ˜gTT −→^ →∞ E
where the convergence happens because that’s the law of large numbers. If the number of simulation points T is big, then ˜gT ≈ E [Y /X]. How big do we need to make T? Use the central limit theorem:
˜gT N (E [Y /X] , Var [˜g 1 ] /
How do we find the variance Var [˜g 1 ]? We approximate it by simulating. Let’s be very concrete about this. Code Example 3 is a function which draws a sample from the fitted kernel density estimate. First let’s check that it works, by giving it something easy to do, namely reproducing the means, which we can work out: (^7) Economically, we might want to know this because it would tell us about how quickly the capital stock per person grows.
population growth rate
investment rate
0.04 0.05 0.06 0.07 0.
10
10
10
20
20
30
40
50
60
(^807080) 90 90
100
100
(^110 )
120
120
130
130140150
160
160
170
170
180
180
190
190
200
Figure 4: Contour plot of popinv2, the estimated joint density of population growth rate and investment rate. See the notes to lecture 6 for the plotting commands.
0 2 4 6 8
Y/X
Probability density
YoverX <- z[,"invest.rate"]/z[,"pop.growth.rate"] plot(density(YoverX),xlab="Y/X",ylab="Probability density",main="") rug(YoverX,side=1)
Figure 5: Distribution of Y /X implied by the joint density estimate popinv2.
interest from s independent realizations of the model, each of size T. We can just combine them into one grand average:
˜gs,T =
s
∑^ s
i=
g ˜ T(1) (13)
As an average of IID quantities, the variance of ˜gs,T is 1/s times the variance
of ˜g(1) T. By this point, we are getting the sampling distribution of the density of a nonlinear transformation of the variables in our model, with no more effort than calculating a mean. In the next lecture, we will see some of the things which can be accomplished when we can get complicated sampling distributions easily by simulation.
0 2 4 6 8 10
Y/X
Probability density
plot(0,xlab="Y/X",ylab="Probability density",type="n",xlim=c(-1,10), ylim=c(0,0.3)) one.plot <- function() { zprime <- rpopinv(2000) YoverXprime <- zprime[,"invest.rate"]/zprime[,"pop.growth.rate"] density.prime <- density(YoverXprime) lines(density.prime,col="grey") } invisible(replicate(50,one.plot()))
Figure 6: Showing the sampling variability in the distribution of Y /X by “over- plotting”. Each line is a distribution from an estimated sample of size 2000, as in Figure 5; here 50 of them are plotted on top of each other. The thickness of the bands indicates how much variation there is from simulation to simulation at any given value of Y /X. (Setting the type of the initial plot to n, for “null”, creates the plotting window, axes, legends, etc., but doesn’t actually plot anything.)
1 2 3 4 5
50
60
70
80
90
100
110
duration
waiting
plot(geyser$duration,geyser$waiting,xlab="duration",ylab="waiting") abline(fit.ols)
Figure 7: Data for the geyser data set, plus the OLS regression line.
rgeyser <- function() { n <- nrow(geyser) sigma <- summary(fit.ols)$sigma new.waiting <- rnorm(n,mean=fitted(fit.ols),sd=sigma) new.geyser <- data.frame(duration=geyser$duration, waiting=new.waiting) return(new.geyser) }
Code Example 4: Function for generating surrogate data sets from the linear model fit to geyser.
40 60 80 100 120
waiting
Density
plot(density(geyser$waiting),xlab="waiting",main="",sub="") lines(density(rgeyser()$waiting),lty=2)
Figure 8: Actual density of the waiting time between eruptions (solid curve) an that produced by simulating the OLS model (dashed).
9, we might suspect that one problem is heteroskedasticity^9. In the homework, you estimated a conditional variance function,
library(np) var1 <- npreg(residuals(fit.ols)^2 ~ geyser$duration)
which is plotted in Figure 10, along with the (constant) variance function of the OLS model. The estimated variance function var1 does not look particularly flat, but it comes from applying a fairly complicated procedure (kernel smoothing with data-driven bandwidth selection) to a fairly limited amount of data (299 obser- vations). Maybe that’s the amount of wiggliness we should expect to see due to finite-sample fluctuations? To rule this out, we can make surrogate data from the homoskedastic model, treat it the same way as the real data, and plot the resulting variance functions (Figure 11). These comparisons have been qualitative, but one could certainly be more quantitative about this. For instance, one might measure heteroskedasticity by, say, evaluating the conditional variance at all the data points, and looking at the ratio of the interquartile range to the median. This would be zero for perfect homoskedasticity, and grow as the dispersion of actual variances around the “typical” variance increased. For the data, this is 111129 = 0.86. Simulations from the OLS model give values around 10−^15.
(^9) At the very least, homework 2 should have planted that idea in your mind.