{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Populations, Samples, and Estimators \n",
"\n",
"In this notebook we will examine the relationship between a population, a method for selecting a sample from the populations, and the resulting sample.\n",
"\n",
"When we are in the situation where we have data from the population of interest, then we can directly examine the population distribution and parameters. In many situations we do not have the population and must work with a sample. Our goal in this case is to make inferences about the population. In this notebook, we will use the restaurant inspections as an example of a population and draw samples from the populations to figure out how we might use the sample for making inferences about the population."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import os\n",
"from IPython.display import display, Latex, Markdown"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import seaborn as sns\n",
"%matplotlib inline\n",
"sns.set_context(\"talk\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Restaurant Inspection Scores - The Population\n",
"\n",
"\n",
"Recall that we have an administrative data set that contains inspection scores for all restauarants in San Francisco over a three year period. Many restaurants have more than one inspection a year. If our population is restaurants, then we will want to focus on one set of scores. Let's choose one inspection score per restaurant from 2016.\n",
"\n",
"Below, we read in the data, examine a few results, and create our population of restaurant inspection scores in 2016."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"dsDir = \"data/\"\n",
"\n",
"ins = pd.read_csv(\"data/inspections.csv\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"ins.head(10)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"ins.tail(10)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We select one score per restaurant in 2016."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"ins['new_date'] = ins['date'].apply(lambda d: pd.datetime.strptime(str(d),'%Y%m%d'))\n",
"ins['year'] = ins['new_date'].apply(lambda d: d.year)\n",
"\n",
"ins = ins[ins['year']==2016].groupby('business_id').last().copy()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print(\"Number of Restaurants:\", len(ins))\n",
"ins.head(10)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"ins.tail(10)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Population Distribution\n",
"\n",
"Let's look at the distribution of inspections scores for the restaurant population. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"scoreCts = ins['score'].value_counts().sort_index()\n",
"scoreCts"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notice that scores are integer values and for this population they range between 52 and 100. There are no restaurants with a score of 95, 97, or 99. We make a bar plot (rather than a histogram) so that we can see all of the possible values for inspection score for the restaurants. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"plt.bar(scoreCts.index.values, scoreCts.values)\n",
"plt.xlabel('Restaurant score')\n",
"plt.ylabel('Frequency')\n",
"#plt.savefig(\"barplot_counts.pdf\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Ideally, we want percentages on the y axis. This will it easier for us to compare the population distribution with the distribution of a sample and the probability distribution of a random draw from the population. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"100 * scoreCts/scoreCts.sum()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We could have normaized the counts to begin with as follows."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"scoreCts = 100 * ins['score'].value_counts(normalize = True).sort_index()\n",
"scoreCts"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"plt.bar(scoreCts.index.values, scoreCts)\n",
"plt.xlabel('Restaurant score')\n",
"plt.ylabel('Percent')\n",
"#plt.savefig(\"barplot_percent.pdf\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Population parameters - average and SD\n",
"\n",
"We can examine simple summaries of the population distribution such as the average inspection score and the standard deviation of the inspection score. \n",
"\n",
"Below we show that the sample average can be computed as a weighted average of the unique values in the population, where the weight for an inspection score is the proportion of restaurants with that score. That is,\n",
"\n",
"$$\\large\n",
"\\texttt{Population Average} = \\frac{1}{N} \\sum_{i=1}^N x_i,\n",
"$$\n",
"\n",
"where $x_i$ is the score for restaurant $i$, for $i=1, \\ldots, N$.\n",
"\n",
"Suppose there are $m$ unique values for the score, for $j = 1, \\ldots, m$. Then, we can equivalently\n",
"express the population average as \n",
"\n",
"$$\\large\n",
"\\texttt{Population Average} = \\sum_{j=1}^m v_j \\times p_j,\n",
"$$\n",
"\n",
"where $p_j$ is the proportion of the population with score $v_j$."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print(\"The population average is: \", ins['score'].mean() )\n",
"\n",
"print(\"Another way to compute this is as a weighted sum: \",\n",
" (scoreCts.index.values * scoreCts / 100).sum())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The standard deviation (SD) of the scores is a measure of the typical deviations of an inspection score from the population mean. It is also called the root mean square error about the mean. This alternative name tells us how to compute the SD. \n",
"\n",
"$$\\large\n",
"\\texttt{Standard Deviation} = \\sqrt{\\sum_{i=1}^m \\left(v_j - \\texttt{Pop Avg} \\right)^2 p_j}\n",
"$$\n",
"\n",
"Working from the inside outward, we see that we are examining the error about the mean (the loss), squaring it, taking the mean, and then the square root. \n",
"\n",
"The `std` function performs this computation for us."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print(\"The population SD is: \", ins['score'].std())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The population of restaurants in 2016 in San Francisco have an average inspection score of 90 with a SD of 8.3. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Probability Distribution of Draws from the population\n",
"\n",
"In order to investigate the probability distribution of a draw from the population, we start with a much simpler example where the population is very small. This will make it easier for us to make probability calculations and generalize from these calculations to drawing from a more general population.\n",
"\n",
"We set up a small population with 5 inspection scores: 80, 80, 92, 92, 96.\n",
"As before, we can examine the population distribution, mean, and SD."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"scores_tiny = pd.Series([80, 80, 92, 92, 96], name=\"score\")\n",
"\n",
"scoreCts_tiny = scores_tiny.value_counts(sort = True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"plt.bar(scoreCts_tiny.index.values, 100 * scoreCts_tiny/scoreCts_tiny.sum())\n",
"plt.xticks(np.arange(79, 101, 1))\n",
"#plt.savefig(\"barplot_percent_tiny.pdf\")\n",
"plt.show()\n",
"\n",
"print(\"The tiny population mean is: \", scores_tiny.mean()) \n",
"print(\"The tiny population SD is: \", scores_tiny.std() )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Draw one score at random \n",
"\n",
"For this population, it is relatively easy for us to consider the *probability distribution* of one draw at random. When we say at random, we mean with equal chance.\n",
"\n",
"If $X$ represents the possible outcome of this chance process, then $X$ can take on the value of 80 or 92 or 96. The *probability distribution* of $X$ summarizes the chance of each of these possible outcomes. We can summarize these probabilities in a table:\n",
"\n",
"\n",
"|outcome | 80 | 92 | 96 |\n",
"|---|---|---|---|\n",
"|chance | 2/5 | 2/5 | 1/5|"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### What do we expect?\n",
"\n",
"What do we expect $X$ to be? To get a sense of this, we can use the computer to take a sample\n",
"and repeat again and again to see how the results vary. We first repeat only 3 times to see how the values of $X$ vary. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"np.random.seed(37)\n",
"print(\"One sampled score\", ins['score'].sample(1), \n",
" \"\\nAnother sampled score\", ins['score'].sample(1),\n",
" \"\\nAnd another\", ins['score'].sample(1))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"On the first draw, we got 92, on the secon 94 and the third is the same as the second. \n",
"\n",
"Let's repeat this process one thousand times to see what the distribution of possible values for $X$ looks like. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"np.random.seed(77)\n",
"samples_tiny = pd.Series([scores_tiny.sample(1, replace = True).values[0] \n",
" for _ in range(1000)])\n",
"samples_tiny.describe()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We see that the average value for the 1000 realizations of $X$ is 88.3. Recall that the population average is 88. We also see that the standard deviation of these 1000 realizations is 6.7. For comparison the SD of the population is 7.5.\n",
"\n",
"This simulation that we performed gives us some insight as to the *Expected Value* of $X$ and the *Standard Deviation* of $X$. \n",
"\n",
"Let's also examine the proportions of the 1000 values of $X$ that are 80, 92, and 96."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"scoreCts_samp = 100 * pd.value_counts(samples_tiny, normalize = True)\n",
"\n",
"barSample = plt.bar(scoreCts_samp.index.values, scoreCts_samp.values)\n",
"plt.xticks(np.arange(80, 101, 2))\n",
"plt.yticks(np.arange(0, 45, 5))\n",
"plt.xlabel('1000 Sampled Restaurant Scores from Tiny Population (80, 80, 92, 92, 96)')\n",
"plt.ylabel('Percent')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notice that the simulation produced proportions that are close to the probabilities. That is, in 1000 simulated draws from our tiny population, about 38% of the draws were 80. In comparison, the chance that $X$ is 80 is $2/5$ or 40%."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### From Simulation to Proof\n",
"\n",
"The simulation gave us several insights: \n",
"\n",
"* The probability distribution of $X$ matches the population distribution \n",
"* The expected value of $X$ is the population average.\n",
"* The SD of $X$ is the population SD.\n",
"\n",
"Actually, we had figured the first of these discoveries out already. The last two of the discoveries, we can prove analytically. See the posted course notes.\n",
"\n",
"Let's confirm that these discoveries hold for our larger population of all restaurants in San Francisco."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"np.random.seed(707)\n",
"samples = ins['score'].sample(1000, replace = True)\n",
"samples.describe()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Recall that our population mean is 90 and SD is 8.3. \n",
"\n",
"Let's examine the distribution of the 1000 simulated values of $X$ and compare this simulated distribution to the population distribution."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"scoreCts_samp = 100 * pd.value_counts(samples, normalize = True)\n",
"\n",
"barSample = plt.bar(scoreCts_samp.index.values, scoreCts_samp.values)\n",
"plt.xticks(np.arange(50, 101, 10))\n",
"plt.yticks(np.arange(0, 15, 2))\n",
"plt.xlabel('1000 Sampled Restaurant Scores')\n",
"plt.ylabel('Percent')\n",
"#plt.savefig(\"barplot_samp1000.pdf\")\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"barPop = plt.bar(scoreCts.index.values, scoreCts.values)\n",
"plt.xticks(np.arange(50, 101, 10))\n",
"plt.yticks(np.arange(0, 15, 2))\n",
"plt.xlabel('Population of Restaurant Scores')\n",
"plt.ylabel('Percent')\n",
"#plt.savefig(\"barplot_pop.pdf\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notice that in our sample of 1000 we did not observe all of the lowest values because these have low proportions in our population."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Sampling 100 restaurants\n",
"\n",
"Now suppose we take a sample of 100 restaurants at random *without* replacement.\n",
"\n",
"What does any one sample look like?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"np.random.seed(107)\n",
"samples = ins['score'].sample(100, replace = False)\n",
"scoreCts_samp = pd.value_counts(samples, sort = True)\n",
"\n",
"barSample = plt.bar(scoreCts_samp.keys(), \n",
" 100 * scoreCts_samp.values/scoreCts_samp.values.sum())\n",
"plt.xticks(np.arange(50, 101, 10))\n",
"plt.yticks(np.arange(0, 15, 2))\n",
"plt.xlabel('Scores for Sample of 100 Restaurants')\n",
"plt.ylabel('Percent')\n",
"#plt.savefig(\"barplot_samp100.pdf\")\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"samples.mean()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The sample looks similar to the population distribution, although it's clearly different.\n",
"\n",
"\n",
"Consider the 100 random variables, $X_1$, $X_2$, ... $X_{100}$ that result from 100 draws at random without replacement from the population. Each of these random variables has the same distribution. This implies that \n",
"$$\\large\n",
"\\textbf{E}(X_i) = \\texttt{population average}\n",
"$$ \n",
"In turn, this then implies that \n",
"$$\\large\n",
"\\textbf{E}(\\bar{X}) = \\texttt{population average}\n",
"$$ \n",
"(See the probability handout for a proof).\n",
"\n",
"Since the $X_i$ have the same distribution, we also find that \n",
"$$\\large\n",
"SD(X_i) = \\textrm{population SD} = \\sigma\n",
"$$ \n",
"However, \n",
"$$\\large\n",
"SD(\\bar{X}) = \\frac{N-n}{N-1}\\frac{\\sigma}{\\sqrt{n}},\n",
"$$\n",
"rather than $\\frac{\\sigma}{\\sqrt{n}}$ because the $X_i$ are dependent random variables.\n",
"\n",
"We can use simulation studies to develop insight into these results and others."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Simulating the Probability Distribution of $\\bar{X}$\n",
"\n",
"What does the probabiity distribution of the sample average look like? \n",
"\n",
"We can simulate this distribution by taking 1000 replications: where for each replicate we take a simple random sample of 100 values from the population and find the sample average. Repeating this 1000 times gives us an idea as to what the *sampling distribution* of the average looks like. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"np.random.seed(707)\n",
"res = pd.Series([\n",
" ins['score'].sample(100, replace = False).mean() \n",
" for _ in range(1000)\n",
"])\n",
"res.describe()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"scrolled": true
},
"outputs": [],
"source": [
"sns.distplot(res)\n",
"#plt.savefig('mean_hist1000v2.pdf')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As noted earlier, the simulation indicates that expected value of $\\bar{X}$ should match the population average, which is 90. We can also see that the SD of $\\bar{X}$ is about $(4443/4542) \\times \\sigma/\\sqrt{100} \\approx 0.82$. When we compute an SD of a statistics, we usually called is the *Standard Error* or SE for short. \n",
"\n",
"Notice that we have discovered via simulation that the probability distribution of the sample average roughly looks like the normal curve. It is unimodal, symmetric, with neither long nor short tails. "
]
},
{
"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": "markdown",
"metadata": {},
"source": [
"### Law of Large Numbers - demonstration\n",
"\n",
"We begin by setting 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.exp(np.linspace(np.log(10), np.log(10000), 50)).astype(\"int\")\n",
"\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",
"plt.figure(figsize=(15,10))\n",
"\n",
"pd.Series([\n",
" ins['score'].sample(s, replace = True).mean() \n",
" for s in sample_sizes\n",
" ], index=sample_sizes).plot()\n",
"plt.yticks(np.arange(86, 95, 2))\n",
"plt.xscale('log')\n",
"plt.xlabel('Sample Size (log scale)')\n",
"plt.ylabel('Average Inspection Score')\n",
"#plt.savefig('lln.pdf')\n"
]
},
{
"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": [
"plt.figure(figsize=(15,10))\n",
"\n",
"for i in range(0,100):\n",
" pd.Series([\n",
" ins['score'].sample(s, replace = True).mean() \n",
" for s in sample_sizes\n",
" ], index=sample_sizes).plot(color='grey', alpha = 0.2)\n",
"\n",
"plt.yticks(np.arange(86, 95, 2))\n",
"plt.xscale('log')\n",
"plt.xlabel('Sample Size (log scale)')\n",
"plt.ylabel('Average Inspection Score')\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": [
"sample_sizes = np.exp(np.linspace(np.log(10), np.log(10000), 50)).astype(\"int\")\n",
"\n",
"sds = []\n",
"\n",
"for s in sample_sizes:\n",
" means = [\n",
" ins['score'].sample(s, replace = True).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.figure(figsize=(10,7))\n",
"\n",
"plt.plot(sample_sizes, sds, label='SE for 1000 Simulated Means')\n",
"plt.plot(sample_sizes, ins['score'].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": [
"### Central Limit Theorem Demonstration\n",
"\n",
"We will discover one more theoretical result via simulation. Note that when we plotted the simulated sampling distribution of the average for 100 samples, we saw that the histogram appeared to roughly follow the normal curve. Let's see how the sampling distribution depends on the sample size. We consider 5 samples sizes: 20, 40, 100, 400, 1000."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"sample_sizes = [20, 40, 100, 400, 1000]\n",
"data = {} \n",
"for s in sample_sizes:\n",
" means = [\n",
" ins['score'].sample(s, replace = True).mean() \n",
" for _ in range(10000)]\n",
" data[s] = means"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"plt.figure(figsize=(10,7))\n",
"\n",
"for s in sample_sizes:\n",
" sns.distplot(data[s], label=str(s))\n",
"plt.legend()\n",
"#plt.savefig(\"histogram.pdf\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We have discovered that as the sample size grows, the distribution appears to follow the normal curve more closely. Additionally, the center of the distribution is at the population mean and the spread of the distribution shrinks (it depends on the SD of the distribution which we know decreases like $1/\\sqrt{n}$.\n",
"\n",
"This is the *Central Limit Theorem* For $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": "markdown",
"metadata": {},
"source": [
"## Restaurant Inspection Scores - The Sample\n",
"\n",
"Now suppose we are in the realm where we do not know or see the population and we have one sample of 100. \n",
"\n",
"Suppose that we want to use our sample to make statements about the population. \n",
"\n",
"Here is out sample:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"np.random.seed(37)\n",
"my_sample = ins['score'].sample(100, replace = False)\n",
"scoreCts_samp = 100 * pd.value_counts(my_sample, normalize = True)\n",
"\n",
"barSample = plt.bar(scoreCts_samp.index.values, \n",
" scoreCts_samp.values)\n",
"plt.xticks(np.arange(50, 101, 10))\n",
"plt.yticks(np.arange(0, 15, 2))\n",
"plt.xlabel('Scores for Sample of 100 Restaurants')\n",
"plt.ylabel('Percent')\n",
"#plt.savefig(\"barplot_mysamp.pdf\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We have seen in our earlier simulation studies that the *Empirical Distribution* of the sample looks approximately like the Population Distribution. This implies that parameter estimates based on our sample should be relatively good estimates of our population parameters.\n",
"\n",
"In fact, the theory that we have proven or discovered via simulation that:\n",
"\n",
"* the expected value of the sample average is the population average\n",
"* the variability in the sample average decreases like $\\sigma/\\sqrt{n}$\n",
"* for $n$ large, the sample average behaves like one draw from a distribution that looks like the normal curve that is centered at the population average and has a spread of $\\sigma/\\sqrt{n}$\n",
"\n",
"We can use these results to make statements about the population average. For example, we can say that the population average is near:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"np.mean(my_sample)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we approximate the population SD with the sample SD (why is that OK), we can say that we expect the error of our estimate to be about:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"np.std(my_sample)/np.sqrt(len(my_sample))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Bootstrapping the Sample Average\n",
"\n",
"What happens when we want to estimate a parameter other than the population mean, such as a population percentile? The theory that we have derived and simulated for the mean is a bit more delicate for other estimators. For example, we may not be able to use the $\\texttt{SD}(sample)/\\sqrt{n}$ as an approximation for the SE of the estimaotr. Indeed, if the sampling distribution of the estimator is not close to normal, we may want to use a different approach for providing an estimate of the variabiity in our estimator? \n",
"\n",
"In this situation, we fall back on the mechanism for generating the data: the Simple Random Sample (whether with or without replacement). We have seen the empirical distribution of the sample is similar to the population distribution. We use this similarity to bootstrap ourselves into the realm of a population. In particular, we use the sample proportions as the population distribution. This is called the *bootstrap population*. From there we essentially perform Monte Carlo simulation with this population to understand the behavior of the paramter estimator.\n",
"\n",
"That is, we take a sample from the *bootstrap population*, which we call a *bootstrap sample*. For the bootstrap sample, we calculate the estimator (e.g., mean, percentile, Huber estimator), which we call the *bootstrap statistic*. We repeat this process thousands of times and study the distribution of the bootstrap sampling distribution. \n",
"\n",
"Note that it is the *shape* and *variability* of the bootstrap sampling distribution that is of interest to us. The average is not of interest because by design, it will align with the bootstrap population (our original sample), not the true population. \n",
"\n",
"The code is nearly the same as before, we simply draw at random from our sample, rather than from the population. For now, we will ignore the difference between sampling with and without replacement and assume that we have a large enough population size that these are essentially equivalent.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"np.random.seed(37)\n",
"boot_means = [\n",
" my_sample.sample(100, replace = True).mean() \n",
" for _ in range(10000)]\n",
"boot_means[0:20]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"sns.distplot(boot_means)\n",
"plt.xlabel('10000 Bootstrapped Sample Averages (sample size = 100)')\n",
"#plt.savefig(\"bootstrap_hist.pdf\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As mentioned, the average of the 10000 bootstrapped means is very close to our sample average, 89.65, not the population average. This again is because the bootstrap population has a mean of 89.65 and that is the population that we are sampling from."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"np.mean(boot_means)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Also notice that the SD of the 10000 sample averages is close to our sample average/10, i.e., 0.74, rather than the population average/10, which is 0.83. Given the skewness of the population (and the sample) there is another version of the bootstrap that is typically better to use in this situation. It is called the standardized bootstrap. We may introduce it.\n",
"\n",
"Nonetheless, this is a rough approximation to the standard error of the statistic of interest."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"np.std(boot_means)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We will consider the bootstrap for other statistics next."
]
}
],
"metadata": {
"anaconda-cloud": {},
"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.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}