{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Monte Carlo methods and the Central Limit Theorem\n",
"\n",
"Let's discuss how to use randomized sampling tools for estimating quantities of statistical interest. This idea encompasses a large class of specific tools, broadly known as [Monte Carlo Methods](https://en.wikipedia.org/wiki/Monte_Carlo_method). Their core principle is to use randomness to obtain approximate solutions to otherwise deterministic problems. Why?\n",
"\n",
"* Faster\n",
"* Easier\n",
"\n",
"**Key drawback:** they may (with low probability) give the wrong answer.\n",
"\n",
"Alternative: [Las Vegas Algorithms](https://en.wikipedia.org/wiki/Las_Vegas_algorithm). These are randomized algorithms that either always give correct results or explicitly indicate failure."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Monte Carlo\n",
"\n",
"We will carry out some more detailed simulation studies to examine the expected value, standard deviation, and distribution of the sample average for averages of different sizes.\n",
"In the process we will confirm our theoretical results and discover new ones.\n",
"\n",
"These are examples of a simple but powerful approach to studying random processes through simulation. The technique that we have been using is called Monte Carlo simulation. Briefly, suppose that we want to study the behavior of a statistic $T(X_1, \\ldots, X_n)$ which is a function of $X_1, \\ldots X_n$. (The sample mean, median, Huber estimator are all examples).\n",
"Then we can study the behavior of $T$ under different conditions, such as a rango of sample sizes, different population distributions, sampling with or without replacement, etc. We perform the Monte Carlo as follows: \n",
"\n",
"* Take a combination of input values, e.g., sample size and population distribution, which we call a data generation model\n",
"* Generate data from this model and calculate the statistic of interest\n",
"* Repeat this process many (typically thousands) of times\n",
"* Repeat the above process for all combinations of input values (data generation models).\n",
"\n",
"We will study the impact of the sample size on the probability distribution of $\\bar{X}$ for the restaurant population and sampling with replacement. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# A bit of setup first\n",
"%matplotlib inline\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import pandas as pd\n",
"import seaborn as sns\n",
"from scipy.stats import norm"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.style.use(\"seaborn\")\n",
"plt.rcParams['figure.figsize'] = (10, 6)\n",
"sns.set_context('talk', font_scale=1.4)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Law of Large Numbers - demonstration\n",
"\n",
"First, let's consider our population to be 50,000 uniformly distributed random numbers in [0, 1]:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"pop = pd.Series(np.random.uniform(size=50_000))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"the mean of this population is, as expected, very close to 1/2:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"pop.mean()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"But let's see what happens as we study this population via sampling. Let's set up a range of sample sizes that we want to study."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"sample_sizes = np.logspace(1, 4, 50, dtype='int')\n",
"sample_sizes"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next we carry out one round of our Monte Carlo study. That is, we examine the sample average for all of our sample sizes, where we generate only one sample for each size. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"np.random.seed(707)\n",
"pd.Series([\n",
" pop.sample(s, replace=False).mean() \n",
" for s in sample_sizes\n",
" ], index=sample_sizes).plot()\n",
"plt.xscale('log')\n",
"plt.xlabel('Sample Size (log scale)')\n",
"plt.ylabel('Mean');\n",
"#plt.savefig('lln.pdf');"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It appears that the sample average gets closer to the population average as the sample size grows. Note that the x-axis is on log scale.\n",
"\n",
"We repeat this process 100 times to get a sense of how quickly the sample average converges to the population mean. Not that we use transparency to help see where are the bulk of values. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"for i in range(0,100):\n",
" pd.Series([\n",
" pop.sample(s, replace=False).mean() \n",
" for s in sample_sizes\n",
" ], index=sample_sizes).plot(color='grey', alpha = 0.2)\n",
"\n",
"plt.xscale('log')\n",
"plt.xlabel('Sample Size (log scale)')\n",
"plt.ylabel('Mean');\n",
"#plt.savefig('lln_many.pdf');"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We have discovered the *Law of Large Numbers*: As the sample size increases, the sample average (from indpendent sample with replacement from a population) converges to the population average. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Square-root law\n",
"\n",
"We already know the Square-root Law: The standard error of the sample average shrinks by a facotr of $1/\\sqrt{n}$ with the sample size. However, we can confirm this is the case with a simulation study. Again, we vary the sample size. This time we take 1000 replications for each sample size. That is for a particular sample size, we obtain 1000 sample averages, and we find the standard deviation of these 1000 sample averages to approximate the SD of the sample average. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# This cell takes a while to run\n",
"sample_sizes = np.logspace(1, 4, 50, dtype='int')\n",
"sds = []\n",
"\n",
"for s in sample_sizes:\n",
" means = [\n",
" pop.sample(s, replace = False).mean() \n",
" for _ in range(1000)]\n",
" sds.append(np.std(means)) "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Since we want to confirm the Square-root Law, we plot our findings along with our theory, i.e., $\\sigma/\\sqrt{n}$. The two curves are essentially on top of each other. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"plt.plot(sample_sizes, sds, label='SE for 1000 Simulated Means')\n",
"plt.plot(sample_sizes, pop.std()/np.sqrt(sample_sizes), \n",
" label='Population SD/sqrt(sample size)')\n",
"\n",
"plt.xscale('log')\n",
"plt.xlabel('Sample Size (log scale)')\n",
"plt.ylabel('Standard Error of Mean')\n",
"plt.legend();\n",
"#plt.savefig('sqrt_law.pdf')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# The Central Limit Theorem\n",
"\n",
"Let's consider the problem of estimating the mean of a population of size $N$, by taking samples of size $n$ from this population. The *Central Limit Theorem* states that if $n$ large in absolute terms and small relative to $N$ (if sampling without replacement), the probability distribution of the sample average becomes increasingly close to the normal curve with center at the population average and SD $= \\sigma/\\sqrt{n}$. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = np.random.uniform(size=1000)\n",
"plt.hist(a, bins=30);"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"sample_size = 2\n",
"repetitions = 100\n",
"b = np.random.uniform(size=(sample_size, repetitions))\n",
"bav = b.mean(axis=0)\n",
"plt.hist(bav, bins=30);"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"mu = 0.5\n",
"sigma = 0.1\n",
"xmin, xmax = mu-5*sigma, mu+5*sigma\n",
"x = np.linspace(xmin, xmax, 200)\n",
"plt.hist(np.random.normal(mu, sigma, size=10_000), density=True, bins=50);\n",
"plt.plot(x, norm.pdf(x, mu, sigma), lw=3);"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def uni_cl_theo(sample_size, repetitions, ax=None, bins=None):\n",
"\n",
" bins = 30 if bins is None else bins\n",
" if ax is None:\n",
" fig, ax = plt.subplots()\n",
" \n",
" # mean and variance of the uniform (0,1) distribution\n",
" mu = 0.5\n",
" sigma2_uni = 1/12\n",
" sigma_norm = np.sqrt(sigma2_uni/sample_size)\n",
"\n",
" sample_means = np.random.uniform(size=(sample_size, repetitions)).mean(axis=0)\n",
" assert sample_means.size == repetitions # sanity check\n",
" \n",
" xmin_n, xmax_n = mu-5*sigma_norm, mu+5*sigma_norm\n",
" xmin = min(0, xmin_n)\n",
" xmax = max(1, xmax_n)\n",
" x = np.linspace(xmin, xmax, 300) \n",
" ax.hist(sample_means, density=True, bins=bins);\n",
" ax.plot(x, norm.pdf(x, mu, sigma_norm), lw=3, label=f'n={sample_size}, r={repetitions}')\n",
" ax.set_xlim([xmin, xmax])\n",
" ax.legend()\n",
" return ax\n",
"\n",
"uni_cl_theo(1, 1000);"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for reps in [10, 100, 1000, 10000]:\n",
" uni_cl_theo(2, reps)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"reps = 1_000\n",
"for sample_size in [1, 2, 10, 100, 500]:\n",
" uni_cl_theo(sample_size, reps)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 2
}