{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"tags": [
"remove-cell"
]
},
"outputs": [],
"source": [
"import numpy as np\n",
"import pandas as pd\n",
"\n",
"%matplotlib inline\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# A simulation-based solution\n",
"\n",
"We have introduced the concept of simulation in Section 5.3 (we simulated the output of rolling a six-sided die). Simulations are used to imitate real-world scenarios. They can have many roles, ranging from obtaining insight into a physical system to testing and training of models and algorithms. In this chapter, we will use simulations to estimate probabilities. We will explore other applications later, such as gaining insight into probability distributions.\n",
"\n",
"Here we use the computer to run/execute our simulations and we will develop code that will allow us to do that. There are several steps in designing and executing a simulation:\n",
"- Conceptualize what to simulate;\n",
"- Simulate one instance;\n",
"- Decide on the number of repetitions;\n",
"- Summarize the results of the simulation.\n",
"\n",
"There are two important issues that we would like to note here:\n",
"- Simulations will give us only an estimate/approximation of the probability we are interested in; the more repetitions, the better the approximation.\n",
"- The number of repetitions is important and strategies for selecting them will be discussed in more detail later in the chapter.\n",
"\n",
"## Conceptualize and simulate one instance\n",
"\n",
"In the birthday problem described at the beginning of this chapter (30 people at a party), the only information that is needed for deciding on matching birthdays is the set of birthdates. The simulation we will construct will focus on that - we just need a function that generates 30 random birthdays. It turns out we have already seen a function in `numpy` that can do that: `random.choice`.\n",
"\n",
"The cell code below shows the results of simulating a group of 30 birthdates, where birthdates are described by the integers from 1 to 365 and saved in the array `birthdays`."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([353, 265, 326, 356, 124, 329, 122, 304, 144, 176, 268, 93, 117,\n",
" 178, 215, 112, 76, 120, 231, 139, 142, 227, 110, 295, 159, 210,\n",
" 77, 6, 159, 42])"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"birthdays=np.arange(1,366,1)\n",
"n=30\n",
"one_run=np.random.choice(birthdays,n)\n",
"one_run"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Are there duplicates in the `one_run` array? It is not easy to answer by just looking at the above output, but we can use the `numpy` sorting function to help with that."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 6, 42, 76, 77, 93, 110, 112, 117, 120, 122, 124, 139, 142,\n",
" 144, 159, 159, 176, 178, 210, 215, 227, 231, 265, 268, 295, 304,\n",
" 326, 329, 353, 356])"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.sort(one_run)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We need a function that will give us the number of occurrences of the most frequent day. There are many ways to achieve this:\n",
"- use the `Counter` function we introduced before;\n",
"- `numpy` has a useful function called `bincount`;\n",
"- write your own function.\n",
"\n",
"We will use the first option; using the other two are useful exercises for developing your coding skills. Let's first recall the `Counter` function output:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Counter({15: 1, 2: 3, 7: 2, 1: 1})"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from collections import Counter\n",
"Counter([15,2,7,2,2,1,7])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As you can see in the above output, `Counter` calculates for each element in the list or array the number of occurrences. The most frequent occurrence (in case of ties, the one that occurs first in our list/array) can be obtained as below. The following cells show the code for extracting: (i) the most frequent element and the number of times it appears in our list or array; (ii) the number of appearances in the list of the most frequent element."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[(2, 3)]"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Counter([15,2,7,2,2,1,7]).most_common(1)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Counter([15,2,7,2,2,1,7]).most_common(1)[0][1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Repeated simulations and summary\n",
"\n",
"We now create a function that will simulate **nrep** repetitions of the \n",
"birthday setting for **n** subjects. The function returns an array that has **nrep** entries, each showing the count (frequency) of the most frequent birthday in one simulation."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"def birthday_sim(n,nrep):\n",
" '''Estimate birthday matching probabilities using nrep simulations'''\n",
" outcomes = np.array([])\n",
" for i in np.arange(nrep):\n",
" outcomes = np.append(outcomes, \n",
" Counter(np.random.choice(birthdays,n)).most_common(1)[0][1])\n",
" return outcomes"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"scrolled": true
},
"outputs": [
{
"data": {
"text/plain": [
"array([1., 2., 1., 1., 1., 2., 1., 2., 2., 2.])"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# results for ten repetitions of a group of 23 people\n",
"birthday_sim(23,10)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"We are ready now to estimate the probability that at least two people share a birthday in a group of n random subjects. In a similar fashion to the coin toss example where the probability of heads was given by the long run frequency (number of heads / number of tosses), the estimated probability is \n",
"\n",
"$$\\frac{\\mbox{number of repetitions with shared birthdays}}{\\mbox{nrep}}$$\n",
"\n",
"As mentioned above, the number of repetitions affects both accuracy (better accuracy for more repetitions) and computational time. Chapter 12 provides more details on this issue. In the cell code below we use 1000 repetitions."
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.486"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"n=23\n",
"nrep=1000\n",
"sum(birthday_sim(n,nrep)>=2)/nrep"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that the result we obtain is close but not equal to the probability we calculated at the beginning of this chapter (0.5073). Increasing the number of repetitions will lead to an estimate that is closer to the exact probability. Also, rerunning the above cell will lead to a (slightly) different result:"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.514"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"n=23\n",
"nrep=1000\n",
"sum(birthday_sim(n,nrep)>=2)/nrep"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## On the assumptions used in simulations\n",
"\n",
"It is important to consider whether the assumptions made in the simulations are the same or different than the ones we made in the mathematical derivation. The answer is yes (same assumptions) because: (i) the `birthdays` array has 365 elements (so we implicitly assume the year has 365 days); and (ii) birthdates are independent and equally likely (because the `numpy` `random.choice` function is designed to sample elements this way when only sample size is provided). \n",
"\n",
"We will talk in a later section about ways to relax these assumptions."
]
}
],
"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.8.8"
}
},
"nbformat": 4,
"nbformat_minor": 2
}