"
11 | ]
12 | },
13 | {
14 | "cell_type": "markdown",
15 | "metadata": {},
16 | "source": [
17 | "## An Introduction to Bayesian Statistical Analysis"
18 | ]
19 | },
20 | {
21 | "cell_type": "markdown",
22 | "metadata": {},
23 | "source": [
24 | "Before we jump in to model-building and using MCMC to do wonderful things, it is useful to understand a few of the theoretical underpinnings of the Bayesian statistical paradigm. A little theory (and I do mean a *little*) goes a long way towards being able to apply the methods correctly and effectively.\n",
25 | "\n",
26 | "There are several introductory references to Bayesian statistics that go well beyond what we will cover here. Some suggestions:\n",
27 | "\n",
28 | "[Chapter 11 of Schaum's Outline of Probability and Statistics](https://www.kobo.com/us/en/ebook/schaum-s-outline-of-probability-and-statistics-4th-edition)\n",
29 | "\n",
30 | "[Introduction to Bayesian Statistics](https://www.stat.auckland.ac.nz/~brewer/stats331.pdf)\n",
31 | "\n",
32 | "[Bayesian Statistics](https://www.york.ac.uk/depts/maths/histstat/pml1/bayes/book.htm)\n",
33 | "\n",
34 | "\n",
35 | "## What *is* Bayesian Statistical Analysis?\n",
36 | "\n",
37 | "Though many of you will have taken a statistics course or two during your undergraduate (or graduate) education, most of those who have will likely not have had a course in *Bayesian* statistics. Most introductory courses, particularly for non-statisticians, still do not cover Bayesian methods at all, except perhaps to derive Bayes' formula as a trivial rearrangement of the definition of conditional probability. Even today, Bayesian courses are typically tacked onto the curriculum, rather than being integrated into the program.\n",
38 | "\n",
39 | "In fact, Bayesian statistics is not just a particular method, or even a class of methods; it is an entirely different paradigm for doing statistical analysis.\n",
40 | "\n",
41 | "> Practical methods for making inferences from data using probability models for quantities we observe and about which we wish to learn.\n",
42 | "*-- Gelman et al. 2013*\n",
43 | "\n",
44 | "A Bayesian model is described by parameters, uncertainty in those parameters is described using probability distributions."
45 | ]
46 | },
47 | {
48 | "cell_type": "markdown",
49 | "metadata": {},
50 | "source": [
51 | "All conclusions from Bayesian statistical procedures are stated in terms of *probability statements*\n",
52 | "\n",
53 | "\n",
54 | "\n",
55 | "This confers several benefits to the analyst, including:\n",
56 | "\n",
57 | "- ease of interpretation, summarization of uncertainty\n",
58 | "- can incorporate uncertainty in parent parameters\n",
59 | "- easy to calculate summary statistics"
60 | ]
61 | },
62 | {
63 | "cell_type": "markdown",
64 | "metadata": {},
65 | "source": [
66 | "## What is Probability?\n",
67 | "\n",
68 | "> *Misunderstanding of probability may be the greatest of all impediments to scientific literacy.*\n",
69 | "> — Stephen Jay Gould\n",
70 | "\n",
71 | "It is useful to start with defining what probability is. There are three main categories:\n",
72 | "\n",
73 | "### 1. Classical probability\n",
74 | "\n",
75 | "
\n",
76 | "$Pr(X=x) = \\frac{\\text{# x outcomes}}{\\text{# possible outcomes}}$\n",
77 | "
\n",
78 | "\n",
79 | "Classical probability is an assessment of **possible** outcomes of elementary events. Elementary events are assumed to be equally likely.\n",
80 | "\n",
81 | "### 2. Frequentist probability\n",
82 | "\n",
83 | "
\n",
84 | "$Pr(X=x) = \\lim_{n \\rightarrow \\infty} \\frac{\\text{# times x has occurred}}{\\text{# independent and identical trials}}$\n",
85 | "
\n",
86 | "\n",
87 | "This interpretation considers probability to be the relative frequency \"in the long run\" of outcomes.\n",
88 | "\n",
89 | "### 3. Subjective probability\n",
90 | "\n",
91 | "
\n",
92 | "$Pr(X=x)$\n",
93 | "
\n",
94 | "\n",
95 | "Subjective probability is a measure of one's uncertainty in the value of \\\\(X\\\\). It characterizes the state of knowledge regarding some unknown quantity using probability.\n",
96 | "\n",
97 | "It is not associated with long-term frequencies nor with equal-probability events.\n",
98 | "\n",
99 | "For example:\n",
100 | "\n",
101 | "- X = the true prevalence of diabetes in Austin is < 15%\n",
102 | "- X = the blood type of the person sitting next to you is type A\n",
103 | "- X = the Nashville Predators will win next year's Stanley Cup\n",
104 | "- X = it is raining in Nashville\n"
105 | ]
106 | },
107 | {
108 | "cell_type": "markdown",
109 | "metadata": {},
110 | "source": [
111 | "## Bayesian vs Frequentist Statistics: What's the difference?\n",
112 | "\n",
113 | "See the [VanderPlas paper and video](http://conference.scipy.org/proceedings/scipy2014/pdfs/vanderplas.pdf).\n",
114 | "\n",
115 | "\n",
116 | "\n",
117 | "Any statistical paradigm, Bayesian or otherwise, involves at least the following: \n",
118 | "\n",
119 | "1. Some **unknown quantities** about which we are interested in learning or testing. We call these *parameters*.\n",
120 | "2. Some **data** which have been observed, and hopefully contain information about (1).\n",
121 | "3. One or more **models** that relate the data to the parameters, and is the instrument that is used to learn.\n"
122 | ]
123 | },
124 | {
125 | "cell_type": "markdown",
126 | "metadata": {},
127 | "source": [
128 | "### The Frequentist World View\n",
129 | "\n",
130 | "\n",
131 | "\n",
132 | "- The data that have been observed are considered **random**, because they are realizations of random processes, and hence will vary each time one goes to observe the system.\n",
133 | "- Model parameters are considered **fixed**. The parameters' values are unknown, but they are fixed, and so we *condition* on them.\n",
134 | "\n",
135 | "In mathematical notation, this implies a (very) general model of the following form:\n",
136 | "\n",
137 | "
\n",
138 | "$f(y | \\theta)$\n",
139 | "
\n",
140 | "\n",
141 | "Here, the model \\\\(f\\\\) accepts data values \\\\(y\\\\) as an argument, conditional on particular values of \\\\(\\theta\\\\).\n",
142 | "\n",
143 | "Frequentist inference typically involves deriving **estimators** for the unknown parameters. Estimators are formulae that return estimates for particular estimands, as a function of data. They are selected based on some chosen optimality criterion, such as *unbiasedness*, *variance minimization*, or *efficiency*.\n",
144 | "\n",
145 | "> For example, lets say that we have collected some data on the prevalence of autism spectrum disorder (ASD) in some defined population. Our sample includes \\\\(n\\\\) sampled children, \\\\(y\\\\) of them having been diagnosed with autism. A frequentist estimator of the prevalence \\\\(p\\\\) is:\n",
146 | "\n",
147 | ">
\n",
150 | "\n",
151 | "> Why this particular function? Because it can be shown to be unbiased and minimum-variance.\n",
152 | "\n",
153 | "It is important to note that new estimators need to be derived for every estimand that is introduced.\n",
154 | "\n",
155 | "### The Bayesian World View\n",
156 | "\n",
157 | "\n",
158 | "\n",
159 | "- Data are considered **fixed**. They used to be random, but once they were written into your lab notebook/spreadsheet/IPython notebook they do not change.\n",
160 | "- Model parameters themselves may not be random, but Bayesians use probability distribtutions to describe their uncertainty in parameter values, and are therefore treated as **random**. In some cases, it is useful to consider parameters as having been sampled from probability distributions.\n",
161 | "\n",
162 | "This implies the following form:\n",
163 | "\n",
164 | "
\n",
165 | "$p(\\theta | y)$\n",
166 | "
\n",
167 | "\n",
168 | "This formulation used to be referred to as ***inverse probability***, because it infers from observations to parameters, or from effects to causes.\n",
169 | "\n",
170 | "Bayesians do not seek new estimators for every estimation problem they encounter. There is only one estimator for Bayesian inference: **Bayes' Formula**."
171 | ]
172 | },
173 | {
174 | "cell_type": "markdown",
175 | "metadata": {},
176 | "source": [
177 | "## Bayes' Formula\n",
178 | "\n",
179 | "Given two events A and B, the conditional probability of A given that B is true is expressed as follows:\n",
180 | "\n",
181 | "$Pr(A|B) = \\frac{Pr(B|A)Pr(A)}{Pr(B)}$\n",
182 | "\n",
183 | "where P(B)>0. Although Bayes' theorem is a fundamental result of probability theory, it has a specific interpretation in Bayesian statistics. \n",
184 | "\n",
185 | "In the above equation, A usually represents a proposition (such as the statement that a coin lands on heads fifty percent of the time) and B represents the evidence, or new data that is to be taken into account (such as the result of a series of coin flips). P(A) is the **prior** probability of A which expresses one's beliefs about A before evidence is taken into account. The prior probability may also quantify prior knowledge or information about A. \n",
186 | "\n",
187 | "P(B|A) is the **likelihood**, which can be interpreted as the probability of the evidence B given that A is true. The likelihood quantifies the extent to which the evidence B supports the proposition A. \n",
188 | "\n",
189 | "P(A|B) is the **posterior** probability, the probability of the proposition A after taking the evidence B into account. Essentially, Bayes' theorem updates one's prior beliefs P(A) after considering the new evidence B.\n",
190 | "\n",
191 | "P(B) is the **marginal likelihood**, which can be interpreted as the sum of the conditional probability of B under all possible events $A_i$\n",
192 | "in the sample\n",
193 | "space \n",
194 | "\n",
195 | "- For two events $P(B) = P(B|A)P(A) + P(B|\\bar{A})P(\\bar{A})$\n"
196 | ]
197 | },
198 | {
199 | "cell_type": "markdown",
200 | "metadata": {},
201 | "source": [
202 | "### Example: Genetic probabilities\n",
203 | "\n",
204 | "Let's put Bayesian inference into action using a very simple example. I've chosen this example because it is one of the rare occasions where the posterior can be calculated by hand. We will show how data can be used to update our belief in competing hypotheses.\n",
205 | "\n",
206 | "Hemophilia is a rare genetic disorder that impairs the ability for the body's clotting factors to coagualate the blood in response to broken blood vessels. The disease is an **x-linked recessive** trait, meaning that there is only one copy of the gene in males but two in females, and the trait can be masked by the dominant allele of the gene. \n",
207 | "\n",
208 | "This implies that males with 1 gene are *affected*, while females with 1 gene are unaffected, but *carriers* of the disease. Having 2 copies of the disease is fatal, so this genotype does not exist in the population.\n",
209 | "\n",
210 | "In this example, consider a woman whose mother is a carrier (because her brother is affected) and who marries an unaffected man. Let's now observe some data: the woman has two consecutive (non-twin) sons who are unaffected. We are interested in determining **if the woman is a carrier**.\n",
211 | "\n",
212 | "\n",
213 | "\n",
214 | "To set up this problem, we need to set up our probability model. The unknown quantity of interest is simply an indicator variable \\\\(W\\\\) that equals 1 if the woman is affected, and zero if she is not. We are interested in the probability that the variable equals one, given what we have observed:\n",
215 | "\n",
216 | "\\\\[Pr(W=1 | s_1=0, s_2=0)\\\\]\n",
217 | "\n",
218 | "Our prior information is based on what we know about the woman's ancestry: her mother was a carrier. Hence, the prior is \\\\(Pr(W=1) = 0.5\\\\). Another way of expressing this is in terms of the **prior odds**, or:\n",
219 | "\n",
220 | "\\\\[O(W=1) = \\frac{Pr(W=1)}{Pr(W=0)} = 1\\\\]\n",
221 | "\n",
222 | "Now for the likelihood: The form of this function is:\n",
223 | "\n",
224 | "\\\\[L(W | s_1=0, s_2=0)\\\\]\n",
225 | "\n",
226 | "This can be calculated as the probability of observing the data for any passed value for the parameter. For this simple problem, the likelihood takes only two possible values:\n",
227 | "\n",
228 | "\\\\[\\begin{aligned}\n",
229 | "L(W=1 &| s_1=0, s_2=0) = (0.5)(0.5) = 0.25 \\cr\n",
230 | "L(W=0 &| s_1=0, s_2=0) = (1)(1) = 1\n",
231 | "\\end{aligned}\\\\]\n",
232 | "\n",
233 | "With all the pieces in place, we can now apply Bayes' formula to calculate the posterior probability that the woman is a carrier:\n",
234 | "\n",
235 | "\\\\[\\begin{aligned}\n",
236 | "Pr(W=1 | s_1=0, s_2=0) &= \\frac{L(W=1 | s_1=0, s_2=0) Pr(W=1)}{L(W=1 | s_1=0, s_2=0) Pr(W=1) + L(W=0 | s_1=0, s_2=0) Pr(W=0)} \\cr\n",
237 | " &= \\frac{(0.25)(0.5)}{(0.25)(0.5) + (1)(0.5)} \\cr\n",
238 | " &= 0.2\n",
239 | "\\end{aligned}\\\\]\n",
240 | "\n",
241 | "Hence, there is a 0.2 probability of the woman being a carrier.\n",
242 | "\n",
243 | "Its a bit trivial, but we can code this in Python:"
244 | ]
245 | },
246 | {
247 | "cell_type": "code",
248 | "execution_count": 13,
249 | "metadata": {},
250 | "outputs": [],
251 | "source": [
252 | "prior = 0.5\n",
253 | "p = 0.5\n",
254 | "\n",
255 | "L = lambda w, s: np.prod([(1-i, p**i * (1-p)**(1-i))[w] for i in s])"
256 | ]
257 | },
258 | {
259 | "cell_type": "code",
260 | "execution_count": 14,
261 | "metadata": {},
262 | "outputs": [
263 | {
264 | "data": {
265 | "text/plain": [
266 | "0.2"
267 | ]
268 | },
269 | "execution_count": 14,
270 | "metadata": {},
271 | "output_type": "execute_result"
272 | }
273 | ],
274 | "source": [
275 | "s = [0,0]\n",
276 | "\n",
277 | "post = L(1, s) * prior / (L(1, s) * prior + L(0, s) * (1 - prior))\n",
278 | "post"
279 | ]
280 | },
281 | {
282 | "cell_type": "markdown",
283 | "metadata": {},
284 | "source": [
285 | "Now, what happens if the woman has a third unaffected child? What is our estimate of her probability of being a carrier then? \n",
286 | "\n",
287 | "Bayes' formula makes it easy to update analyses with new information, in a sequential fashion. We simply assign the posterior from the previous analysis to be the prior for the new analysis, and proceed as before:"
288 | ]
289 | },
290 | {
291 | "cell_type": "code",
292 | "execution_count": 15,
293 | "metadata": {},
294 | "outputs": [
295 | {
296 | "data": {
297 | "text/plain": [
298 | "0.5"
299 | ]
300 | },
301 | "execution_count": 15,
302 | "metadata": {},
303 | "output_type": "execute_result"
304 | }
305 | ],
306 | "source": [
307 | "L(1, [0])"
308 | ]
309 | },
310 | {
311 | "cell_type": "code",
312 | "execution_count": 16,
313 | "metadata": {},
314 | "outputs": [
315 | {
316 | "data": {
317 | "text/plain": [
318 | "0.11111111111111112"
319 | ]
320 | },
321 | "execution_count": 16,
322 | "metadata": {},
323 | "output_type": "execute_result"
324 | }
325 | ],
326 | "source": [
327 | "s = [0]\n",
328 | "prior = post\n",
329 | "\n",
330 | "L(1, s) * prior / (L(1, s) * prior + L(0, s) * (1 - prior))"
331 | ]
332 | },
333 | {
334 | "cell_type": "markdown",
335 | "metadata": {},
336 | "source": [
337 | "Thus, observing a third unaffected child has further reduced our belief that the mother is a carrier."
338 | ]
339 | },
340 | {
341 | "cell_type": "markdown",
342 | "metadata": {},
343 | "source": [
344 | "## More on Bayesian Terminology\n",
345 | "\n",
346 | "Replacing Bayes' Formula with conventional Bayes terms:\n",
347 | "\n",
348 | "\n",
349 | "\n",
350 | "The equation expresses how our belief about the value of \\\\(\\theta\\\\), as expressed by the **prior distribution** \\\\(P(\\theta)\\\\) is reallocated following the observation of the data \\\\(y\\\\), as expressed by the posterior distribution the posterior distribution.\n",
351 | "\n",
352 | "### Marginal\n",
353 | "\n",
354 | "The denominator \\\\(P(y)\\\\) is the likelihood integrated over all \\\\(\\theta\\\\):\n",
355 | "\n",
356 | "
\n",
359 | "\n",
360 | "This usually cannot be calculated directly. However it is just a normalization constant which doesn't depend on the parameter; the act of summation washes out whatever info we had about the parameter. Hence it can often be ignored;The normalising constant makes sure that the resulting posterior distribution is a true probability distribution by ensuring that the sum of the distribution is equal to 1.\n",
361 | "\n",
362 | "In some cases we don’t care about this property of the distribution. We only care about where the peak of the distribution occurs, regardless of whether the distribution is normalised or not\n",
363 | "\n",
364 | "Unfortunately sometimes we are obliged to calculate it. The intractability of this integral is one of the factors that has contributed to the under-utilization of Bayesian methods by statisticians.\n",
365 | "\n",
366 | "### Prior\n",
367 | "\n",
368 | "Once considered a controversial aspect of Bayesian analysis, the prior distribution characterizes what is known about an unknown quantity before observing the data from the present study. Thus, it represents the information state of that parameter. It can be used to reflect the information obtained in previous studies, to constrain the parameter to plausible values, or to represent the population of possible parameter values, of which the current study's parameter value can be considered a sample.\n",
369 | "\n",
370 | "### Likelihood\n",
371 | "\n",
372 | "The likelihood represents the information in the observed data, and is used to update prior distributions to posterior distributions. This updating of belief is justified becuase of the **likelihood principle**, which states:\n",
373 | "\n",
374 | "> Following observation of \\\\(y\\\\), the likelihood \\\\(L(\\theta|y)\\\\) contains all experimental information from \\\\(y\\\\) about the unknown \\\\(\\theta\\\\).\n",
375 | "\n",
376 | "Bayesian analysis satisfies the likelihood principle because the posterior distribution's dependence on the data is only through the likelihood. In comparison, most frequentist inference procedures violate the likelihood principle, because inference will depend on the design of the trial or experiment.\n",
377 | "\n",
378 | "What is a likelihood function? It is closely related to the probability density (or mass) function. Taking a common example, consider some data that are binomially distributed (that is, they describe the outcomes of \\\\(n\\\\) binary events). Here is the binomial sampling distribution:\n",
379 | "\n",
380 | "$p(Y|\\theta) = {n \\choose y} \\theta^{y} (1-\\theta)^{n-y}$\n",
381 | "\n",
382 | "We can code this easily in Python:"
383 | ]
384 | },
385 | {
386 | "cell_type": "code",
387 | "execution_count": 8,
388 | "metadata": {},
389 | "outputs": [],
390 | "source": [
391 | "from scipy.special import comb\n",
392 | "\n",
393 | "pbinom = lambda y, n, p: comb(n, y) * p**y * (1-p)**(n-y)"
394 | ]
395 | },
396 | {
397 | "cell_type": "markdown",
398 | "metadata": {},
399 | "source": [
400 | "This function returns the probability of observing \\\\(y\\\\) events from \\\\(n\\\\) trials, where events occur independently with probability \\\\(p\\\\)."
401 | ]
402 | },
403 | {
404 | "cell_type": "code",
405 | "execution_count": 9,
406 | "metadata": {},
407 | "outputs": [
408 | {
409 | "data": {
410 | "text/plain": [
411 | "0.1171875"
412 | ]
413 | },
414 | "execution_count": 9,
415 | "metadata": {},
416 | "output_type": "execute_result"
417 | }
418 | ],
419 | "source": [
420 | "pbinom(3, 10, 0.5)"
421 | ]
422 | },
423 | {
424 | "cell_type": "code",
425 | "execution_count": 10,
426 | "metadata": {},
427 | "outputs": [
428 | {
429 | "data": {
430 | "text/plain": [
431 | "7.450580596923828e-07"
432 | ]
433 | },
434 | "execution_count": 10,
435 | "metadata": {},
436 | "output_type": "execute_result"
437 | }
438 | ],
439 | "source": [
440 | "pbinom(1, 25, 0.5)"
441 | ]
442 | },
443 | {
444 | "cell_type": "code",
445 | "execution_count": 11,
446 | "metadata": {},
447 | "outputs": [
448 | {
449 | "data": {
450 | "image/png": "iVBORw0KGgoAAAANSUhEUgAAAX0AAAD8CAYAAACb4nSYAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDMuMC4yLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvOIA7rQAAEcpJREFUeJzt3X+MHOd93/H3h2Rl52IkkaNr0Yg6Hp0widWmtYqNktaoUdS/6CQQDcSG6Z4LpRFwQFG1ad2iUCqgAhgQcJKicP8QWh1SpUZ6ieIoAXIJ7CiK7SR/BHZ4tFwnkiKYZkjqSrdiKtctSsMqrW//mFWzPB19c+TeLm+f9ws4zM4zz+x+H+7uZ4czszupKiRJbdg37QIkSZNj6EtSQwx9SWqIoS9JDTH0Jakhhr4kNcTQl6SGGPqS1BBDX5IacmDaBWx222231eLi4rTLkKQ95fTp039WVfPb9bvpQn9xcZH19fVplyFJe0qS8336uXtHkhrSK/STHE3yXJIzSR7YYvkHkzyT5PNJPpHk0Miyryf53PBvbZzFS5J2ZtvdO0n2Aw8Dbwc2gFNJ1qrqmZFuTwGDqrqc5B8CPwO8b7jsq1X1pjHXLUm6Dn229O8GzlTV2ap6CXgMODbaoao+VVWXh7OfBg6Ot0xJ0jj0Cf3bged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k1U101uAVfXfgOeTfM+w6a3AM1MsaRIuAD+YZG74On8rM37wesTo9cbvBX593A9wYNx3OA1VdSXJ/cAT/Pl1fJ+eclm77c3A3wf+KMnnhm3/qqo+NsWatDv+MbA63KA5C/yDKdezq6rqM0keBz5Ld5baU8zgt3OT/BLwd4DbkmwADwEfAj6a5D66D7/3jv1x/UauJLVjVnbvSJJ6MPQlqSGGviQ1xNCXpIYY+pLUEENfkhpi6EtSQwx9SWrI/wMPxnMEu8DVOAAAAABJRU5ErkJggg==\n",
451 | "text/plain": [
452 | ""
453 | ]
454 | },
455 | "metadata": {
456 | "needs_background": "light"
457 | },
458 | "output_type": "display_data"
459 | }
460 | ],
461 | "source": [
462 | "yvals = range(10+1)\n",
463 | "plt.plot(yvals, [pbinom(y, 10, 0.5) for y in yvals], 'ro');"
464 | ]
465 | },
466 | {
467 | "cell_type": "markdown",
468 | "metadata": {},
469 | "source": [
470 | "What about the likelihood function? \n",
471 | "\n",
472 | "The likelihood function is the exact same form as the sampling distribution, except that we are now interested in varying the parameter for a given dataset."
473 | ]
474 | },
475 | {
476 | "cell_type": "code",
477 | "execution_count": 12,
478 | "metadata": {},
479 | "outputs": [
480 | {
481 | "data": {
482 | "image/png": "iVBORw0KGgoAAAANSUhEUgAAAX0AAAD8CAYAAACb4nSYAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDMuMC4yLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvOIA7rQAAIABJREFUeJzt3Xl8lOW99/HPb2ayEJIQIIFAFhJ2wo4hLG4oLriBu4BrS8tRa9fz9Kk9PdXWnu7H03Nal4rVU21VtFoV2dQqi1VZwhYICCQBsgIhgQDZZ+Z6/sjgE2MgEzIz9yy/9+uVF5OZe2a+N0m+uXPdyyXGGJRSSkUGm9UBlFJKBY6WvlJKRRAtfaWUiiBa+kopFUG09JVSKoJo6SulVATR0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pFEC19pZSKIFr6SikVQbT0lVIqgmjpK6VUBNHSV0qpCPL/AKHVemphw/VLAAAAAElFTkSuQmCC\n",
483 | "text/plain": [
484 | ""
485 | ]
486 | },
487 | "metadata": {
488 | "needs_background": "light"
489 | },
490 | "output_type": "display_data"
491 | }
492 | ],
493 | "source": [
494 | "pvals = np.linspace(0, 1)\n",
495 | "y = 4\n",
496 | "plt.plot(pvals, [pbinom(y, 10, p) for p in pvals]);"
497 | ]
498 | },
499 | {
500 | "cell_type": "markdown",
501 | "metadata": {},
502 | "source": [
503 | "So, though we are dealing with the same equation, these are entirely different functions; the distribution is discrete, while the likelihood is continuous; the distribtion's range is from 0 to 10, while the likelihood's is 0 to 1; the distribution integrates (sums) to one, while the likelhood does not."
504 | ]
505 | },
506 | {
507 | "cell_type": "markdown",
508 | "metadata": {},
509 | "source": [
510 | "### Posterior\n",
511 | "\n",
512 | "The mathematical form \\\\(p(\\theta | y)\\\\) that we associated with the Bayesian approach is referred to as a **posterior distribution**.\n",
513 | "\n",
514 | "> posterior /pos·ter·i·or/ (pos-tēr´e-er) later in time; subsequent.\n",
515 | "\n",
516 | "Why posterior? Because it tells us what we know about the unknown \\\\(\\theta\\\\) *after* having observed \\\\(y\\\\)."
517 | ]
518 | },
519 | {
520 | "cell_type": "markdown",
521 | "metadata": {},
522 | "source": [
523 | "## Why be Bayesian?\n",
524 | "\n",
525 | "At this point, it is worth addressing the question of why one might consider an alternative statistical paradigm to the classical/frequentist statistical approach. After all, it is not always easy to specify a full probabilistic model, nor to obtain output from the model once it is specified. So, why bother?\n",
526 | "\n",
527 | "> ... the Bayesian approach is attractive because it is useful. Its usefulness derives in large measure from its simplicity. Its simplicity allows the investigation of far more complex models than can be handled by the tools in the classical toolbox. \n",
528 | "*-- Link and Barker 2010*\n",
529 | "\n",
530 | "We already noted that there is just one estimator in Bayesian inference, which lends to its ***simplicity***. Moreover, Bayes affords a conceptually simple way of coping with multiple parameters; the use of probabilistic models allows very complex models to be assembled in a modular fashion, by factoring a large joint model into the product of several conditional probabilities.\n",
531 | "\n",
532 | "Bayesian statistics is also attractive for its ***coherence***. All unknown quantities for a particular problem are treated as random variables, to be estimated in the same way. Existing knowledge is given precise mathematical expression, allowing it to be integrated with information from the study dataset, and there is formal mechanism for incorporating new information into an existing analysis.\n",
533 | "\n",
534 | "Finally, Bayesian statistics confers an advantage in the ***interpretability*** of analytic outputs. Because models are expressed probabilistically, results can be interpreted probabilistically. Probabilities are easy for users (particularly non-technical users) to understand and apply."
535 | ]
536 | },
537 | {
538 | "cell_type": "markdown",
539 | "metadata": {},
540 | "source": [
541 | "### Example: confidence vs. credible intervals\n",
542 | "\n",
543 | "A commonly-used measure of uncertainty for a statistical point estimate in classical statistics is the ***confidence interval***. Most scientists were introduced to the confidence interval during their introductory statistics course(s) in college. Yet, a large number of users mis-interpret the confidence interval.\n",
544 | "\n",
545 | "Here is the mathematical definition of a 95% confidence interval for some unknown scalar quantity that we will here call \\\\(\\theta\\\\):\n",
546 | "\n",
547 | "
\n",
550 | "\n",
551 | "how the endpoints of this interval are calculated varies according to the sampling distribution of \\\\(Y\\\\), but for as an example, the confidence interval for the population mean when \\\\(Y\\\\) is normally distributed is calculated by:\n",
552 | "\n",
553 | "$Pr(\\bar{Y} - 1.96\\frac{\\sigma}{\\sqrt{n}}< \\theta < \\bar{Y} + 1.96\\frac{\\sigma}{\\sqrt{n}}) = 0.95$\n",
554 | "\n",
555 | "It would be tempting to use this definition to conclude that there is a 95% chance \\\\(\\theta\\\\) is between \\\\(a(Y)\\\\) and \\\\(b(Y)\\\\), but that would be a mistake. \n",
556 | "\n",
557 | "Recall that for frequentists, unknown parameters are **fixed**, which means there is no probability associated with them being any value except what they are fixed to. Here, the interval itself, and not \\\\(\\theta\\\\) is the random variable. The actual interval calculated from the data is just one possible realization of a random process, and it must be strictly interpreted only in relation to an infinite sequence of identical trials that might be (but never are) conducted in practice.\n",
558 | "\n",
559 | "A valid interpretation of the above would be:\n",
560 | "\n",
561 | "> If the experiment were repeated an infinite number of times, 95% of the calculated intervals would contain \\\\(\\theta\\\\).\n",
562 | "\n",
563 | "This is what the statistical notion of \"confidence\" entails, and this sets it apart from probability intervals.\n",
564 | "\n",
565 | "Since they regard unknown parameters as random variables, Bayesians can and do use probability intervals to describe what is known about the value of an unknown quantity. These intervals are commonly known as ***credible intervals***.\n",
566 | "\n",
567 | "The definition of a 95% credible interval is:\n",
568 | "\n",
569 | "
\n",
572 | "\n",
573 | "Notice that we condition here on the data \\\\(y\\\\) instead of the unknown \\\\(\\theta\\\\). Thus, the endpoints are fixed and the variable is random. \n",
574 | "\n",
575 | "We are allowed to interpret this interval as:\n",
576 | "\n",
577 | "> There is a 95% chance \\\\(\\theta\\\\) is between \\\\(a\\\\) and \\\\(b\\\\).\n",
578 | "\n",
579 | "Hence, the credible interval is a statement of what we know about the value of \\\\(\\theta\\\\) based on the observed data."
580 | ]
581 | },
582 | {
583 | "cell_type": "markdown",
584 | "metadata": {},
585 | "source": [
586 | "## Bayesian Inference, in 3 Easy Steps\n",
587 | "\n",
588 | "We are now ready (and willing!) to apply Bayesian methods to our problem. Gelman et al. (2013) describe the process of conducting Bayesian statistical analysis in 3 steps:\n",
589 | "\n",
590 | "\n",
591 | "\n",
592 | "\n",
593 | "\n",
594 | "### Step 1: Specify a probability model\n",
595 | "\n",
596 | "As was noted above, Bayesian statistics involves using probability models to solve problems. So, the first task is to *completely specify* the model in terms of probability distributions. This includes everything: unknown parameters, data, covariates, missing data, predictions. All must be assigned some probability density.\n",
597 | "\n",
598 | "This step involves making choices.\n",
599 | "\n",
600 | "- what is the form of the sampling distribution of the data?\n",
601 | "- what form best describes our uncertainty in the unknown parameters?\n",
602 | "\n",
603 | "### Step 2: Calculate a posterior distribution\n",
604 | "\n",
605 | "The posterior distribution is formulated as a function of the probability model that was specified in Step 1. Usually, we can write it down but we cannot calculate it analytically. In fact, the difficulty inherent in calculating the posterior distribution for most models of interest is perhaps the major contributing factor for the lack of widespread adoption of Bayesian methods for data analysis.\n",
606 | "\n",
607 | "**But**, once the posterior distribution is calculated, you get a lot for free:\n",
608 | "\n",
609 | "- point estimates\n",
610 | "- credible intervals\n",
611 | "- quantiles\n",
612 | "- predictions\n",
613 | "\n",
614 | "### Step 3: Check your model\n",
615 | "\n",
616 | "Though frequently ignored in practice, it is critical that the model and its outputs be assessed before using the outputs for inference. Models are specified based on assumptions that are largely unverifiable, so the least we can do is examine the output in detail, relative to the specified model and the data that were used to fit the model.\n",
617 | "\n",
618 | "Specifically, we must ask:\n",
619 | "\n",
620 | "- does the model fit data?\n",
621 | "- are the conclusions reasonable?\n",
622 | "- are the outputs sensitive to changes in model structure?\n"
623 | ]
624 | },
625 | {
626 | "cell_type": "markdown",
627 | "metadata": {},
628 | "source": [
629 | "---"
630 | ]
631 | },
632 | {
633 | "cell_type": "markdown",
634 | "metadata": {},
635 | "source": [
636 | "## References\n",
637 | "\n",
638 | "Gelman A, Carlin JB, Stern HS, Dunson DB, Vehtari A, Rubin DB. Bayesian Data Analysis, Third Edition. CRC Press; 2013."
639 | ]
640 | },
641 | {
642 | "cell_type": "code",
643 | "execution_count": 17,
644 | "metadata": {},
645 | "outputs": [
646 | {
647 | "data": {
648 | "text/html": [
649 | "\n",
701 | "\n"
716 | ],
717 | "text/plain": [
718 | ""
719 | ]
720 | },
721 | "execution_count": 17,
722 | "metadata": {},
723 | "output_type": "execute_result"
724 | }
725 | ],
726 | "source": [
727 | "from IPython.core.display import HTML\n",
728 | "def css_styling():\n",
729 | " styles = open(\"styles/custom.css\", \"r\").read()\n",
730 | " return HTML(styles)\n",
731 | "css_styling()"
732 | ]
733 | }
734 | ],
735 | "metadata": {
736 | "kernelspec": {
737 | "display_name": "Python 3",
738 | "language": "python",
739 | "name": "python3"
740 | },
741 | "language_info": {
742 | "codemirror_mode": {
743 | "name": "ipython",
744 | "version": 3
745 | },
746 | "file_extension": ".py",
747 | "mimetype": "text/x-python",
748 | "name": "python",
749 | "nbconvert_exporter": "python",
750 | "pygments_lexer": "ipython3",
751 | "version": "3.7.2"
752 | },
753 | "toc": {
754 | "base_numbering": 1,
755 | "nav_menu": {
756 | "height": "12px",
757 | "width": "325px"
758 | },
759 | "number_sections": true,
760 | "sideBar": true,
761 | "skip_h1_title": false,
762 | "title_cell": "Table of Contents",
763 | "title_sidebar": "Contents",
764 | "toc_cell": true,
765 | "toc_position": {},
766 | "toc_section_display": true,
767 | "toc_window_display": true
768 | }
769 | },
770 | "nbformat": 4,
771 | "nbformat_minor": 1
772 | }
773 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Bayesian Statistical Analysis in Python
2 |
3 | The aim of this course is to introduce new users to the Bayesian approach of statistical modeling and analysis, so that they can use Python packages such as NumPy, SciPy and [PyMC](https://github.com/pymc-devs/pymc) effectively to analyze their own data. It is designed to get users quickly up and running with Bayesian methods, incorporating just enough statistical background to allow users to understand, in general terms, what they are implementing. The tutorial will be example-driven, with illustrative case studies using real data. Selected methods will include approximation methods, importance sampling, Markov chain Monte Carlo (MCMC) methods such as Metropolis-Hastings and Slice sampling. In addition to model fitting, the tutorial will address important techniques for model checking, model comparison, and steps for preparing data and processing model output.
4 |
5 | 
6 |
7 | 
8 |
9 | All course content will be available as a GitHub repository, including IPython notebooks and example data.
10 |
11 | **To account for last-minute updates to course material, please clone the repository on the day of the tutorial**
12 |
13 | ## Tutorial Outline
14 |
15 | 1. Introduction to Bayesian statistics.
16 | 2. Markov chain Monte Carlo (MCMC)
17 | 3. The Essentials of PyMC
18 | 4. Fitting Statistical Models in PyMC
19 | 5. Hierarchical Modeling
20 | 6. Model Checking and Validation
21 |
22 | ## Package Installation
23 |
24 | This tutorial requires the following third-party packages to be installed on your system:
25 |
26 | - IPython
27 | - NumPy (>= 1.7)
28 | - SciPy (>= 0.12)
29 | - matplotlib (>=1.2.1)
30 | - PyMC 2.3.3
31 | - nose (OPTIONAL for testing)
32 | - pydot (OPTIONAL; also requires [GraphViz](http://www.graphviz.org))
33 | - gFortran (OPTIONAL to build from source)
34 |
35 | The easiest way to install the Python packages required for this tutorial is via [Anaconda](https://store.continuum.io/cshop/anaconda/), a scientific Python distribution offered by Continuum analytics. Several other tutorials will be recommending a similar setup.
36 |
37 | One of the key features of Anaconda is a command line utility called `conda` that can be used to manage third party packages. We have built a PyMC package for `conda` (Python 2.7.x only) that can be installed from your terminal via the following command:
38 |
39 | conda install -c https://conda.binstar.org/pymc pymc
40 |
41 | This should install any prerequisite packages that are required to run PyMC. Those wishing to run PyMC under Python 3 should build it from source:
42 |
43 | pip install git+git://github.com/pymc-devs/pymc.git@2.3.3
44 |
45 | For those of you on Mac OS X that are already using the [Homebrew](http://brew.sh) package manager, I have prepared a script that will install the entire Python scientific stack, including PyMC 2.3. You can download the script [here](https://gist.github.com/fonnesbeck/7de008b05e670d919b71) and run it via:
46 |
47 | sh install_superpack_brew.sh
48 |
--------------------------------------------------------------------------------
/check_env.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | import numpy
3 | import scipy
4 | import matplotlib
5 | import pymc
6 | import pydot
7 |
8 | # Run PyMC's test suite
9 | pymc.test()
--------------------------------------------------------------------------------
/data/cancer.csv:
--------------------------------------------------------------------------------
1 | y,n
2 | 0,1083
3 | 0,855
4 | 2,3461
5 | 0,657
6 | 1,1208
7 | 1,1025
8 | 0,527
9 | 2,1668
10 | 1,583
11 | 3,582
12 | 0,917
13 | 1,857
14 | 1,680
15 | 1,917
16 | 54,53637
17 | 0,874
18 | 0,395
19 | 1,581
20 | 3,588
21 | 0,383
22 |
--------------------------------------------------------------------------------
/examples/bioassay.py:
--------------------------------------------------------------------------------
1 | # Formula for LD 50
2 | ld50 = lambda alpha, beta: -alpha/beta
3 |
4 | # Inverse-logit transformation
5 | invlogit = lambda x: 1/(1. + np.exp(-x))
6 |
7 | dbinom = distributions.binom.logpmf
8 | dnorm = distributions.norm.logpdf
9 |
10 | def bioassay_post(alpha, beta):
11 |
12 | logp = dnorm(alpha, 0, 10000) + dnorm(beta, 0, 10000)
13 |
14 | p = invlogit(alpha + beta*np.array(log_dose))
15 |
16 | logp += dbinom(deaths, n, p).sum()
17 |
18 | return logp
19 |
20 | def metropolis_bioassay(n_iterations, initial_values, prop_var=1,
21 | tune_for=None, tune_interval=100):
22 |
23 | n_params = len(initial_values)
24 |
25 | # Initial proposal standard deviations
26 | prop_sd = [prop_var] * n_params
27 |
28 | # Initialize trace for parameters
29 | trace = np.empty((n_iterations+1, n_params))
30 |
31 | # Set initial values
32 | trace[0] = initial_values
33 | # Initialize acceptance counts
34 | accepted = [0]*n_params
35 |
36 | # Calculate joint posterior for initial values
37 | current_log_prob = bioassay_post(*trace[0])
38 |
39 | if tune_for is None:
40 | tune_for = n_iterations/2
41 |
42 | for i in range(n_iterations):
43 |
44 | if not i%1000: print 'Iteration', i
45 |
46 | # Grab current parameter values
47 | current_params = trace[i]
48 |
49 | for j in range(n_params):
50 |
51 | # Get current value for parameter j
52 | p = trace[i].copy()
53 |
54 | # Propose new value
55 | theta = rnorm(current_params[j], prop_sd[j])
56 |
57 | # Insert new value
58 | p[j] = theta
59 |
60 | # Calculate log posterior with proposed value
61 | proposed_log_prob = bioassay_post(*p)
62 |
63 | # Log-acceptance rate
64 | alpha = proposed_log_prob - current_log_prob
65 |
66 | # Sample a uniform random variate
67 | u = runif()
68 |
69 | # Test proposed value
70 | if np.log(u) < alpha:
71 | # Accept
72 | trace[i+1,j] = theta
73 | current_log_prob = proposed_log_prob
74 | accepted[j] += 1
75 | else:
76 | # Reject
77 | trace[i+1,j] = trace[i,j]
78 |
79 | # Tune every 100 iterations
80 | if (not (i+1) % tune_interval) and (i < tune_for):
81 |
82 | # Calculate aceptance rate
83 | acceptance_rate = (1.*accepted[j])/tune_interval
84 | if acceptance_rate<0.2:
85 | prop_sd[j] *= 0.9
86 | elif acceptance_rate>0.5:
87 | prop_sd[j] *= 1.1
88 |
89 | accepted[j] = 0
90 |
91 | return trace[tune_for:], accepted
92 |
93 | # Run MCMC
94 | tr, acc = metropolis_bioassay(10000, (0,0))
95 |
96 | for param, samples in zip(['intercept', 'slope'], tr.T):
97 | fig, axes = plt.subplots(1, 2)
98 | axes[0].plot(samples)
99 | axes[0].set_ylabel(param)
100 | axes[1].hist(samples[len(samples)/2:])
101 |
102 | a, b = tr.T
103 | print('LD50 mean is {}'.format(ld50(a,b).mean()))
--------------------------------------------------------------------------------
/images/123.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fonnesbeck/scipy2014_tutorial/d0b987e481a7bf7e513a24a2609c9410f7372d59/images/123.png
--------------------------------------------------------------------------------
/images/bayes.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fonnesbeck/scipy2014_tutorial/d0b987e481a7bf7e513a24a2609c9410f7372d59/images/bayes.png
--------------------------------------------------------------------------------
/images/bayes_formula.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fonnesbeck/scipy2014_tutorial/d0b987e481a7bf7e513a24a2609c9410f7372d59/images/bayes_formula.png
--------------------------------------------------------------------------------
/images/can-of-worms.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fonnesbeck/scipy2014_tutorial/d0b987e481a7bf7e513a24a2609c9410f7372d59/images/can-of-worms.jpg
--------------------------------------------------------------------------------
/images/conditional.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fonnesbeck/scipy2014_tutorial/d0b987e481a7bf7e513a24a2609c9410f7372d59/images/conditional.png
--------------------------------------------------------------------------------
/images/dag.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fonnesbeck/scipy2014_tutorial/d0b987e481a7bf7e513a24a2609c9410f7372d59/images/dag.png
--------------------------------------------------------------------------------
/images/fisher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fonnesbeck/scipy2014_tutorial/d0b987e481a7bf7e513a24a2609c9410f7372d59/images/fisher.png
--------------------------------------------------------------------------------
/images/hemophilia.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fonnesbeck/scipy2014_tutorial/d0b987e481a7bf7e513a24a2609c9410f7372d59/images/hemophilia.png
--------------------------------------------------------------------------------
/images/prob_model.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fonnesbeck/scipy2014_tutorial/d0b987e481a7bf7e513a24a2609c9410f7372d59/images/prob_model.png
--------------------------------------------------------------------------------
/notebook.tex:
--------------------------------------------------------------------------------
1 |
2 | % Default to the notebook output style
3 |
4 |
5 |
6 |
7 | % Inherit from the specified cell style.
8 |
9 |
10 |
11 |
12 |
13 | \documentclass[11pt]{article}
14 |
15 |
16 |
17 | \usepackage[T1]{fontenc}
18 | % Nicer default font (+ math font) than Computer Modern for most use cases
19 | \usepackage{mathpazo}
20 |
21 | % Basic figure setup, for now with no caption control since it's done
22 | % automatically by Pandoc (which extracts  syntax from Markdown).
23 | \usepackage{graphicx}
24 | % We will generate all images so they have a width \maxwidth. This means
25 | % that they will get their normal width if they fit onto the page, but
26 | % are scaled down if they would overflow the margins.
27 | \makeatletter
28 | \def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth
29 | \else\Gin@nat@width\fi}
30 | \makeatother
31 | \let\Oldincludegraphics\includegraphics
32 | % Set max figure width to be 80% of text width, for now hardcoded.
33 | \renewcommand{\includegraphics}[1]{\Oldincludegraphics[width=.8\maxwidth]{#1}}
34 | % Ensure that by default, figures have no caption (until we provide a
35 | % proper Figure object with a Caption API and a way to capture that
36 | % in the conversion process - todo).
37 | \usepackage{caption}
38 | \DeclareCaptionLabelFormat{nolabel}{}
39 | \captionsetup{labelformat=nolabel}
40 |
41 | \usepackage{adjustbox} % Used to constrain images to a maximum size
42 | \usepackage{xcolor} % Allow colors to be defined
43 | \usepackage{enumerate} % Needed for markdown enumerations to work
44 | \usepackage{geometry} % Used to adjust the document margins
45 | \usepackage{amsmath} % Equations
46 | \usepackage{amssymb} % Equations
47 | \usepackage{textcomp} % defines textquotesingle
48 | % Hack from http://tex.stackexchange.com/a/47451/13684:
49 | \AtBeginDocument{%
50 | \def\PYZsq{\textquotesingle}% Upright quotes in Pygmentized code
51 | }
52 | \usepackage{upquote} % Upright quotes for verbatim code
53 | \usepackage{eurosym} % defines \euro
54 | \usepackage[mathletters]{ucs} % Extended unicode (utf-8) support
55 | \usepackage[utf8x]{inputenc} % Allow utf-8 characters in the tex document
56 | \usepackage{fancyvrb} % verbatim replacement that allows latex
57 | \usepackage{grffile} % extends the file name processing of package graphics
58 | % to support a larger range
59 | % The hyperref package gives us a pdf with properly built
60 | % internal navigation ('pdf bookmarks' for the table of contents,
61 | % internal cross-reference links, web links for URLs, etc.)
62 | \usepackage{hyperref}
63 | \usepackage{longtable} % longtable support required by pandoc >1.10
64 | \usepackage{booktabs} % table support for pandoc > 1.12.2
65 | \usepackage[inline]{enumitem} % IRkernel/repr support (it uses the enumerate* environment)
66 | \usepackage[normalem]{ulem} % ulem is needed to support strikethroughs (\sout)
67 | % normalem makes italics be italics, not underlines
68 |
69 |
70 |
71 |
72 | % Colors for the hyperref package
73 | \definecolor{urlcolor}{rgb}{0,.145,.698}
74 | \definecolor{linkcolor}{rgb}{.71,0.21,0.01}
75 | \definecolor{citecolor}{rgb}{.12,.54,.11}
76 |
77 | % ANSI colors
78 | \definecolor{ansi-black}{HTML}{3E424D}
79 | \definecolor{ansi-black-intense}{HTML}{282C36}
80 | \definecolor{ansi-red}{HTML}{E75C58}
81 | \definecolor{ansi-red-intense}{HTML}{B22B31}
82 | \definecolor{ansi-green}{HTML}{00A250}
83 | \definecolor{ansi-green-intense}{HTML}{007427}
84 | \definecolor{ansi-yellow}{HTML}{DDB62B}
85 | \definecolor{ansi-yellow-intense}{HTML}{B27D12}
86 | \definecolor{ansi-blue}{HTML}{208FFB}
87 | \definecolor{ansi-blue-intense}{HTML}{0065CA}
88 | \definecolor{ansi-magenta}{HTML}{D160C4}
89 | \definecolor{ansi-magenta-intense}{HTML}{A03196}
90 | \definecolor{ansi-cyan}{HTML}{60C6C8}
91 | \definecolor{ansi-cyan-intense}{HTML}{258F8F}
92 | \definecolor{ansi-white}{HTML}{C5C1B4}
93 | \definecolor{ansi-white-intense}{HTML}{A1A6B2}
94 |
95 | % commands and environments needed by pandoc snippets
96 | % extracted from the output of `pandoc -s`
97 | \providecommand{\tightlist}{%
98 | \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
99 | \DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\{\}}
100 | % Add ',fontsize=\small' for more characters per line
101 | \newenvironment{Shaded}{}{}
102 | \newcommand{\KeywordTok}[1]{\textcolor[rgb]{0.00,0.44,0.13}{\textbf{{#1}}}}
103 | \newcommand{\DataTypeTok}[1]{\textcolor[rgb]{0.56,0.13,0.00}{{#1}}}
104 | \newcommand{\DecValTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{{#1}}}
105 | \newcommand{\BaseNTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{{#1}}}
106 | \newcommand{\FloatTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{{#1}}}
107 | \newcommand{\CharTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{{#1}}}
108 | \newcommand{\StringTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{{#1}}}
109 | \newcommand{\CommentTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textit{{#1}}}}
110 | \newcommand{\OtherTok}[1]{\textcolor[rgb]{0.00,0.44,0.13}{{#1}}}
111 | \newcommand{\AlertTok}[1]{\textcolor[rgb]{1.00,0.00,0.00}{\textbf{{#1}}}}
112 | \newcommand{\FunctionTok}[1]{\textcolor[rgb]{0.02,0.16,0.49}{{#1}}}
113 | \newcommand{\RegionMarkerTok}[1]{{#1}}
114 | \newcommand{\ErrorTok}[1]{\textcolor[rgb]{1.00,0.00,0.00}{\textbf{{#1}}}}
115 | \newcommand{\NormalTok}[1]{{#1}}
116 |
117 | % Additional commands for more recent versions of Pandoc
118 | \newcommand{\ConstantTok}[1]{\textcolor[rgb]{0.53,0.00,0.00}{{#1}}}
119 | \newcommand{\SpecialCharTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{{#1}}}
120 | \newcommand{\VerbatimStringTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{{#1}}}
121 | \newcommand{\SpecialStringTok}[1]{\textcolor[rgb]{0.73,0.40,0.53}{{#1}}}
122 | \newcommand{\ImportTok}[1]{{#1}}
123 | \newcommand{\DocumentationTok}[1]{\textcolor[rgb]{0.73,0.13,0.13}{\textit{{#1}}}}
124 | \newcommand{\AnnotationTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textbf{\textit{{#1}}}}}
125 | \newcommand{\CommentVarTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textbf{\textit{{#1}}}}}
126 | \newcommand{\VariableTok}[1]{\textcolor[rgb]{0.10,0.09,0.49}{{#1}}}
127 | \newcommand{\ControlFlowTok}[1]{\textcolor[rgb]{0.00,0.44,0.13}{\textbf{{#1}}}}
128 | \newcommand{\OperatorTok}[1]{\textcolor[rgb]{0.40,0.40,0.40}{{#1}}}
129 | \newcommand{\BuiltInTok}[1]{{#1}}
130 | \newcommand{\ExtensionTok}[1]{{#1}}
131 | \newcommand{\PreprocessorTok}[1]{\textcolor[rgb]{0.74,0.48,0.00}{{#1}}}
132 | \newcommand{\AttributeTok}[1]{\textcolor[rgb]{0.49,0.56,0.16}{{#1}}}
133 | \newcommand{\InformationTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textbf{\textit{{#1}}}}}
134 | \newcommand{\WarningTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textbf{\textit{{#1}}}}}
135 |
136 |
137 | % Define a nice break command that doesn't care if a line doesn't already
138 | % exist.
139 | \def\br{\hspace*{\fill} \\* }
140 | % Math Jax compatability definitions
141 | \def\gt{>}
142 | \def\lt{<}
143 | % Document parameters
144 | \title{1\_Introduction-to-Bayes}
145 |
146 |
147 |
148 |
149 | % Pygments definitions
150 |
151 | \makeatletter
152 | \def\PY@reset{\let\PY@it=\relax \let\PY@bf=\relax%
153 | \let\PY@ul=\relax \let\PY@tc=\relax%
154 | \let\PY@bc=\relax \let\PY@ff=\relax}
155 | \def\PY@tok#1{\csname PY@tok@#1\endcsname}
156 | \def\PY@toks#1+{\ifx\relax#1\empty\else%
157 | \PY@tok{#1}\expandafter\PY@toks\fi}
158 | \def\PY@do#1{\PY@bc{\PY@tc{\PY@ul{%
159 | \PY@it{\PY@bf{\PY@ff{#1}}}}}}}
160 | \def\PY#1#2{\PY@reset\PY@toks#1+\relax+\PY@do{#2}}
161 |
162 | \expandafter\def\csname PY@tok@w\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.73,0.73}{##1}}}
163 | \expandafter\def\csname PY@tok@c\endcsname{\let\PY@it=\textit\def\PY@tc##1{\textcolor[rgb]{0.25,0.50,0.50}{##1}}}
164 | \expandafter\def\csname PY@tok@cp\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.74,0.48,0.00}{##1}}}
165 | \expandafter\def\csname PY@tok@k\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
166 | \expandafter\def\csname PY@tok@kp\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
167 | \expandafter\def\csname PY@tok@kt\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.69,0.00,0.25}{##1}}}
168 | \expandafter\def\csname PY@tok@o\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
169 | \expandafter\def\csname PY@tok@ow\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.67,0.13,1.00}{##1}}}
170 | \expandafter\def\csname PY@tok@nb\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
171 | \expandafter\def\csname PY@tok@nf\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.00,0.00,1.00}{##1}}}
172 | \expandafter\def\csname PY@tok@nc\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.00,1.00}{##1}}}
173 | \expandafter\def\csname PY@tok@nn\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.00,1.00}{##1}}}
174 | \expandafter\def\csname PY@tok@ne\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.82,0.25,0.23}{##1}}}
175 | \expandafter\def\csname PY@tok@nv\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}}
176 | \expandafter\def\csname PY@tok@no\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.53,0.00,0.00}{##1}}}
177 | \expandafter\def\csname PY@tok@nl\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.63,0.63,0.00}{##1}}}
178 | \expandafter\def\csname PY@tok@ni\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.60,0.60,0.60}{##1}}}
179 | \expandafter\def\csname PY@tok@na\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.49,0.56,0.16}{##1}}}
180 | \expandafter\def\csname PY@tok@nt\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
181 | \expandafter\def\csname PY@tok@nd\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.67,0.13,1.00}{##1}}}
182 | \expandafter\def\csname PY@tok@s\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
183 | \expandafter\def\csname PY@tok@sd\endcsname{\let\PY@it=\textit\def\PY@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
184 | \expandafter\def\csname PY@tok@si\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.73,0.40,0.53}{##1}}}
185 | \expandafter\def\csname PY@tok@se\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.73,0.40,0.13}{##1}}}
186 | \expandafter\def\csname PY@tok@sr\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.40,0.53}{##1}}}
187 | \expandafter\def\csname PY@tok@ss\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}}
188 | \expandafter\def\csname PY@tok@sx\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
189 | \expandafter\def\csname PY@tok@m\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
190 | \expandafter\def\csname PY@tok@gh\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.00,0.50}{##1}}}
191 | \expandafter\def\csname PY@tok@gu\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.50,0.00,0.50}{##1}}}
192 | \expandafter\def\csname PY@tok@gd\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.63,0.00,0.00}{##1}}}
193 | \expandafter\def\csname PY@tok@gi\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.00,0.63,0.00}{##1}}}
194 | \expandafter\def\csname PY@tok@gr\endcsname{\def\PY@tc##1{\textcolor[rgb]{1.00,0.00,0.00}{##1}}}
195 | \expandafter\def\csname PY@tok@ge\endcsname{\let\PY@it=\textit}
196 | \expandafter\def\csname PY@tok@gs\endcsname{\let\PY@bf=\textbf}
197 | \expandafter\def\csname PY@tok@gp\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.00,0.50}{##1}}}
198 | \expandafter\def\csname PY@tok@go\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.53,0.53,0.53}{##1}}}
199 | \expandafter\def\csname PY@tok@gt\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.00,0.27,0.87}{##1}}}
200 | \expandafter\def\csname PY@tok@err\endcsname{\def\PY@bc##1{\setlength{\fboxsep}{0pt}\fcolorbox[rgb]{1.00,0.00,0.00}{1,1,1}{\strut ##1}}}
201 | \expandafter\def\csname PY@tok@kc\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
202 | \expandafter\def\csname PY@tok@kd\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
203 | \expandafter\def\csname PY@tok@kn\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
204 | \expandafter\def\csname PY@tok@kr\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
205 | \expandafter\def\csname PY@tok@bp\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
206 | \expandafter\def\csname PY@tok@fm\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.00,0.00,1.00}{##1}}}
207 | \expandafter\def\csname PY@tok@vc\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}}
208 | \expandafter\def\csname PY@tok@vg\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}}
209 | \expandafter\def\csname PY@tok@vi\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}}
210 | \expandafter\def\csname PY@tok@vm\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}}
211 | \expandafter\def\csname PY@tok@sa\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
212 | \expandafter\def\csname PY@tok@sb\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
213 | \expandafter\def\csname PY@tok@sc\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
214 | \expandafter\def\csname PY@tok@dl\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
215 | \expandafter\def\csname PY@tok@s2\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
216 | \expandafter\def\csname PY@tok@sh\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
217 | \expandafter\def\csname PY@tok@s1\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
218 | \expandafter\def\csname PY@tok@mb\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
219 | \expandafter\def\csname PY@tok@mf\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
220 | \expandafter\def\csname PY@tok@mh\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
221 | \expandafter\def\csname PY@tok@mi\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
222 | \expandafter\def\csname PY@tok@il\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
223 | \expandafter\def\csname PY@tok@mo\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
224 | \expandafter\def\csname PY@tok@ch\endcsname{\let\PY@it=\textit\def\PY@tc##1{\textcolor[rgb]{0.25,0.50,0.50}{##1}}}
225 | \expandafter\def\csname PY@tok@cm\endcsname{\let\PY@it=\textit\def\PY@tc##1{\textcolor[rgb]{0.25,0.50,0.50}{##1}}}
226 | \expandafter\def\csname PY@tok@cpf\endcsname{\let\PY@it=\textit\def\PY@tc##1{\textcolor[rgb]{0.25,0.50,0.50}{##1}}}
227 | \expandafter\def\csname PY@tok@c1\endcsname{\let\PY@it=\textit\def\PY@tc##1{\textcolor[rgb]{0.25,0.50,0.50}{##1}}}
228 | \expandafter\def\csname PY@tok@cs\endcsname{\let\PY@it=\textit\def\PY@tc##1{\textcolor[rgb]{0.25,0.50,0.50}{##1}}}
229 |
230 | \def\PYZbs{\char`\\}
231 | \def\PYZus{\char`\_}
232 | \def\PYZob{\char`\{}
233 | \def\PYZcb{\char`\}}
234 | \def\PYZca{\char`\^}
235 | \def\PYZam{\char`\&}
236 | \def\PYZlt{\char`\<}
237 | \def\PYZgt{\char`\>}
238 | \def\PYZsh{\char`\#}
239 | \def\PYZpc{\char`\%}
240 | \def\PYZdl{\char`\$}
241 | \def\PYZhy{\char`\-}
242 | \def\PYZsq{\char`\'}
243 | \def\PYZdq{\char`\"}
244 | \def\PYZti{\char`\~}
245 | % for compatibility with earlier versions
246 | \def\PYZat{@}
247 | \def\PYZlb{[}
248 | \def\PYZrb{]}
249 | \makeatother
250 |
251 |
252 | % Exact colors from NB
253 | \definecolor{incolor}{rgb}{0.0, 0.0, 0.5}
254 | \definecolor{outcolor}{rgb}{0.545, 0.0, 0.0}
255 |
256 |
257 |
258 |
259 | % Prevent overflowing lines due to hard-to-break entities
260 | \sloppy
261 | % Setup hyperref package
262 | \hypersetup{
263 | breaklinks=true, % so long urls are correctly broken across lines
264 | colorlinks=true,
265 | urlcolor=urlcolor,
266 | linkcolor=linkcolor,
267 | citecolor=citecolor,
268 | }
269 | % Slightly bigger margins than the latex defaults
270 |
271 | \geometry{verbose,tmargin=1in,bmargin=1in,lmargin=1in,rmargin=1in}
272 |
273 |
274 |
275 | \begin{document}
276 |
277 |
278 | \maketitle
279 |
280 |
281 |
282 |
283 | Table of Contents{}
284 |
285 | {{1~~}An Introduction to Bayesian Statistical Analysis}
286 |
287 | {{2~~}What is Bayesian Statistical Analysis?}
288 |
289 | {{3~~}What is Probability?}
290 |
291 | {{3.1~~}1. Classical probability}
292 |
293 | {{3.2~~}2. Frequentist probability}
294 |
295 | {{3.3~~}3. Subjective probability}
296 |
297 | {{4~~}Bayesian vs Frequentist Statistics: What's the difference?}
298 |
299 | {{4.1~~}The Frequentist World View}
300 |
301 | {{4.2~~}The Bayesian World View}
302 |
303 | {{5~~}Bayes' Formula}
304 |
305 | {{5.1~~}Example: Genetic probabilities}
306 |
307 | {{6~~}More on Bayesian Terminology}
308 |
309 | {{6.1~~}Marginal}
310 |
311 | {{6.2~~}Prior}
312 |
313 | {{6.3~~}Likelihood}
314 |
315 | {{6.4~~}Posterior}
316 |
317 | {{7~~}Why be Bayesian?}
318 |
319 | {{7.1~~}Example: confidence vs.~credible intervals}
320 |
321 | {{8~~}Bayesian Inference, in 3 Easy Steps}
322 |
323 | {{8.1~~}Step 1: Specify a probability model}
324 |
325 | {{8.2~~}Step 2: Calculate a posterior distribution}
326 |
327 | {{8.3~~}Step 3: Check your model}
328 |
329 | {{9~~}References}
330 |
331 | \hypertarget{an-introduction-to-bayesian-statistical-analysis}{%
332 | \subsection{An Introduction to Bayesian Statistical
333 | Analysis}\label{an-introduction-to-bayesian-statistical-analysis}}
334 |
335 | Before we jump in to model-building and using MCMC to do wonderful
336 | things, it is useful to understand a few of the theoretical
337 | underpinnings of the Bayesian statistical paradigm. A little theory (and
338 | I do mean a \emph{little}) goes a long way towards being able to apply
339 | the methods correctly and effectively.
340 |
341 | There are several introductory references to Bayesian statistics that go
342 | well beyond what we will cover here. Some suggestions:
343 |
344 | \href{https://www.kobo.com/us/en/ebook/schaum-s-outline-of-probability-and-statistics-4th-edition}{Chapter
345 | 11 of Schaum's Outline of Probability and Statistics}
346 |
347 | \href{https://www.stat.auckland.ac.nz/~brewer/stats331.pdf}{Introduction
348 | to Bayesian Statistics}
349 |
350 | \href{https://www.york.ac.uk/depts/maths/histstat/pml1/bayes/book.htm}{Bayesian
351 | Statistics}
352 |
353 | \hypertarget{what-is-bayesian-statistical-analysis}{%
354 | \subsection{\texorpdfstring{What \emph{is} Bayesian Statistical
355 | Analysis?}{What is Bayesian Statistical Analysis?}}\label{what-is-bayesian-statistical-analysis}}
356 |
357 | Though many of you will have taken a statistics course or two during
358 | your undergraduate (or graduate) education, most of those who have will
359 | likely not have had a course in \emph{Bayesian} statistics. Most
360 | introductory courses, particularly for non-statisticians, still do not
361 | cover Bayesian methods at all, except perhaps to derive Bayes' formula
362 | as a trivial rearrangement of the definition of conditional probability.
363 | Even today, Bayesian courses are typically tacked onto the curriculum,
364 | rather than being integrated into the program.
365 |
366 | In fact, Bayesian statistics is not just a particular method, or even a
367 | class of methods; it is an entirely different paradigm for doing
368 | statistical analysis.
369 |
370 | \begin{quote}
371 | Practical methods for making inferences from data using probability
372 | models for quantities we observe and about which we wish to learn.
373 | \emph{-- Gelman et al.~2013}
374 | \end{quote}
375 |
376 | A Bayesian model is described by parameters, uncertainty in those
377 | parameters is described using probability distributions.
378 |
379 | All conclusions from Bayesian statistical procedures are stated in terms
380 | of \emph{probability statements}
381 |
382 | \includegraphics{images/prob_model.png}
383 |
384 | This confers several benefits to the analyst, including:
385 |
386 | \begin{itemize}
387 | \tightlist
388 | \item
389 | ease of interpretation, summarization of uncertainty
390 | \item
391 | can incorporate uncertainty in parent parameters
392 | \item
393 | easy to calculate summary statistics
394 | \end{itemize}
395 |
396 | \hypertarget{what-is-probability}{%
397 | \subsection{What is Probability?}\label{what-is-probability}}
398 |
399 | \begin{quote}
400 | \emph{Misunderstanding of probability may be the greatest of all
401 | impediments to scientific literacy.} --- Stephen Jay Gould
402 | \end{quote}
403 |
404 | It is useful to start with defining what probability is. There are three
405 | main categories:
406 |
407 | \hypertarget{classical-probability}{%
408 | \subsubsection{1. Classical probability}\label{classical-probability}}
409 |
410 | \[Pr(X=x) = \frac{\text{# x outcomes}}{\text{# possible outcomes}}\]
411 |
412 | Classical probability is an assessment of \textbf{possible} outcomes of
413 | elementary events. Elementary events are assumed to be equally likely.
414 |
415 | \hypertarget{frequentist-probability}{%
416 | \subsubsection{2. Frequentist
417 | probability}\label{frequentist-probability}}
418 |
419 | \[Pr(X=x) = \lim_{n \rightarrow \infty} \frac{\text{# times x has occurred}}{\text{# independent and identical trials}}\]
420 |
421 | This interpretation considers probability to be the relative frequency
422 | ``in the long run'' of outcomes.
423 |
424 | \hypertarget{subjective-probability}{%
425 | \subsubsection{3. Subjective probability}\label{subjective-probability}}
426 |
427 | \[Pr(X=x)\]
428 |
429 | Subjective probability is a measure of one's uncertainty in the value of
430 | \(X\). It characterizes the state of knowledge regarding some unknown
431 | quantity using probability.
432 |
433 | It is not associated with long-term frequencies nor with
434 | equal-probability events.
435 |
436 | For example:
437 |
438 | \begin{itemize}
439 | \tightlist
440 | \item
441 | X = the true prevalence of diabetes in Austin is \textless{} 15\%
442 | \item
443 | X = the blood type of the person sitting next to you is type A
444 | \item
445 | X = the Nashville Predators will win next year's Stanley Cup
446 | \item
447 | X = it is raining in Nashville
448 | \end{itemize}
449 |
450 | \hypertarget{bayesian-vs-frequentist-statistics-whats-the-difference}{%
451 | \subsection{Bayesian vs Frequentist Statistics: What's the
452 | difference?}\label{bayesian-vs-frequentist-statistics-whats-the-difference}}
453 |
454 | See the
455 | \href{http://conference.scipy.org/proceedings/scipy2014/pdfs/vanderplas.pdf}{VanderPlas
456 | paper and video}.
457 |
458 | \begin{figure}
459 | \centering
460 | \includegraphics{images/can-of-worms.jpg}
461 | \caption{can of worms}
462 | \end{figure}
463 |
464 | Any statistical paradigm, Bayesian or otherwise, involves at least the
465 | following:
466 |
467 | \begin{enumerate}
468 | \def\labelenumi{\arabic{enumi}.}
469 | \tightlist
470 | \item
471 | Some \textbf{unknown quantities} about which we are interested in
472 | learning or testing. We call these \emph{parameters}.
473 | \item
474 | Some \textbf{data} which have been observed, and hopefully contain
475 | information about (1).
476 | \item
477 | One or more \textbf{models} that relate the data to the parameters,
478 | and is the instrument that is used to learn.
479 | \end{enumerate}
480 |
481 | \hypertarget{the-frequentist-world-view}{%
482 | \subsubsection{The Frequentist World
483 | View}\label{the-frequentist-world-view}}
484 |
485 | \begin{figure}
486 | \centering
487 | \includegraphics{images/fisher.png}
488 | \caption{Fisher}
489 | \end{figure}
490 |
491 | \begin{itemize}
492 | \tightlist
493 | \item
494 | The data that have been observed are considered \textbf{random},
495 | because they are realizations of random processes, and hence will vary
496 | each time one goes to observe the system.
497 | \item
498 | Model parameters are considered \textbf{fixed}. The parameters' values
499 | are unknown, but they are fixed, and so we \emph{condition} on them.
500 | \end{itemize}
501 |
502 | In mathematical notation, this implies a (very) general model of the
503 | following form:
504 |
505 | \[f(y | \theta)\]
506 |
507 | Here, the model \(f\) accepts data values \(y\) as an argument,
508 | conditional on particular values of \(\theta\).
509 |
510 | Frequentist inference typically involves deriving \textbf{estimators}
511 | for the unknown parameters. Estimators are formulae that return
512 | estimates for particular estimands, as a function of data. They are
513 | selected based on some chosen optimality criterion, such as
514 | \emph{unbiasedness}, \emph{variance minimization}, or \emph{efficiency}.
515 |
516 | \begin{quote}
517 | For example, lets say that we have collected some data on the prevalence
518 | of autism spectrum disorder (ASD) in some defined population. Our sample
519 | includes \(n\) sampled children, \(y\) of them having been diagnosed
520 | with autism. A frequentist estimator of the prevalence \(p\) is:
521 | \end{quote}
522 |
523 | \begin{quote}
524 | \[\hat{p} = \frac{y}{n}\]
525 | \end{quote}
526 |
527 | \begin{quote}
528 | Why this particular function? Because it can be shown to be unbiased and
529 | minimum-variance.
530 | \end{quote}
531 |
532 | It is important to note that new estimators need to be derived for every
533 | estimand that is introduced.
534 |
535 | \hypertarget{the-bayesian-world-view}{%
536 | \subsubsection{The Bayesian World View}\label{the-bayesian-world-view}}
537 |
538 | \begin{figure}
539 | \centering
540 | \includegraphics{images/bayes.png}
541 | \caption{Bayes}
542 | \end{figure}
543 |
544 | \begin{itemize}
545 | \tightlist
546 | \item
547 | Data are considered \textbf{fixed}. They used to be random, but once
548 | they were written into your lab notebook/spreadsheet/IPython notebook
549 | they do not change.
550 | \item
551 | Model parameters themselves may not be random, but Bayesians use
552 | probability distribtutions to describe their uncertainty in parameter
553 | values, and are therefore treated as \textbf{random}. In some cases,
554 | it is useful to consider parameters as having been sampled from
555 | probability distributions.
556 | \end{itemize}
557 |
558 | This implies the following form:
559 |
560 | \[p(\theta | y)\]
561 |
562 | This formulation used to be referred to as \textbf{\emph{inverse
563 | probability}}, because it infers from observations to parameters, or
564 | from effects to causes.
565 |
566 | Bayesians do not seek new estimators for every estimation problem they
567 | encounter. There is only one estimator for Bayesian inference:
568 | \textbf{Bayes' Formula}.
569 |
570 | \hypertarget{bayes-formula}{%
571 | \subsection{Bayes' Formula}\label{bayes-formula}}
572 |
573 | Given two events A and B, the conditional probability of A given that B
574 | is true is expressed as follows:
575 |
576 | \[Pr(A|B) = \frac{Pr(B|A)Pr(A)}{Pr(B)}\]
577 |
578 | where P(B)\textgreater{}0. Although Bayes' theorem is a fundamental
579 | result of probability theory, it has a specific interpretation in
580 | Bayesian statistics.
581 |
582 | In the above equation, A usually represents a proposition (such as the
583 | statement that a coin lands on heads fifty percent of the time) and B
584 | represents the evidence, or new data that is to be taken into account
585 | (such as the result of a series of coin flips). P(A) is the
586 | \textbf{prior} probability of A which expresses one's beliefs about A
587 | before evidence is taken into account. The prior probability may also
588 | quantify prior knowledge or information about A.
589 |
590 | P(B\textbar{}A) is the \textbf{likelihood}, which can be interpreted as
591 | the probability of the evidence B given that A is true. The likelihood
592 | quantifies the extent to which the evidence B supports the proposition
593 | A.
594 |
595 | P(A\textbar{}B) is the \textbf{posterior} probability, the probability
596 | of the proposition A after taking the evidence B into account.
597 | Essentially, Bayes' theorem updates one's prior beliefs P(A) after
598 | considering the new evidence B.
599 |
600 | P(B) is the \textbf{marginal likelihood}, which can be interpreted as
601 | the sum of the conditional probability of B under all possible events
602 | \$A\_i\# in the sample space
603 |
604 | \begin{itemize}
605 | \tightlist
606 | \item
607 | For two events \(P(B) = P(B|A)P(A) + P(B|\bar{A})P(\bar{A})\)
608 | \end{itemize}
609 |
610 | \hypertarget{example-genetic-probabilities}{%
611 | \subsubsection{Example: Genetic
612 | probabilities}\label{example-genetic-probabilities}}
613 |
614 | Let's put Bayesian inference into action using a very simple example.
615 | I've chosen this example because it is one of the rare occasions where
616 | the posterior can be calculated by hand. We will show how data can be
617 | used to update our belief in competing hypotheses.
618 |
619 | Hemophilia is a rare genetic disorder that impairs the ability for the
620 | body's clotting factors to coagualate the blood in response to broken
621 | blood vessels. The disease is an \textbf{x-linked recessive} trait,
622 | meaning that there is only one copy of the gene in males but two in
623 | females, and the trait can be masked by the dominant allele of the gene.
624 |
625 | This implies that males with 1 gene are \emph{affected}, while females
626 | with 1 gene are unaffected, but \emph{carriers} of the disease. Having 2
627 | copies of the disease is fatal, so this genotype does not exist in the
628 | population.
629 |
630 | In this example, consider a woman whose mother is a carrier (because her
631 | brother is affected) and who marries an unaffected man. Let's now
632 | observe some data: the woman has two consecutive (non-twin) sons who are
633 | unaffected. We are interested in determining \textbf{if the woman is a
634 | carrier}.
635 |
636 | \begin{figure}
637 | \centering
638 | \includegraphics{images/hemophilia.png}
639 | \caption{hemophilia}
640 | \end{figure}
641 |
642 | To set up this problem, we need to set up our probability model. The
643 | unknown quantity of interest is simply an indicator variable \(W\) that
644 | equals 1 if the woman is affected, and zero if she is not. We are
645 | interested in the probability that the variable equals one, given what
646 | we have observed:
647 |
648 | \[Pr(W=1 | s_1=0, s_2=0)\]
649 |
650 | Our prior information is based on what we know about the woman's
651 | ancestry: her mother was a carrier. Hence, the prior is
652 | \(Pr(W=1) = 0.5\). Another way of expressing this is in terms of the
653 | \textbf{prior odds}, or:
654 |
655 | \[O(W=1) = \frac{Pr(W=1)}{Pr(W=0)} = 1\]
656 |
657 | Now for the likelihood: The form of this function is:
658 |
659 | \[L(W | s_1=0, s_2=0)\]
660 |
661 | This can be calculated as the probability of observing the data for any
662 | passed value for the parameter. For this simple problem, the likelihood
663 | takes only two possible values:
664 |
665 | \[\begin{aligned}
666 | L(W=1 &| s_1=0, s_2=0) = (0.5)(0.5) = 0.25 \cr
667 | L(W=0 &| s_1=0, s_2=0) = (1)(1) = 1
668 | \end{aligned}\]
669 |
670 | With all the pieces in place, we can now apply Bayes' formula to
671 | calculate the posterior probability that the woman is a carrier:
672 |
673 | \[\begin{aligned}
674 | Pr(W=1 | s_1=0, s_2=0) &= \frac{L(W=1 | s_1=0, s_2=0) Pr(W=1)}{L(W=1 | s_1=0, s_2=0) Pr(W=1) + L(W=0 | s_1=0, s_2=0) Pr(W=0)} \cr
675 | &= \frac{(0.25)(0.5)}{(0.25)(0.5) + (1)(0.5)} \cr
676 | &= 0.2
677 | \end{aligned}\]
678 |
679 | Hence, there is a 0.2 probability of the woman being a carrier.
680 |
681 | Its a bit trivial, but we can code this in Python:
682 |
683 | \begin{Verbatim}[commandchars=\\\{\}]
684 | {\color{incolor}In [{\color{incolor}13}]:} \PY{n}{prior} \PY{o}{=} \PY{l+m+mf}{0.5}
685 | \PY{n}{p} \PY{o}{=} \PY{l+m+mf}{0.5}
686 |
687 | \PY{n}{L} \PY{o}{=} \PY{k}{lambda} \PY{n}{w}\PY{p}{,} \PY{n}{s}\PY{p}{:} \PY{n}{np}\PY{o}{.}\PY{n}{prod}\PY{p}{(}\PY{p}{[}\PY{p}{(}\PY{l+m+mi}{1}\PY{o}{\PYZhy{}}\PY{n}{i}\PY{p}{,} \PY{n}{p}\PY{o}{*}\PY{o}{*}\PY{n}{i} \PY{o}{*} \PY{p}{(}\PY{l+m+mi}{1}\PY{o}{\PYZhy{}}\PY{n}{p}\PY{p}{)}\PY{o}{*}\PY{o}{*}\PY{p}{(}\PY{l+m+mi}{1}\PY{o}{\PYZhy{}}\PY{n}{i}\PY{p}{)}\PY{p}{)}\PY{p}{[}\PY{n}{w}\PY{p}{]} \PY{k}{for} \PY{n}{i} \PY{o+ow}{in} \PY{n}{s}\PY{p}{]}\PY{p}{)}
688 | \end{Verbatim}
689 |
690 |
691 | \begin{Verbatim}[commandchars=\\\{\}]
692 | {\color{incolor}In [{\color{incolor}14}]:} \PY{n}{s} \PY{o}{=} \PY{p}{[}\PY{l+m+mi}{0}\PY{p}{,}\PY{l+m+mi}{0}\PY{p}{]}
693 |
694 | \PY{n}{post} \PY{o}{=} \PY{n}{L}\PY{p}{(}\PY{l+m+mi}{1}\PY{p}{,} \PY{n}{s}\PY{p}{)} \PY{o}{*} \PY{n}{prior} \PY{o}{/} \PY{p}{(}\PY{n}{L}\PY{p}{(}\PY{l+m+mi}{1}\PY{p}{,} \PY{n}{s}\PY{p}{)} \PY{o}{*} \PY{n}{prior} \PY{o}{+} \PY{n}{L}\PY{p}{(}\PY{l+m+mi}{0}\PY{p}{,} \PY{n}{s}\PY{p}{)} \PY{o}{*} \PY{p}{(}\PY{l+m+mi}{1} \PY{o}{\PYZhy{}} \PY{n}{prior}\PY{p}{)}\PY{p}{)}
695 | \PY{n}{post}
696 | \end{Verbatim}
697 |
698 |
699 | \begin{Verbatim}[commandchars=\\\{\}]
700 | {\color{outcolor}Out[{\color{outcolor}14}]:} 0.2
701 | \end{Verbatim}
702 |
703 | Now, what happens if the woman has a third unaffected child? What is our
704 | estimate of her probability of being a carrier then?
705 |
706 | Bayes' formula makes it easy to update analyses with new information, in
707 | a sequential fashion. We simply assign the posterior from the previous
708 | analysis to be the prior for the new analysis, and proceed as before:
709 |
710 | \begin{Verbatim}[commandchars=\\\{\}]
711 | {\color{incolor}In [{\color{incolor}15}]:} \PY{n}{L}\PY{p}{(}\PY{l+m+mi}{1}\PY{p}{,} \PY{p}{[}\PY{l+m+mi}{0}\PY{p}{]}\PY{p}{)}
712 | \end{Verbatim}
713 |
714 |
715 | \begin{Verbatim}[commandchars=\\\{\}]
716 | {\color{outcolor}Out[{\color{outcolor}15}]:} 0.5
717 | \end{Verbatim}
718 |
719 | \begin{Verbatim}[commandchars=\\\{\}]
720 | {\color{incolor}In [{\color{incolor}16}]:} \PY{n}{s} \PY{o}{=} \PY{p}{[}\PY{l+m+mi}{0}\PY{p}{]}
721 | \PY{n}{prior} \PY{o}{=} \PY{n}{post}
722 |
723 | \PY{n}{L}\PY{p}{(}\PY{l+m+mi}{1}\PY{p}{,} \PY{n}{s}\PY{p}{)} \PY{o}{*} \PY{n}{prior} \PY{o}{/} \PY{p}{(}\PY{n}{L}\PY{p}{(}\PY{l+m+mi}{1}\PY{p}{,} \PY{n}{s}\PY{p}{)} \PY{o}{*} \PY{n}{prior} \PY{o}{+} \PY{n}{L}\PY{p}{(}\PY{l+m+mi}{0}\PY{p}{,} \PY{n}{s}\PY{p}{)} \PY{o}{*} \PY{p}{(}\PY{l+m+mi}{1} \PY{o}{\PYZhy{}} \PY{n}{prior}\PY{p}{)}\PY{p}{)}
724 | \end{Verbatim}
725 |
726 |
727 | \begin{Verbatim}[commandchars=\\\{\}]
728 | {\color{outcolor}Out[{\color{outcolor}16}]:} 0.11111111111111112
729 | \end{Verbatim}
730 |
731 | Thus, observing a third unaffected child has further reduced our belief
732 | that the mother is a carrier.
733 |
734 | \hypertarget{more-on-bayesian-terminology}{%
735 | \subsection{More on Bayesian
736 | Terminology}\label{more-on-bayesian-terminology}}
737 |
738 | Replacing Bayes' Formula with conventional Bayes terms:
739 |
740 | \begin{figure}
741 | \centering
742 | \includegraphics{images/bayes_formula.png}
743 | \caption{bayes formula}
744 | \end{figure}
745 |
746 | The equation expresses how our belief about the value of \(\theta\), as
747 | expressed by the \textbf{prior distribution} \(P(\theta)\) is
748 | reallocated following the observation of the data \(y\), as expressed by
749 | the posterior distribution the posterior distribution.
750 |
751 | \hypertarget{marginal}{%
752 | \subsubsection{Marginal}\label{marginal}}
753 |
754 | The denominator \(P(y)\) is the likelihood integrated over all
755 | \(\theta\):
756 |
757 | \[Pr(\theta|y) = \frac{Pr(y|\theta)Pr(\theta)}{\int Pr(y|\theta)Pr(\theta) d\theta}\]
758 |
759 | This usually cannot be calculated directly. However it is just a
760 | normalization constant which doesn't depend on the parameter; the act of
761 | summation washes out whatever info we had about the parameter. Hence it
762 | can often be ignored;The normalising constant makes sure that the
763 | resulting posterior distribution is a true probability distribution by
764 | ensuring that the sum of the distribution is equal to 1.
765 |
766 | In some cases we don't care about this property of the distribution. We
767 | only care about where the peak of the distribution occurs, regardless of
768 | whether the distribution is normalised or not
769 |
770 | Unfortunately sometimes we are obliged to calculate it. The
771 | intractability of this integral is one of the factors that has
772 | contributed to the under-utilization of Bayesian methods by
773 | statisticians.
774 |
775 | \hypertarget{prior}{%
776 | \subsubsection{Prior}\label{prior}}
777 |
778 | Once considered a controversial aspect of Bayesian analysis, the prior
779 | distribution characterizes what is known about an unknown quantity
780 | before observing the data from the present study. Thus, it represents
781 | the information state of that parameter. It can be used to reflect the
782 | information obtained in previous studies, to constrain the parameter to
783 | plausible values, or to represent the population of possible parameter
784 | values, of which the current study's parameter value can be considered a
785 | sample.
786 |
787 | \hypertarget{likelihood}{%
788 | \subsubsection{Likelihood}\label{likelihood}}
789 |
790 | The likelihood represents the information in the observed data, and is
791 | used to update prior distributions to posterior distributions. This
792 | updating of belief is justified becuase of the \textbf{likelihood
793 | principle}, which states:
794 |
795 | \begin{quote}
796 | Following observation of \(y\), the likelihood \(L(\theta|y)\) contains
797 | all experimental information from \(y\) about the unknown \(\theta\).
798 | \end{quote}
799 |
800 | Bayesian analysis satisfies the likelihood principle because the
801 | posterior distribution's dependence on the data is only through the
802 | likelihood. In comparison, most frequentist inference procedures violate
803 | the likelihood principle, because inference will depend on the design of
804 | the trial or experiment.
805 |
806 | What is a likelihood function? It is closely related to the probability
807 | density (or mass) function. Taking a common example, consider some data
808 | that are binomially distributed (that is, they describe the outcomes of
809 | \(n\) binary events). Here is the binomial sampling distribution:
810 |
811 | \[p(Y|\theta) = {n \choose y} \theta^{y} (1-\theta)^{n-y}\]
812 |
813 | We can code this easily in Python:
814 |
815 | \begin{Verbatim}[commandchars=\\\{\}]
816 | {\color{incolor}In [{\color{incolor}8}]:} \PY{k+kn}{from} \PY{n+nn}{scipy}\PY{n+nn}{.}\PY{n+nn}{special} \PY{k}{import} \PY{n}{comb}
817 |
818 | \PY{n}{pbinom} \PY{o}{=} \PY{k}{lambda} \PY{n}{y}\PY{p}{,} \PY{n}{n}\PY{p}{,} \PY{n}{p}\PY{p}{:} \PY{n}{comb}\PY{p}{(}\PY{n}{n}\PY{p}{,} \PY{n}{y}\PY{p}{)} \PY{o}{*} \PY{n}{p}\PY{o}{*}\PY{o}{*}\PY{n}{y} \PY{o}{*} \PY{p}{(}\PY{l+m+mi}{1}\PY{o}{\PYZhy{}}\PY{n}{p}\PY{p}{)}\PY{o}{*}\PY{o}{*}\PY{p}{(}\PY{n}{n}\PY{o}{\PYZhy{}}\PY{n}{y}\PY{p}{)}
819 | \end{Verbatim}
820 |
821 |
822 | This function returns the probability of observing \(y\) events from
823 | \(n\) trials, where events occur independently with probability \(p\).
824 |
825 | \begin{Verbatim}[commandchars=\\\{\}]
826 | {\color{incolor}In [{\color{incolor}9}]:} \PY{n}{pbinom}\PY{p}{(}\PY{l+m+mi}{3}\PY{p}{,} \PY{l+m+mi}{10}\PY{p}{,} \PY{l+m+mf}{0.5}\PY{p}{)}
827 | \end{Verbatim}
828 |
829 |
830 | \begin{Verbatim}[commandchars=\\\{\}]
831 | {\color{outcolor}Out[{\color{outcolor}9}]:} 0.1171875
832 | \end{Verbatim}
833 |
834 | \begin{Verbatim}[commandchars=\\\{\}]
835 | {\color{incolor}In [{\color{incolor}10}]:} \PY{n}{pbinom}\PY{p}{(}\PY{l+m+mi}{1}\PY{p}{,} \PY{l+m+mi}{25}\PY{p}{,} \PY{l+m+mf}{0.5}\PY{p}{)}
836 | \end{Verbatim}
837 |
838 |
839 | \begin{Verbatim}[commandchars=\\\{\}]
840 | {\color{outcolor}Out[{\color{outcolor}10}]:} 7.450580596923828e-07
841 | \end{Verbatim}
842 |
843 | \begin{Verbatim}[commandchars=\\\{\}]
844 | {\color{incolor}In [{\color{incolor}11}]:} \PY{n}{yvals} \PY{o}{=} \PY{n+nb}{range}\PY{p}{(}\PY{l+m+mi}{10}\PY{o}{+}\PY{l+m+mi}{1}\PY{p}{)}
845 | \PY{n}{plt}\PY{o}{.}\PY{n}{plot}\PY{p}{(}\PY{n}{yvals}\PY{p}{,} \PY{p}{[}\PY{n}{pbinom}\PY{p}{(}\PY{n}{y}\PY{p}{,} \PY{l+m+mi}{10}\PY{p}{,} \PY{l+m+mf}{0.5}\PY{p}{)} \PY{k}{for} \PY{n}{y} \PY{o+ow}{in} \PY{n}{yvals}\PY{p}{]}\PY{p}{,} \PY{l+s+s1}{\PYZsq{}}\PY{l+s+s1}{ro}\PY{l+s+s1}{\PYZsq{}}\PY{p}{)}\PY{p}{;}
846 | \end{Verbatim}
847 |
848 |
849 | \begin{center}
850 | \adjustimage{max size={0.9\linewidth}{0.9\paperheight}}{output_20_0.png}
851 | \end{center}
852 | { \hspace*{\fill} \\}
853 |
854 | What about the likelihood function?
855 |
856 | The likelihood function is the exact same form as the sampling
857 | distribution, except that we are now interested in varying the parameter
858 | for a given dataset.
859 |
860 | \begin{Verbatim}[commandchars=\\\{\}]
861 | {\color{incolor}In [{\color{incolor}12}]:} \PY{n}{pvals} \PY{o}{=} \PY{n}{np}\PY{o}{.}\PY{n}{linspace}\PY{p}{(}\PY{l+m+mi}{0}\PY{p}{,} \PY{l+m+mi}{1}\PY{p}{)}
862 | \PY{n}{y} \PY{o}{=} \PY{l+m+mi}{4}
863 | \PY{n}{plt}\PY{o}{.}\PY{n}{plot}\PY{p}{(}\PY{n}{pvals}\PY{p}{,} \PY{p}{[}\PY{n}{pbinom}\PY{p}{(}\PY{n}{y}\PY{p}{,} \PY{l+m+mi}{10}\PY{p}{,} \PY{n}{p}\PY{p}{)} \PY{k}{for} \PY{n}{p} \PY{o+ow}{in} \PY{n}{pvals}\PY{p}{]}\PY{p}{)}\PY{p}{;}
864 | \end{Verbatim}
865 |
866 |
867 | \begin{center}
868 | \adjustimage{max size={0.9\linewidth}{0.9\paperheight}}{output_22_0.png}
869 | \end{center}
870 | { \hspace*{\fill} \\}
871 |
872 | So, though we are dealing with the same equation, these are entirely
873 | different functions; the distribution is discrete, while the likelihood
874 | is continuous; the distribtion's range is from 0 to 10, while the
875 | likelihood's is 0 to 1; the distribution integrates (sums) to one, while
876 | the likelhood does not.
877 |
878 | \hypertarget{posterior}{%
879 | \subsubsection{Posterior}\label{posterior}}
880 |
881 | The mathematical form \(p(\theta | y)\) that we associated with the
882 | Bayesian approach is referred to as a \textbf{posterior distribution}.
883 |
884 | \begin{quote}
885 | posterior /pos·ter·i·or/ (pos-tēr´e-er) later in time; subsequent.
886 | \end{quote}
887 |
888 | Why posterior? Because it tells us what we know about the unknown
889 | \(\theta\) \emph{after} having observed \(y\).
890 |
891 | \hypertarget{why-be-bayesian}{%
892 | \subsection{Why be Bayesian?}\label{why-be-bayesian}}
893 |
894 | At this point, it is worth addressing the question of why one might
895 | consider an alternative statistical paradigm to the
896 | classical/frequentist statistical approach. After all, it is not always
897 | easy to specify a full probabilistic model, nor to obtain output from
898 | the model once it is specified. So, why bother?
899 |
900 | \begin{quote}
901 | \ldots{} the Bayesian approach is attractive because it is useful. Its
902 | usefulness derives in large measure from its simplicity. Its simplicity
903 | allows the investigation of far more complex models than can be handled
904 | by the tools in the classical toolbox.\\
905 | \emph{-- Link and Barker 2010}
906 | \end{quote}
907 |
908 | We already noted that there is just one estimator in Bayesian inference,
909 | which lends to its \textbf{\emph{simplicity}}. Moreover, Bayes affords a
910 | conceptually simple way of coping with multiple parameters; the use of
911 | probabilistic models allows very complex models to be assembled in a
912 | modular fashion, by factoring a large joint model into the product of
913 | several conditional probabilities.
914 |
915 | Bayesian statistics is also attractive for its
916 | \textbf{\emph{coherence}}. All unknown quantities for a particular
917 | problem are treated as random variables, to be estimated in the same
918 | way. Existing knowledge is given precise mathematical expression,
919 | allowing it to be integrated with information from the study dataset,
920 | and there is formal mechanism for incorporating new information into an
921 | existing analysis.
922 |
923 | Finally, Bayesian statistics confers an advantage in the
924 | \textbf{\emph{interpretability}} of analytic outputs. Because models are
925 | expressed probabilistically, results can be interpreted
926 | probabilistically. Probabilities are easy for users (particularly
927 | non-technical users) to understand and apply.
928 |
929 | \hypertarget{example-confidence-vs.credible-intervals}{%
930 | \subsubsection{Example: confidence vs.~credible
931 | intervals}\label{example-confidence-vs.credible-intervals}}
932 |
933 | A commonly-used measure of uncertainty for a statistical point estimate
934 | in classical statistics is the \textbf{\emph{confidence interval}}. Most
935 | scientists were introduced to the confidence interval during their
936 | introductory statistics course(s) in college. Yet, a large number of
937 | users mis-interpret the confidence interval.
938 |
939 | Here is the mathematical definition of a 95\% confidence interval for
940 | some unknown scalar quantity that we will here call \(\theta\):
941 |
942 | \[Pr(a(Y) < \theta < b(Y) | \theta) = 0.95\]
943 |
944 | how the endpoints of this interval are calculated varies according to
945 | the sampling distribution of \(Y\), but for as an example, the
946 | confidence interval for the population mean when \(Y\) is normally
947 | distributed is calculated by:
948 |
949 | \[Pr(\bar{Y} - 1.96\frac{\sigma}{\sqrt{n}}< \theta < \bar{Y} + 1.96\frac{\sigma}{\sqrt{n}}) = 0.95\]
950 |
951 | It would be tempting to use this definition to conclude that there is a
952 | 95\% chance \(\theta\) is between \(a(Y)\) and \(b(Y)\), but that would
953 | be a mistake.
954 |
955 | Recall that for frequentists, unknown parameters are \textbf{fixed},
956 | which means there is no probability associated with them being any value
957 | except what they are fixed to. Here, the interval itself, and not
958 | \(\theta\) is the random variable. The actual interval calculated from
959 | the data is just one possible realization of a random process, and it
960 | must be strictly interpreted only in relation to an infinite sequence of
961 | identical trials that might be (but never are) conducted in practice.
962 |
963 | A valid interpretation of the above would be:
964 |
965 | \begin{quote}
966 | If the experiment were repeated an infinite number of times, 95\% of the
967 | calculated intervals would contain \(\theta\).
968 | \end{quote}
969 |
970 | This is what the statistical notion of ``confidence'' entails, and this
971 | sets it apart from probability intervals.
972 |
973 | Since they regard unknown parameters as random variables, Bayesians can
974 | and do use probability intervals to describe what is known about the
975 | value of an unknown quantity. These intervals are commonly known as
976 | \textbf{\emph{credible intervals}}.
977 |
978 | The definition of a 95\% credible interval is:
979 |
980 | \[Pr(a(y) < \theta < b(y) | Y=y) = 0.95\]
981 |
982 | Notice that we condition here on the data \(y\) instead of the unknown
983 | \(\theta\). Thus, the endpoints are fixed and the variable is random.
984 |
985 | We are allowed to interpret this interval as:
986 |
987 | \begin{quote}
988 | There is a 95\% chance \(\theta\) is between \(a\) and \(b\).
989 | \end{quote}
990 |
991 | Hence, the credible interval is a statement of what we know about the
992 | value of \(\theta\) based on the observed data.
993 |
994 | \hypertarget{bayesian-inference-in-3-easy-steps}{%
995 | \subsection{Bayesian Inference, in 3 Easy
996 | Steps}\label{bayesian-inference-in-3-easy-steps}}
997 |
998 | We are now ready (and willing!) to apply Bayesian methods to our
999 | problem. Gelman et al. (2013) describe the process of conducting
1000 | Bayesian statistical analysis in 3 steps:
1001 |
1002 | \begin{figure}
1003 | \centering
1004 | \includegraphics{images/123.png}
1005 | \caption{123}
1006 | \end{figure}
1007 |
1008 | \hypertarget{step-1-specify-a-probability-model}{%
1009 | \subsubsection{Step 1: Specify a probability
1010 | model}\label{step-1-specify-a-probability-model}}
1011 |
1012 | As was noted above, Bayesian statistics involves using probability
1013 | models to solve problems. So, the first task is to \emph{completely
1014 | specify} the model in terms of probability distributions. This includes
1015 | everything: unknown parameters, data, covariates, missing data,
1016 | predictions. All must be assigned some probability density.
1017 |
1018 | This step involves making choices.
1019 |
1020 | \begin{itemize}
1021 | \tightlist
1022 | \item
1023 | what is the form of the sampling distribution of the data?
1024 | \item
1025 | what form best describes our uncertainty in the unknown parameters?
1026 | \end{itemize}
1027 |
1028 | \hypertarget{step-2-calculate-a-posterior-distribution}{%
1029 | \subsubsection{Step 2: Calculate a posterior
1030 | distribution}\label{step-2-calculate-a-posterior-distribution}}
1031 |
1032 | The posterior distribution is formulated as a function of the
1033 | probability model that was specified in Step 1. Usually, we can write it
1034 | down but we cannot calculate it analytically. In fact, the difficulty
1035 | inherent in calculating the posterior distribution for most models of
1036 | interest is perhaps the major contributing factor for the lack of
1037 | widespread adoption of Bayesian methods for data analysis.
1038 |
1039 | \textbf{But}, once the posterior distribution is calculated, you get a
1040 | lot for free:
1041 |
1042 | \begin{itemize}
1043 | \tightlist
1044 | \item
1045 | point estimates
1046 | \item
1047 | credible intervals
1048 | \item
1049 | quantiles
1050 | \item
1051 | predictions
1052 | \end{itemize}
1053 |
1054 | \hypertarget{step-3-check-your-model}{%
1055 | \subsubsection{Step 3: Check your model}\label{step-3-check-your-model}}
1056 |
1057 | Though frequently ignored in practice, it is critical that the model and
1058 | its outputs be assessed before using the outputs for inference. Models
1059 | are specified based on assumptions that are largely unverifiable, so the
1060 | least we can do is examine the output in detail, relative to the
1061 | specified model and the data that were used to fit the model.
1062 |
1063 | Specifically, we must ask:
1064 |
1065 | \begin{itemize}
1066 | \tightlist
1067 | \item
1068 | does the model fit data?
1069 | \item
1070 | are the conclusions reasonable?
1071 | \item
1072 | are the outputs sensitive to changes in model structure?
1073 | \end{itemize}
1074 |
1075 | \begin{center}\rule{0.5\linewidth}{\linethickness}\end{center}
1076 |
1077 | \hypertarget{references}{%
1078 | \subsection{References}\label{references}}
1079 |
1080 | Gelman A, Carlin JB, Stern HS, Dunson DB, Vehtari A, Rubin DB. Bayesian
1081 | Data Analysis, Third Edition. CRC Press; 2013.
1082 |
1083 | \begin{Verbatim}[commandchars=\\\{\}]
1084 | {\color{incolor}In [{\color{incolor}17}]:} \PY{k+kn}{from} \PY{n+nn}{IPython}\PY{n+nn}{.}\PY{n+nn}{core}\PY{n+nn}{.}\PY{n+nn}{display} \PY{k}{import} \PY{n}{HTML}
1085 | \PY{k}{def} \PY{n+nf}{css\PYZus{}styling}\PY{p}{(}\PY{p}{)}\PY{p}{:}
1086 | \PY{n}{styles} \PY{o}{=} \PY{n+nb}{open}\PY{p}{(}\PY{l+s+s2}{\PYZdq{}}\PY{l+s+s2}{styles/custom.css}\PY{l+s+s2}{\PYZdq{}}\PY{p}{,} \PY{l+s+s2}{\PYZdq{}}\PY{l+s+s2}{r}\PY{l+s+s2}{\PYZdq{}}\PY{p}{)}\PY{o}{.}\PY{n}{read}\PY{p}{(}\PY{p}{)}
1087 | \PY{k}{return} \PY{n}{HTML}\PY{p}{(}\PY{n}{styles}\PY{p}{)}
1088 | \PY{n}{css\PYZus{}styling}\PY{p}{(}\PY{p}{)}
1089 | \end{Verbatim}
1090 |
1091 |
1092 | \begin{Verbatim}[commandchars=\\\{\}]
1093 | {\color{outcolor}Out[{\color{outcolor}17}]:}
1094 | \end{Verbatim}
1095 |
1096 |
1097 | % Add a bibliography block to the postdoc
1098 |
1099 |
1100 |
1101 | \end{document}
1102 |
--------------------------------------------------------------------------------
/styles/bmh_matplotlibrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "lines.linewidth": 2.0,
3 | "examples.download": true,
4 | "axes.edgecolor": "#bcbcbc",
5 | "patch.linewidth": 0.5,
6 | "legend.fancybox": true,
7 | "axes.color_cycle": [
8 | "#348ABD",
9 | "#A60628",
10 | "#7A68A6",
11 | "#467821",
12 | "#CF4457",
13 | "#188487",
14 | "#E24A33"
15 | ],
16 | "axes.facecolor": "#eeeeee",
17 | "axes.labelsize": "large",
18 | "axes.grid": true,
19 | "patch.edgecolor": "#eeeeee",
20 | "axes.titlesize": "x-large",
21 | "svg.embed_char_paths": "path",
22 | "examples.directory": ""
23 | }
24 |
--------------------------------------------------------------------------------
/styles/custom.css:
--------------------------------------------------------------------------------
1 |
53 |
68 |
--------------------------------------------------------------------------------
/styles/matplotlibrc:
--------------------------------------------------------------------------------
1 | ### MATPLOTLIBRC FORMAT
2 |
3 | # This is a sample matplotlib configuration file - you can find a copy
4 | # of it on your system in
5 | # site-packages/matplotlib/mpl-data/matplotlibrc. If you edit it
6 | # there, please note that it will be overwritten in your next install.
7 | # If you want to keep a permanent local copy that will not be
8 | # overwritten, place it in HOME/.matplotlib/matplotlibrc (unix/linux
9 | # like systems) and C:\Documents and Settings\yourname\.matplotlib
10 | # (win32 systems).
11 | #
12 | # This file is best viewed in a editor which supports python mode
13 | # syntax highlighting. Blank lines, or lines starting with a comment
14 | # symbol, are ignored, as are trailing comments. Other lines must
15 | # have the format
16 | # key : val # optional comment
17 | #
18 | # Colors: for the color values below, you can either use - a
19 | # matplotlib color string, such as r, k, or b - an rgb tuple, such as
20 | # (1.0, 0.5, 0.0) - a hex string, such as ff00ff or #ff00ff - a scalar
21 | # grayscale intensity such as 0.75 - a legal html color name, eg red,
22 | # blue, darkslategray
23 |
24 | #### CONFIGURATION BEGINS HERE
25 |
26 | # the default backend; one of GTK GTKAgg GTKCairo GTK3Agg GTK3Cairo
27 | # CocoaAgg FltkAgg MacOSX QtAgg Qt4Agg TkAgg WX WXAgg Agg Cairo GDK PS
28 | # PDF SVG Template
29 | # You can also deploy your own backend outside of matplotlib by
30 | # referring to the module name (which must be in the PYTHONPATH) as
31 | # 'module://my_backend'
32 | backend : TkAgg
33 |
34 | # If you are using the Qt4Agg backend, you can choose here
35 | # to use the PyQt4 bindings or the newer PySide bindings to
36 | # the underlying Qt4 toolkit.
37 | #backend.qt4 : PyQt4 # PyQt4 | PySide
38 |
39 | # Note that this can be overridden by the environment variable
40 | # QT_API used by Enthought Tool Suite (ETS); valid values are
41 | # "pyqt" and "pyside". The "pyqt" setting has the side effect of
42 | # forcing the use of Version 2 API for QString and QVariant.
43 |
44 | # if you are running pyplot inside a GUI and your backend choice
45 | # conflicts, we will automatically try to find a compatible one for
46 | # you if backend_fallback is True
47 | #backend_fallback: True
48 |
49 | #interactive : False
50 | #toolbar : toolbar2 # None | toolbar2 ("classic" is deprecated)
51 | #timezone : UTC # a pytz timezone string, eg US/Central or Europe/Paris
52 |
53 | # Where your matplotlib data lives if you installed to a non-default
54 | # location. This is where the matplotlib fonts, bitmaps, etc reside
55 | #datapath : /home/jdhunter/mpldata
56 |
57 |
58 | ### LINES
59 | # See http://matplotlib.org/api/artist_api.html#module-matplotlib.lines for more
60 | # information on line properties.
61 | lines.linewidth : 2.0 # line width in points
62 | #lines.linestyle : - # solid line
63 | #lines.color : blue # has no affect on plot(); see axes.color_cycle
64 | #lines.marker : None # the default marker
65 | #lines.markeredgewidth : 0.5 # the line width around the marker symbol
66 | #lines.markersize : 6 # markersize, in points
67 | #lines.dash_joinstyle : miter # miter|round|bevel
68 | #lines.dash_capstyle : butt # butt|round|projecting
69 | #lines.solid_joinstyle : miter # miter|round|bevel
70 | #lines.solid_capstyle : projecting # butt|round|projecting
71 | #lines.antialiased : True # render lines in antialised (no jaggies)
72 |
73 | ### PATCHES
74 | # Patches are graphical objects that fill 2D space, like polygons or
75 | # circles. See
76 | # http://matplotlib.org/api/artist_api.html#module-matplotlib.patches
77 | # information on patch properties
78 | patch.linewidth : 0.5 # edge width in points
79 | patch.facecolor : blue
80 | patch.edgecolor : eeeeee
81 | patch.antialiased : True
82 |
83 | ### FONT
84 | #
85 | # font properties used by text.Text. See
86 | # http://matplotlib.org/api/font_manager_api.html for more
87 | # information on font properties. The 6 font properties used for font
88 | # matching are given below with their default values.
89 | #
90 | # The font.family property has five values: 'serif' (e.g. Times),
91 | # 'sans-serif' (e.g. Helvetica), 'cursive' (e.g. Zapf-Chancery),
92 | # 'fantasy' (e.g. Western), and 'monospace' (e.g. Courier). Each of
93 | # these font families has a default list of font names in decreasing
94 | # order of priority associated with them.
95 | #
96 | # The font.style property has three values: normal (or roman), italic
97 | # or oblique. The oblique style will be used for italic, if it is not
98 | # present.
99 | #
100 | # The font.variant property has two values: normal or small-caps. For
101 | # TrueType fonts, which are scalable fonts, small-caps is equivalent
102 | # to using a font size of 'smaller', or about 83% of the current font
103 | # size.
104 | #
105 | # The font.weight property has effectively 13 values: normal, bold,
106 | # bolder, lighter, 100, 200, 300, ..., 900. Normal is the same as
107 | # 400, and bold is 700. bolder and lighter are relative values with
108 | # respect to the current weight.
109 | #
110 | # The font.stretch property has 11 values: ultra-condensed,
111 | # extra-condensed, condensed, semi-condensed, normal, semi-expanded,
112 | # expanded, extra-expanded, ultra-expanded, wider, and narrower. This
113 | # property is not currently implemented.
114 | #
115 | # The font.size property is the default font size for text, given in pts.
116 | # 12pt is the standard value.
117 | #
118 | #font.family : monospace
119 | #font.style : normal
120 | #font.variant : normal
121 | #font.weight : medium
122 | #font.stretch : normal
123 | # note that font.size controls default text sizes. To configure
124 | # special text sizes tick labels, axes, labels, title, etc, see the rc
125 | # settings for axes and ticks. Special text sizes can be defined
126 | # relative to font.size, using the following values: xx-small, x-small,
127 | # small, medium, large, x-large, xx-large, larger, or smaller
128 | #font.size : 12.0
129 | #font.serif : Bitstream Vera Serif, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif
130 | #font.sans-serif : Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
131 | #font.cursive : Apple Chancery, Textile, Zapf Chancery, Sand, cursive
132 | #font.fantasy : Comic Sans MS, Chicago, Charcoal, Impact, Western, fantasy
133 | #font.monospace : Andale Mono, Nimbus Mono L, Courier New, Courier, Fixed, Terminal, monospace
134 |
135 |
136 | ### TEXT
137 | # text properties used by text.Text. See
138 | # http://matplotlib.org/api/artist_api.html#module-matplotlib.text for more
139 | # information on text properties
140 |
141 | #text.color : black
142 |
143 | ### LaTeX customizations. See http://www.scipy.org/Wiki/Cookbook/Matplotlib/UsingTex
144 | #text.usetex : False # use latex for all text handling. The following fonts
145 | # are supported through the usual rc parameter settings:
146 | # new century schoolbook, bookman, times, palatino,
147 | # zapf chancery, charter, serif, sans-serif, helvetica,
148 | # avant garde, courier, monospace, computer modern roman,
149 | # computer modern sans serif, computer modern typewriter
150 | # If another font is desired which can loaded using the
151 | # LaTeX \usepackage command, please inquire at the
152 | # matplotlib mailing list
153 | #text.latex.unicode : False # use "ucs" and "inputenc" LaTeX packages for handling
154 | # unicode strings.
155 | #text.latex.preamble : # IMPROPER USE OF THIS FEATURE WILL LEAD TO LATEX FAILURES
156 | # AND IS THEREFORE UNSUPPORTED. PLEASE DO NOT ASK FOR HELP
157 | # IF THIS FEATURE DOES NOT DO WHAT YOU EXPECT IT TO.
158 | # preamble is a comma separated list of LaTeX statements
159 | # that are included in the LaTeX document preamble.
160 | # An example:
161 | # text.latex.preamble : \usepackage{bm},\usepackage{euler}
162 | # The following packages are always loaded with usetex, so
163 | # beware of package collisions: color, geometry, graphicx,
164 | # type1cm, textcomp. Adobe Postscript (PSSNFS) font packages
165 | # may also be loaded, depending on your font settings
166 |
167 | #text.dvipnghack : None # some versions of dvipng don't handle alpha
168 | # channel properly. Use True to correct
169 | # and flush ~/.matplotlib/tex.cache
170 | # before testing and False to force
171 | # correction off. None will try and
172 | # guess based on your dvipng version
173 |
174 | #text.hinting : 'auto' # May be one of the following:
175 | # 'none': Perform no hinting
176 | # 'auto': Use freetype's autohinter
177 | # 'native': Use the hinting information in the
178 | # font file, if available, and if your
179 | # freetype library supports it
180 | # 'either': Use the native hinting information,
181 | # or the autohinter if none is available.
182 | # For backward compatibility, this value may also be
183 | # True === 'auto' or False === 'none'.
184 | text.hinting_factor : 8 # Specifies the amount of softness for hinting in the
185 | # horizontal direction. A value of 1 will hint to full
186 | # pixels. A value of 2 will hint to half pixels etc.
187 |
188 | #text.antialiased : True # If True (default), the text will be antialiased.
189 | # This only affects the Agg backend.
190 |
191 | # The following settings allow you to select the fonts in math mode.
192 | # They map from a TeX font name to a fontconfig font pattern.
193 | # These settings are only used if mathtext.fontset is 'custom'.
194 | # Note that this "custom" mode is unsupported and may go away in the
195 | # future.
196 | #mathtext.cal : cursive
197 | #mathtext.rm : serif
198 | #mathtext.tt : monospace
199 | #mathtext.it : serif:italic
200 | #mathtext.bf : serif:bold
201 | #mathtext.sf : sans
202 | mathtext.fontset : cm # Should be 'cm' (Computer Modern), 'stix',
203 | # 'stixsans' or 'custom'
204 | #mathtext.fallback_to_cm : True # When True, use symbols from the Computer Modern
205 | # fonts when a symbol can not be found in one of
206 | # the custom math fonts.
207 |
208 | #mathtext.default : it # The default font to use for math.
209 | # Can be any of the LaTeX font names, including
210 | # the special name "regular" for the same font
211 | # used in regular text.
212 |
213 | ### AXES
214 | # default face and edge color, default tick sizes,
215 | # default fontsizes for ticklabels, and so on. See
216 | # http://matplotlib.org/api/axes_api.html#module-matplotlib.axes
217 | #axes.hold : True # whether to clear the axes by default on
218 | axes.facecolor : eeeeee # axes background color
219 | axes.edgecolor : bcbcbc # axes edge color
220 | #axes.linewidth : 1.0 # edge linewidth
221 | axes.grid : True # display grid or not
222 | axes.titlesize : x-large # fontsize of the axes title
223 | axes.labelsize : large # fontsize of the x any y labels
224 | #axes.labelweight : normal # weight of the x and y labels
225 | #axes.labelcolor : black
226 | #axes.axisbelow : False # whether axis gridlines and ticks are below
227 | # the axes elements (lines, text, etc)
228 | #axes.formatter.limits : -7, 7 # use scientific notation if log10
229 | # of the axis range is smaller than the
230 | # first or larger than the second
231 | #axes.formatter.use_locale : False # When True, format tick labels
232 | # according to the user's locale.
233 | # For example, use ',' as a decimal
234 | # separator in the fr_FR locale.
235 | #axes.formatter.use_mathtext : False # When True, use mathtext for scientific
236 | # notation.
237 | #axes.unicode_minus : True # use unicode for the minus symbol
238 | # rather than hyphen. See
239 | # http://en.wikipedia.org/wiki/Plus_and_minus_signs#Character_codes
240 | axes.color_cycle : 348ABD, A60628, 7A68A6, 467821,D55E00, CC79A7, 56B4E9, 009E73, F0E442, 0072B2 # color cycle for plot lines
241 | # as list of string colorspecs:
242 | # single letter, long name, or
243 | # web-style hex
244 |
245 | #polaraxes.grid : True # display grid on polar axes
246 | #axes3d.grid : True # display grid on 3d axes
247 |
248 | ### TICKS
249 | # see http://matplotlib.org/api/axis_api.html#matplotlib.axis.Tick
250 | #xtick.major.size : 4 # major tick size in points
251 | #xtick.minor.size : 2 # minor tick size in points
252 | #xtick.major.width : 0.5 # major tick width in points
253 | #xtick.minor.width : 0.5 # minor tick width in points
254 | #xtick.major.pad : 4 # distance to major tick label in points
255 | #xtick.minor.pad : 4 # distance to the minor tick label in points
256 | #xtick.color : k # color of the tick labels
257 | #xtick.labelsize : medium # fontsize of the tick labels
258 | #xtick.direction : in # direction: in, out, or inout
259 |
260 | #ytick.major.size : 4 # major tick size in points
261 | #ytick.minor.size : 2 # minor tick size in points
262 | #ytick.major.width : 0.5 # major tick width in points
263 | #ytick.minor.width : 0.5 # minor tick width in points
264 | #ytick.major.pad : 4 # distance to major tick label in points
265 | #ytick.minor.pad : 4 # distance to the minor tick label in points
266 | #ytick.color : k # color of the tick labels
267 | #ytick.labelsize : medium # fontsize of the tick labels
268 | #ytick.direction : in # direction: in, out, or inout
269 |
270 |
271 | ### GRIDS
272 | #grid.color : black # grid color
273 | #grid.linestyle : : # dotted
274 | #grid.linewidth : 0.5 # in points
275 | #grid.alpha : 1.0 # transparency, between 0.0 and 1.0
276 |
277 | ### Legend
278 | legend.fancybox : True # if True, use a rounded box for the
279 | # legend, else a rectangle
280 | #legend.isaxes : True
281 | #legend.numpoints : 2 # the number of points in the legend line
282 | #legend.fontsize : large
283 | #legend.pad : 0.0 # deprecated; the fractional whitespace inside the legend border
284 | #legend.borderpad : 0.5 # border whitespace in fontsize units
285 | #legend.markerscale : 1.0 # the relative size of legend markers vs. original
286 | # the following dimensions are in axes coords
287 | #legend.labelsep : 0.010 # deprecated; the vertical space between the legend entries
288 | #legend.labelspacing : 0.5 # the vertical space between the legend entries in fraction of fontsize
289 | #legend.handlelen : 0.05 # deprecated; the length of the legend lines
290 | #legend.handlelength : 2. # the length of the legend lines in fraction of fontsize
291 | #legend.handleheight : 0.7 # the height of the legend handle in fraction of fontsize
292 | #legend.handletextsep : 0.02 # deprecated; the space between the legend line and legend text
293 | #legend.handletextpad : 0.8 # the space between the legend line and legend text in fraction of fontsize
294 | #legend.axespad : 0.02 # deprecated; the border between the axes and legend edge
295 | #legend.borderaxespad : 0.5 # the border between the axes and legend edge in fraction of fontsize
296 | #legend.columnspacing : 2. # the border between the axes and legend edge in fraction of fontsize
297 | #legend.shadow : False
298 | #legend.frameon : True # whether or not to draw a frame around legend
299 |
300 | ### FIGURE
301 | # See http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure
302 | figure.figsize : 11, 8 # figure size in inches
303 | figure.dpi : 100 # figure dots per inch
304 | #figure.facecolor : 0.75 # figure facecolor; 0.75 is scalar gray
305 | #figure.edgecolor : white # figure edgecolor
306 | #figure.autolayout : False # When True, automatically adjust subplot
307 | # parameters to make the plot fit the figure
308 |
309 | # The figure subplot parameters. All dimensions are a fraction of the
310 | # figure width or height
311 | #figure.subplot.left : 0.125 # the left side of the subplots of the figure
312 | #figure.subplot.right : 0.9 # the right side of the subplots of the figure
313 | #figure.subplot.bottom : 0.1 # the bottom of the subplots of the figure
314 | #figure.subplot.top : 0.9 # the top of the subplots of the figure
315 | #figure.subplot.wspace : 0.2 # the amount of width reserved for blank space between subplots
316 | #figure.subplot.hspace : 0.2 # the amount of height reserved for white space between subplots
317 |
318 | ### IMAGES
319 | #image.aspect : equal # equal | auto | a number
320 | #image.interpolation : bilinear # see help(imshow) for options
321 | #image.cmap : jet # gray | jet etc...
322 | #image.lut : 256 # the size of the colormap lookup table
323 | #image.origin : upper # lower | upper
324 | #image.resample : False
325 |
326 | ### CONTOUR PLOTS
327 | #contour.negative_linestyle : dashed # dashed | solid
328 |
329 | ### Agg rendering
330 | ### Warning: experimental, 2008/10/10
331 | #agg.path.chunksize : 0 # 0 to disable; values in the range
332 | # 10000 to 100000 can improve speed slightly
333 | # and prevent an Agg rendering failure
334 | # when plotting very large data sets,
335 | # especially if they are very gappy.
336 | # It may cause minor artifacts, though.
337 | # A value of 20000 is probably a good
338 | # starting point.
339 | ### SAVING FIGURES
340 | #path.simplify : True # When True, simplify paths by removing "invisible"
341 | # points to reduce file size and increase rendering
342 | # speed
343 | #path.simplify_threshold : 0.1 # The threshold of similarity below which
344 | # vertices will be removed in the simplification
345 | # process
346 | #path.snap : True # When True, rectilinear axis-aligned paths will be snapped to
347 | # the nearest pixel when certain criteria are met. When False,
348 | # paths will never be snapped.
349 |
350 | # the default savefig params can be different from the display params
351 | # Eg, you may want a higher resolution, or to make the figure
352 | # background white
353 | savefig.dpi : 300 # figure dots per inch
354 | #savefig.facecolor : white # figure facecolor when saving
355 | #savefig.edgecolor : white # figure edgecolor when saving
356 | #savefig.format : png # png, ps, pdf, svg
357 | #savefig.bbox : standard # 'tight' or 'standard'.
358 | #savefig.pad_inches : 0.1 # Padding to be used when bbox is set to 'tight'
359 |
360 | # tk backend params
361 | #tk.window_focus : False # Maintain shell focus for TkAgg
362 |
363 | # ps backend params
364 | #ps.papersize : letter # auto, letter, legal, ledger, A0-A10, B0-B10
365 | #ps.useafm : False # use of afm fonts, results in small files
366 | #ps.usedistiller : False # can be: None, ghostscript or xpdf
367 | # Experimental: may produce smaller files.
368 | # xpdf intended for production of publication quality files,
369 | # but requires ghostscript, xpdf and ps2eps
370 | #ps.distiller.res : 6000 # dpi
371 | #ps.fonttype : 3 # Output Type 3 (Type3) or Type 42 (TrueType)
372 |
373 | # pdf backend params
374 | #pdf.compression : 6 # integer from 0 to 9
375 | # 0 disables compression (good for debugging)
376 | #pdf.fonttype : 3 # Output Type 3 (Type3) or Type 42 (TrueType)
377 |
378 | # svg backend params
379 | #svg.image_inline : True # write raster image data directly into the svg file
380 | #svg.image_noscale : False # suppress scaling of raster data embedded in SVG
381 | #svg.fonttype : 'path' # How to handle SVG fonts:
382 | # 'none': Assume fonts are installed on the machine where the SVG will be viewed.
383 | # 'path': Embed characters as paths -- supported by most SVG renderers
384 | # 'svgfont': Embed characters as SVG fonts -- supported only by Chrome,
385 | # Opera and Safari
386 |
387 | # docstring params
388 | #docstring.hardcopy = False # set this when you want to generate hardcopy docstring
389 |
390 | # Set the verbose flags. This controls how much information
391 | # matplotlib gives you at runtime and where it goes. The verbosity
392 | # levels are: silent, helpful, debug, debug-annoying. Any level is
393 | # inclusive of all the levels below it. If your setting is "debug",
394 | # you'll get all the debug and helpful messages. When submitting
395 | # problems to the mailing-list, please set verbose to "helpful" or "debug"
396 | # and paste the output into your report.
397 | #
398 | # The "fileo" gives the destination for any calls to verbose.report.
399 | # These objects can a filename, or a filehandle like sys.stdout.
400 | #
401 | # You can override the rc default verbosity from the command line by
402 | # giving the flags --verbose-LEVEL where LEVEL is one of the legal
403 | # levels, eg --verbose-helpful.
404 | #
405 | # You can access the verbose instance in your code
406 | # from matplotlib import verbose.
407 | #verbose.level : silent # one of silent, helpful, debug, debug-annoying
408 | #verbose.fileo : sys.stdout # a log filename, sys.stdout or sys.stderr
409 |
410 | # Event keys to interact with figures/plots via keyboard.
411 | # Customize these settings according to your needs.
412 | # Leave the field(s) empty if you don't need a key-map. (i.e., fullscreen : '')
413 |
414 | #keymap.fullscreen : f # toggling
415 | #keymap.home : h, r, home # home or reset mnemonic
416 | #keymap.back : left, c, backspace # forward / backward keys to enable
417 | #keymap.forward : right, v # left handed quick navigation
418 | #keymap.pan : p # pan mnemonic
419 | #keymap.zoom : o # zoom mnemonic
420 | #keymap.save : s # saving current figure
421 | #keymap.quit : ctrl+w # close the current figure
422 | #keymap.grid : g # switching on/off a grid in current axes
423 | #keymap.yscale : l # toggle scaling of y-axes ('log'/'linear')
424 | #keymap.xscale : L, k # toggle scaling of x-axes ('log'/'linear')
425 | #keymap.all_axes : a # enable all axes
426 |
427 | ###ANIMATION settings
428 | #animation.writer : ffmpeg # MovieWriter 'backend' to use
429 | #animation.codec : mp4 # Codec to use for writing movie
430 | #animation.bitrate: -1 # Controls size/quality tradeoff for movie.
431 | # -1 implies let utility auto-determine
432 | #animation.frame_format: 'png' # Controls frame format used by temp files
433 | #animation.ffmpeg_path: 'ffmpeg' # Path to ffmpeg binary. Without full path
434 | # $PATH is searched
435 | #animation.ffmpeg_args: '' # Additional arugments to pass to mencoder
436 | #animation.mencoder_path: 'ffmpeg' # Path to mencoder binary. Without full path
437 | # $PATH is searched
438 | #animation.mencoder_args: '' # Additional arugments to pass to mencoder
439 |
--------------------------------------------------------------------------------