471 lines
35 KiB
HTML
471 lines
35 KiB
HTML
<!--
|
|
Automatically generated HTML file from DocOnce source
|
|
(https://github.com/hplgit/doconce/)
|
|
-->
|
|
<html>
|
|
<head>
|
|
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
|
<meta name="generator" content="DocOnce: https://github.com/hplgit/doconce/" />
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
<meta name="description" content="Data Analysis and Machine Learning: Elements of Bayesian theory and Bayesian Neural Networks">
|
|
|
|
<title>Data Analysis and Machine Learning: Elements of Bayesian theory and Bayesian Neural Networks</title>
|
|
|
|
<!-- Bootstrap style: bootstrap -->
|
|
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
|
|
<!-- not necessary
|
|
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
|
|
-->
|
|
|
|
<style type="text/css">
|
|
|
|
/* Add scrollbar to dropdown menus in bootstrap navigation bar */
|
|
.dropdown-menu {
|
|
height: auto;
|
|
max-height: 400px;
|
|
overflow-x: hidden;
|
|
}
|
|
|
|
/* Adds an invisible element before each target to offset for the navigation
|
|
bar */
|
|
.anchor::before {
|
|
content:"";
|
|
display:block;
|
|
height:50px; /* fixed header height for style bootstrap */
|
|
margin:-50px 0 0; /* negative fixed header height */
|
|
}
|
|
</style>
|
|
|
|
|
|
</head>
|
|
|
|
<!-- tocinfo
|
|
{'highest level': 2,
|
|
'sections': [('Why Bayesian Statistics?', 2, None, '___sec0'),
|
|
('Inference', 2, None, '___sec1'),
|
|
('Statistical Inference', 2, None, '___sec2'),
|
|
('Some history', 2, None, '___sec3'),
|
|
('The Bayesian recipe', 2, None, '___sec4'),
|
|
("Bayes' theorem", 2, None, '___sec5'),
|
|
("The friends of Bayes' theorem", 2, None, '___sec6'),
|
|
('Inference With Parametric Models', 2, None, '___sec7'),
|
|
('Illustrative examples with python code', 2, None, '___sec8'),
|
|
('Example: Is this a fair coin?', 2, None, '___sec9'),
|
|
('A few words on different priors', 2, None, '___sec10'),
|
|
('Bayesian parameter estimation (single parameter)',
|
|
2,
|
|
None,
|
|
'___sec11'),
|
|
('Example: Measured flux from a star', 3, None, '___sec12'),
|
|
('Simple Photon Counts: Frequentist Approach',
|
|
3,
|
|
None,
|
|
'___sec13'),
|
|
('Simple Photon Counts: Bayesian Approach', 3, None, '___sec14'),
|
|
('A note about priors', 3, None, '___sec15'),
|
|
('Simple Photon Counts: Bayesian approach in practice',
|
|
3,
|
|
None,
|
|
'___sec16'),
|
|
('Best estimates and confidence intervals', 3, None, '___sec17'),
|
|
('Simple Photon Counts: Best estimates and confidence intervals',
|
|
3,
|
|
None,
|
|
'___sec18'),
|
|
('Bayesian parameter estimation (multiple parameters, '
|
|
'covariance)',
|
|
2,
|
|
None,
|
|
'___sec19'),
|
|
('Bayesian model selection', 2, None, '___sec20')]}
|
|
end of tocinfo -->
|
|
|
|
<body>
|
|
|
|
|
|
|
|
<script type="text/x-mathjax-config">
|
|
MathJax.Hub.Config({
|
|
TeX: {
|
|
equationNumbers: { autoNumber: "none" },
|
|
extensions: ["AMSmath.js", "AMSsymbols.js", "autobold.js", "color.js"]
|
|
}
|
|
});
|
|
</script>
|
|
<script type="text/javascript" async
|
|
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<!-- Bootstrap navigation bar -->
|
|
<div class="navbar navbar-default navbar-fixed-top">
|
|
<div class="navbar-header">
|
|
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-responsive-collapse">
|
|
<span class="icon-bar"></span>
|
|
<span class="icon-bar"></span>
|
|
<span class="icon-bar"></span>
|
|
</button>
|
|
<a class="navbar-brand" href="Bayesian-bs.html">Data Analysis and Machine Learning: Elements of Bayesian theory and Bayesian Neural Networks</a>
|
|
</div>
|
|
|
|
<div class="navbar-collapse collapse navbar-responsive-collapse">
|
|
<ul class="nav navbar-nav navbar-right">
|
|
<li class="dropdown">
|
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Contents <b class="caret"></b></a>
|
|
<ul class="dropdown-menu">
|
|
<!-- navigation toc: --> <li><a href="._Bayesian-bs001.html#___sec0" style="font-size: 80%;"><b>Why Bayesian Statistics?</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="._Bayesian-bs002.html#___sec1" style="font-size: 80%;"><b>Inference</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="._Bayesian-bs003.html#___sec2" style="font-size: 80%;"><b>Statistical Inference</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="._Bayesian-bs004.html#___sec3" style="font-size: 80%;"><b>Some history</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="._Bayesian-bs010.html#___sec4" style="font-size: 80%;"><b>The Bayesian recipe</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="._Bayesian-bs011.html#___sec5" style="font-size: 80%;"><b>Bayes' theorem</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="._Bayesian-bs013.html#___sec6" style="font-size: 80%;"><b>The friends of Bayes' theorem</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="._Bayesian-bs014.html#___sec7" style="font-size: 80%;"><b>Inference With Parametric Models</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="._Bayesian-bs016.html#___sec8" style="font-size: 80%;"><b>Illustrative examples with python code</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="._Bayesian-bs017.html#___sec9" style="font-size: 80%;"><b>Example: Is this a fair coin?</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="._Bayesian-bs018.html#___sec10" style="font-size: 80%;"><b>A few words on different priors</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="._Bayesian-bs019.html#___sec11" style="font-size: 80%;"><b>Bayesian parameter estimation (single parameter)</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec12" style="font-size: 80%;"> Example: Measured flux from a star</a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec13" style="font-size: 80%;"> Simple Photon Counts: Frequentist Approach</a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec14" style="font-size: 80%;"> Simple Photon Counts: Bayesian Approach</a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec15" style="font-size: 80%;"> A note about priors</a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec16" style="font-size: 80%;"> Simple Photon Counts: Bayesian approach in practice</a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec17" style="font-size: 80%;"> Best estimates and confidence intervals</a></li>
|
|
<!-- navigation toc: --> <li><a href="#___sec18" style="font-size: 80%;"> Simple Photon Counts: Best estimates and confidence intervals</a></li>
|
|
<!-- navigation toc: --> <li><a href="._Bayesian-bs021.html#___sec19" style="font-size: 80%;"><b>Bayesian parameter estimation (multiple parameters, covariance)</b></a></li>
|
|
<!-- navigation toc: --> <li><a href="._Bayesian-bs022.html#___sec20" style="font-size: 80%;"><b>Bayesian model selection</b></a></li>
|
|
|
|
</ul>
|
|
</li>
|
|
</ul>
|
|
</div>
|
|
</div>
|
|
</div> <!-- end of navigation bar -->
|
|
|
|
<div class="container">
|
|
|
|
<p> </p><p> </p><p> </p> <!-- add vertical space -->
|
|
|
|
<a name="part0020"></a>
|
|
<!-- !split -->
|
|
|
|
<h3 id="___sec12" class="anchor">Example: Measured flux from a star </h3>
|
|
|
|
Adapted from the blog <a href="http://jakevdp.github.io" target="_self">Pythonic Perambulations</a> by Jake VanderPlas.
|
|
|
|
<p>
|
|
Imagine that we point our telescope to the sky, and observe the light coming from a single star. For the time being, we'll assume that the star's true flux is constant with time, i.e. that is it has a fixed value \( F_\mathrm{true} \) (we'll also ignore effects like sky noise and other sources of systematic error). We'll assume that we perform a series of \( N \) measurements with our telescope, where the ith measurement reports the observed photon flux \( F_i \) and error \( e_i \) <button type="button" class="btn btn-primary btn-xs" rel="tooltip" data-placement="top" title="We'll make the reasonable assumption that errors are Gaussian. In a Frequentist perspective, \( e_i \) is the standard deviation of the results of a single measurement event in the limit of repetitions of that event. In the Bayesian perspective, \( e_i \) is the standard deviation of the (Gaussian) probability distribution describing our knowledge of that particular measurement given its observed value."><a href="#def_footnote_2" id="link_footnote_2" style="color: white">2</a></button>.
|
|
The question is, given this set of measurements \( D = \{F_i, e_i\} \), what is our best estimate of the true flux \( F_\mathrm{true} \)?
|
|
|
|
<p id="def_footnote_2"><a href="#link_footnote_2"><b>2:</b></a> We'll make the reasonable assumption that errors are Gaussian. In a Frequentist perspective, \( e_i \) is the standard deviation of the results of a single measurement event in the limit of repetitions of <em>that event</em>. In the Bayesian perspective, \( e_i \) is the standard deviation of the (Gaussian) probability distribution describing our knowledge of that particular measurement given its observed value.</p>
|
|
|
|
<p>
|
|
Because the measurements are number counts, a Poisson distribution is a good approximation to the measurement process:
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># for repeatability</span>
|
|
F_true <span style="color: #666666">=</span> <span style="color: #666666">1000</span> <span style="color: #408080; font-style: italic"># true flux, say number of photons measured in 1 second</span>
|
|
N <span style="color: #666666">=</span> <span style="color: #666666">50</span> <span style="color: #408080; font-style: italic"># number of measurements</span>
|
|
F <span style="color: #666666">=</span> stats<span style="color: #666666">.</span>poisson(F_true)<span style="color: #666666">.</span>rvs(N)
|
|
<span style="color: #408080; font-style: italic"># N measurements of the flux</span>
|
|
e <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sqrt(F) <span style="color: #408080; font-style: italic"># errors on Poisson counts estimated via square root</span>
|
|
</pre></div>
|
|
<p>
|
|
Now let's make a simple visualization of the "observed" data, see Fig. <a href="#fig:flux">2</a>.
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>fig, ax <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>subplots()
|
|
ax<span style="color: #666666">.</span>errorbar(F, np<span style="color: #666666">.</span>arange(N), xerr<span style="color: #666666">=</span>e, fmt<span style="color: #666666">=</span><span style="color: #BA2121">'ok'</span>, ecolor<span style="color: #666666">=</span><span style="color: #BA2121">'gray'</span>, alpha<span style="color: #666666">=0.5</span>)
|
|
ax<span style="color: #666666">.</span>vlines([F_true], <span style="color: #666666">0</span>, N, linewidth<span style="color: #666666">=5</span>, alpha<span style="color: #666666">=0.2</span>)
|
|
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">"Flux"</span>);ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">"measurement number"</span>);
|
|
</pre></div>
|
|
<p>
|
|
<center> <!-- figure label: --> <div id="fig:flux"></div> <!-- FIGURE -->
|
|
<hr class="figure">
|
|
<center><p class="caption">Figure 2: Single photon counts (flux measurements). <!-- caption label: fig:flux --> </p></center>
|
|
<p><img src="fig/singlephotoncount_fig_1.png" align="bottom" width=400></p>
|
|
</center>
|
|
|
|
<p>
|
|
These measurements each have a different error \( e_i \) which is estimated from Poisson statistics using the standard square-root rule. In this toy example we already know the true flux \( F_\mathrm{true} \), but the question is this: given our measurements and errors, what is our best estimate of the true flux?
|
|
|
|
<p>
|
|
Let's take a look at the frequentist and Bayesian approaches to solving this.
|
|
|
|
<h3 id="___sec13" class="anchor">Simple Photon Counts: Frequentist Approach </h3>
|
|
|
|
We'll start with the classical frequentist maximum likelihood approach. Given a single observation \( D_i = (F_i, e_i) \), we can compute the probability distribution of the measurement given the true flux Ftrue given our assumption of Gaussian errors
|
|
$$
|
|
\begin{equation}
|
|
p(D_i | F_\mathrm{true}, I) = \frac{1}{\sqrt{2\pi e_i^2}} \exp \left( \frac{-(F_i-F_\mathrm{true})^2}{2e_i^2} \right).
|
|
\tag{5}
|
|
\end{equation}
|
|
$$
|
|
|
|
This should be read "the probability of \( D_i \) given \( F_\mathrm{true} \)
|
|
equals ...". You should recognize this as a normal distribution with mean \( F_\mathrm{true} \) and standard deviation \( e_i \).
|
|
|
|
<p>
|
|
We construct the <em>likelihood function</em> by computing the product of the probabilities for each data point
|
|
$$
|
|
\begin{equation}
|
|
\mathcal{L}(D | F_\mathrm{true}, I) = \prod_{i=1}^N p(D_i | F_\mathrm{true}, I),
|
|
\tag{6}
|
|
\end{equation}
|
|
$$
|
|
|
|
here \( D = \{D_i\} \) represents the entire set of measurements. Because the value of the likelihood can become very small, it is often more convenient to instead compute the log-likelihood. Combining the previous two equations and computing the log, we have
|
|
$$
|
|
\begin{equation}
|
|
\log\mathcal{L} = -\frac{1}{2} \sum_{i=1}^N \left[ \log(2\pi e_i^2) + \frac{(F_i-F_\mathrm{true})^2}{e_i^2} \right].
|
|
\tag{7}
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>
|
|
What we'd like to do is determine \( F_\mathrm{true} \) such that the likelihood is maximized. For this simple problem, the maximization can be computed analytically (i.e. by setting \( d\log\mathcal{L}/d F_\mathrm{true} = 0 \)). This results in the following observed estimate of \( F_\mathrm{true} \)
|
|
$$
|
|
\begin{equation}
|
|
F_\mathrm{est} = \sum_{i=1}^N w_i F_i; \quad w_i = 1/e_i^2.
|
|
\tag{8}
|
|
\end{equation}
|
|
$$
|
|
|
|
Notice that in the special case of all errors \( e_i \) being equal, this reduces to
|
|
$$
|
|
\begin{equation}
|
|
F_\mathrm{est} = \frac{1}{N} \sum_{i=1} F_i.
|
|
\tag{9}
|
|
\end{equation}
|
|
$$
|
|
|
|
That is, in agreement with intuition, \( F_\mathrm{est} \) is simply the mean of the observed data when errors are equal.
|
|
|
|
<p>
|
|
We can go further and ask what the error of our estimate is. In the frequentist approach, this can be accomplished by fitting a Gaussian approximation to the likelihood curve at maximum; in this simple case this can also be solved analytically (the sum of Gaussians is also a Gaussian). It can be shown that the standard deviation of this Gaussian approximation is
|
|
$$
|
|
\begin{equation}
|
|
\sigma_\mathrm{est} = \sum_{i=1}^N w_i.
|
|
\tag{10}
|
|
\end{equation}
|
|
$$
|
|
|
|
These results are fairly simple calculations; let's evaluate them for our toy dataset:
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>w<span style="color: #666666">=1./</span>e<span style="color: #666666">**2</span>
|
|
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">"""</span>
|
|
<span style="color: #BA2121">F_true = {0}</span>
|
|
<span style="color: #BA2121">F_est = {1:.0f} +/- {2:.0f} (based on {3} measurements) """</span>\
|
|
<span style="color: #666666">.</span>format(F_true, (w <span style="color: #666666">*</span> F)<span style="color: #666666">.</span>sum() <span style="color: #666666">/</span> w<span style="color: #666666">.</span>sum(), w<span style="color: #666666">.</span>sum() <span style="color: #666666">**</span> <span style="color: #666666">-0.5</span>, N))
|
|
</pre></div>
|
|
<p>
|
|
<code>F_true = 1000</code> <br />
|
|
<code>F_est = 998 +/- 4 (based on 50 measurements)</code> <br />
|
|
|
|
<p>
|
|
We find that for 50 measurements of the flux, our estimate has an error of about 0.4% and is consistent with the input value.
|
|
|
|
<h3 id="___sec14" class="anchor">Simple Photon Counts: Bayesian Approach </h3>
|
|
|
|
The Bayesian approach, as you might expect, begins and ends with probabilities. Our hypothesis is that the star has a constant flux \( F_\mathrm{true} \). It recognizes that what we fundamentally want to compute is our knowledge of the parameters in question given the data and other information (such as our knowledge of uncertainties for the observed values), i.e. in this case, \( p(F_\mathrm{true} | D,I) \).
|
|
Note that this formulation of the problem is fundamentally contrary to the frequentist philosophy, which says that probabilities have no meaning for model parameters like \( F_\mathrm{true} \). Nevertheless, within the Bayesian philosophy this is perfectly acceptable.
|
|
|
|
<p>
|
|
To compute this result, Bayesians next apply Bayes' Theorem <a href="._Bayesian-bs011.html#mjx-eqn-1">(1)</a>.
|
|
If we set the prior \( p(F_\mathrm{true}|I) \propto 1 \) (a flat prior), we find
|
|
\( p(F_\mathrm{true}|D,I) \propto p(D | F_\mathrm{true},I) \equiv \mathcal{L}(D | F_\mathrm{true},I) \)
|
|
and the Bayesian probability is maximized at precisely the same value as the frequentist result! So despite the philosophical differences, we see that (for this simple problem at least) the Bayesian and frequentist point estimates are equivalent.
|
|
|
|
<h3 id="___sec15" class="anchor">A note about priors </h3>
|
|
|
|
The prior allows inclusion of other information into the computation, which becomes very useful in cases where multiple measurement strategies are being combined to constrain a single model. The necessity to specify a prior, however, is one of the more controversial pieces of Bayesian analysis.
|
|
A frequentist will point out that the prior is problematic when no true prior information is available. Though it might seem straightforward to use a noninformative prior like the flat prior mentioned above, there are some <a href="http://normaldeviate.wordpress.com/2013/07/13/lost-causes-in-statistics-ii-noninformative- priors/comment-page-1/" target="_self">surprisingly subtleties</a> involved. It turns out that in many situations, a truly noninformative prior does not exist! Frequentists point out that the subjective choice of a prior which necessarily biases your result has no place in statistical data analysis.
|
|
A Bayesian would counter that frequentism doesn't solve this problem, but simply skirts the question. Frequentism can often be viewed as simply a special case of the Bayesian approach for some (implicit) choice of the prior: a Bayesian would say that it's better to make this implicit choice explicit, even if the choice might include some subjectivity.
|
|
|
|
<h3 id="___sec16" class="anchor">Simple Photon Counts: Bayesian approach in practice </h3>
|
|
|
|
Leaving these philosophical debates aside for the time being, let's address how Bayesian results are generally computed in practice. For a one parameter problem like the one considered here, it's as simple as computing the posterior probability \( p(F_\mathrm{true} | D,I) \) as a function of \( F_\mathrm{true} \): this is the distribution reflecting our knowledge of the parameter \( F_\mathrm{true} \).
|
|
But as the dimension of the model grows, this direct approach becomes increasingly intractable. For this reason, Bayesian calculations often depend on sampling methods such as Markov Chain Monte Carlo (MCMC). For this practical example, let us apply an MCMC approach using Dan Foreman-Mackey's <a href="http://dan.iel.fm/emcee/current/" target="_self">emcee</a> package. Keep in mind here that the goal is to generate a set of points drawn from the posterior probability distribution, and to use those points to determine the answer we seek.
|
|
To perform this MCMC, we start by defining Python functions for the prior \( p(F_\mathrm{true} | I) \), the likelihood \( p(D | F_\mathrm{true},I) \), and the posterior \( p(F_\mathrm{true} | D,I) \), noting that none of these need be properly normalized. Our model here is one-dimensional, but to handle multi-dimensional models we'll define the model in terms of an array of parameters \( \boldsymbol{\alpha} \), which in this case is \( \boldsymbol{\alpha} = [F_\mathrm{true}] \)
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">log_prior</span>(alpha):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">0</span> <span style="color: #408080; font-style: italic"># flat prior</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">log_likelihood</span>(alpha, F, e):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">-0.5</span> <span style="color: #666666">*</span> np<span style="color: #666666">.</span>sum(np<span style="color: #666666">.</span>log(<span style="color: #666666">2</span> <span style="color: #666666">*</span> np<span style="color: #666666">.</span>pi <span style="color: #666666">*</span> e <span style="color: #666666">**</span> <span style="color: #666666">2</span>) \
|
|
<span style="color: #666666">+</span> (F <span style="color: #666666">-</span> alpha[<span style="color: #666666">0</span>]) <span style="color: #666666">**</span> <span style="color: #666666">2</span> <span style="color: #666666">/</span> e <span style="color: #666666">**</span> <span style="color: #666666">2</span>)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">log_posterior</span>(alpha, F, e):
|
|
<span style="color: #008000; font-weight: bold">return</span> log_prior(alpha) <span style="color: #666666">+</span> log_likelihood(alpha, F, e)
|
|
</pre></div>
|
|
<p>
|
|
Now we set up the problem, including generating some random starting guesses for the multiple chains of points.
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>ndim <span style="color: #666666">=</span> <span style="color: #666666">1</span> <span style="color: #408080; font-style: italic"># number of parameters in the model</span>
|
|
nwalkers <span style="color: #666666">=</span> <span style="color: #666666">50</span> <span style="color: #408080; font-style: italic"># number of MCMC walkers</span>
|
|
nburn <span style="color: #666666">=</span> <span style="color: #666666">1000</span> <span style="color: #408080; font-style: italic"># "burn-in" period to let chains stabilize</span>
|
|
nsteps <span style="color: #666666">=</span> <span style="color: #666666">2000</span> <span style="color: #408080; font-style: italic"># number of MCMC steps to take</span>
|
|
<span style="color: #408080; font-style: italic"># we'll start at random locations between 0 and 2000</span>
|
|
starting_guesses <span style="color: #666666">=</span> <span style="color: #666666">2000</span> <span style="color: #666666">*</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(nwalkers, ndim)
|
|
sampler <span style="color: #666666">=</span> emcee<span style="color: #666666">.</span>EnsembleSampler(nwalkers, ndim, log_posterior, args<span style="color: #666666">=</span>[F,e])
|
|
sampler<span style="color: #666666">.</span>run_mcmc(starting_guesses, nsteps)
|
|
<span style="color: #408080; font-style: italic"># Shape of sampler.chain = (nwalkers, nsteps, ndim)</span>
|
|
<span style="color: #408080; font-style: italic"># Flatten the sampler chain and discard burn-in points:</span>
|
|
samples <span style="color: #666666">=</span> sampler<span style="color: #666666">.</span>chain[:, nburn:, :]<span style="color: #666666">.</span>reshape((<span style="color: #666666">-1</span>, ndim))
|
|
</pre></div>
|
|
<p>
|
|
If this all worked correctly, the array sample should contain a series of 50,000 points drawn from the posterior. Let's plot them and check. See results in Fig. <a href="#fig:flux-bayesian">3</a>.
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>fig, ax <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>subplots()
|
|
ax<span style="color: #666666">.</span>hist(samples, bins<span style="color: #666666">=50</span>, histtype<span style="color: #666666">=</span><span style="color: #BA2121">"stepfilled"</span>, alpha<span style="color: #666666">=0.3</span>, normed<span style="color: #666666">=</span><span style="color: #008000">True</span>)
|
|
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">r'$F_\mathrm{est}$'</span>)
|
|
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">r'$p(F_\mathrm{est}|D,I)$'</span>)
|
|
</pre></div>
|
|
<p>
|
|
<center> <!-- figure label: --> <div id="fig:flux-bayesian"></div> <!-- FIGURE -->
|
|
<hr class="figure">
|
|
<center><p class="caption">Figure 3: Bayesian posterior pdf (represented by a histogram of MCMC samples) from flux measurements. <!-- caption label: fig:flux-bayesian --> </p></center>
|
|
<p><img src="fig/singlephotoncount_fig_2.png" align="bottom" width=400></p>
|
|
</center>
|
|
|
|
<h3 id="___sec17" class="anchor">Best estimates and confidence intervals </h3>
|
|
|
|
The posterior distribution from our Bayesian data analysis is the key quantity that encodes our inference about the values of the model parameters, given the data and the relevant background information. Often, however, we wish to summarize this result with just a few numbers: the best estimate and a measure of its reliability.
|
|
|
|
<p>
|
|
There are a few different options for this. The choice of the most appropriate one depends mainly on the shape of the posterior distribution:
|
|
|
|
<p>
|
|
<em>Symmetric posterior pdfs</em>: Since the probability (density) associated with any particular value of the parameter is a measure of how much we believe that it lies in the neighbourhood of that point, our best estimate is given by the maximum of the posterior pdf. If we denote the quantity of interest by \( X \), with a posterior pdf \( P =p(X|D,I) \), then the best estimate of its value \( X_0 \) is given by the condition \( dP/dX|_{X=X_0}=0 \). Strictly speaking, we should also check the sign of the second derivative to ensure that \( X_0 \) represents a maximum.
|
|
|
|
<p>
|
|
To obtain a measure of the reliability of this best estimate, we need to look at the width or spread of the posterior pdf about \( X_0 \). When considering the behaviour of any function in the neighbourhood of a particular point, it is often helpful to carry out a Taylor series expansion; this is simply a standard tool for (locally) approximating a complicated function by a low-order polynomial. The linear term is zero at the maximum and the quadratic term is often the dominating one determining the width of the posterior pdf. Ignoring all the higher-order terms we arrive at the Gaussian approximation
|
|
$$
|
|
\begin{equation}
|
|
p(X|D,I) \approx \frac{1}{\sigma\sqrt{2\pi}} \exp \left[ -\frac{(x-\mu)^2}{2\sigma^2} \right],
|
|
\tag{11}
|
|
\end{equation}
|
|
$$
|
|
|
|
where the mean \( \mu = X_0 \) and the variance \( \sigma = \left( - \left. \frac{d^2L}{dX^2} \right|_{X_0} \right)^{-1/2} \), where \( L \) is the logarithm of the posterior \( P \). Our inference about the quantity of interest is conveyed very concisely, therefore, by the statement \( X = X_0 \pm \sigma \), and
|
|
$$
|
|
$$
|
|
p(X_0-\sigma < X < X_0+\sigma | D,I) = \int_{X_0-\sigma}^{X_0+\sigma} p(X|D,I) dX \approx 0.67.
|
|
$$
|
|
$$
|
|
|
|
<p>
|
|
<em>Asymmetric posterior pdfs</em>: While the maximum of the posterior (\( X_0 \)) can still be regarded as giving the best estimate, the true value is now more likely to be on one side of this rather than the other. Alternatively one can compute the mean value, \( \langle X \rangle = \int X p(X|D,I) dX \), although this tends to overemphasise very long tails. The best option is probably a compromise that can be employed when having access to a large sample from the posterior (as provided by an MCMC), namely to give the median of this ensamble.
|
|
|
|
<p>
|
|
Furthermore, the concept of an error-bar does not seem appropriate in this case, as it implicitly entails the idea of symmetry. A good way of expressing the reliability with which a parameter can be inferred, for an asymmetric posterior pdf, is rather through a <em>confidence interval</em>. Since the area under the posterior pdf between \( X_1 \) and \( X_2 \) is proportional to how much we believe that \( X \) lies in that range, the shortest interval that encloses 67% of the area represents a sensible measure of the uncertainty of the estimate. Obviously we can choose to provide some other degree-of-belief that we think is relevant for the case at hand. Assuming that the posterior pdf has been normalized, to have unit area, we need to find \( X_1 \) and \( X_2 \) such that:
|
|
$$
|
|
$$
|
|
p(X_1 < X < X_2 | D,I) = \int_{X_1}^{X_2} p(X|D,I) dX \approx 0.67,
|
|
$$
|
|
$$
|
|
|
|
where the difference \( X_2 - X_1 \) is as small as possible. The region \( X_1 < X < X_2 \) is then called the shortest 67% confidence interval.
|
|
|
|
<p>
|
|
<em>Multimodal posterior pdfs</em>: We can sometimes obtain posteriors which are multimodal; i.e. contains several disconnected regions with large probabilities. There is no difficulty when one of the maxima is very much larger than the others: we can simply ignore the subsidiary solutions, to a good approximation, and concentrate on the global maximum. The problem arises when there are several maxima of comparable magnitude. What do we now mean by a best estimate, and how should we quantify its reliability? The idea of a best estimate and an error-bar, or even a confidence interval, is merely an attempt to summarize the posterior with just two or three numbers; sometimes this just can’t be done, and so these concepts are not valid. For the bimodal case we might be able to characterize the posterior in terms of a few numbers: two best estimates and their associated error-bars, or disjoint confidence intervals. For a general multimodal pdf, the most honest thing we can do is just display the posterior itself.
|
|
|
|
<h3 id="___sec18" class="anchor">Simple Photon Counts: Best estimates and confidence intervals </h3>
|
|
|
|
To compute these numbers for our example, you would run:
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>sampper<span style="color: #666666">=</span>np<span style="color: #666666">.</span>percentile(samples, [<span style="color: #666666">2.5</span>, <span style="color: #666666">16.5</span>, <span style="color: #666666">50</span>, <span style="color: #666666">83.5</span>, <span style="color: #666666">97.5</span>],axis<span style="color: #666666">=0</span>)<span style="color: #666666">.</span>flatten()
|
|
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">"""</span>
|
|
<span style="color: #BA2121">F_true = {0}</span>
|
|
<span style="color: #BA2121">Based on {1} measurements the posterior point estimates are:</span>
|
|
<span style="color: #BA2121">...F_est = {2:.0f} +/- {3:.0f}</span>
|
|
<span style="color: #BA2121">or using credible intervals:</span>
|
|
<span style="color: #BA2121">...F_est = {4:.0f} (posterior median) </span>
|
|
<span style="color: #BA2121">...F_est in [{5:.0f}, {6:.0f}] (67</span><span style="color: #BB6688; font-weight: bold">% c</span><span style="color: #BA2121">redible interval) </span>
|
|
<span style="color: #BA2121">...F_est in [{7:.0f}, {8:.0f}] (95</span><span style="color: #BB6688; font-weight: bold">% c</span><span style="color: #BA2121">redible interval) """</span>\
|
|
<span style="color: #666666">.</span>format(F_true, N, np<span style="color: #666666">.</span>mean(samples), np<span style="color: #666666">.</span>std(samples), \
|
|
sampper[<span style="color: #666666">2</span>], sampper[<span style="color: #666666">1</span>], sampper[<span style="color: #666666">3</span>], sampper[<span style="color: #666666">0</span>], sampper[<span style="color: #666666">4</span>]))
|
|
</pre></div>
|
|
<p>
|
|
<code>F_true = 1000</code> <br />
|
|
<code>Based on 50 measurements the posterior point estimates are:</code> <br />
|
|
<code>...F_est = 998 +/- 4</code> <br />
|
|
<code>or using credible intervals:</code> <br />
|
|
<code>...F_est = 998 (posterior median)</code> <br />
|
|
<code>...F_est in [993, 1002] (67% credible interval)</code> <br />
|
|
<code>...F_est in [989, 1006] (95% credible interval)</code> <br />
|
|
|
|
<p>
|
|
In this particular example, the posterior pdf is actually a Gaussian (since it is constructed as a product of Gaussians), and the mean and variance from the quadratic approximation will agree exactly with the frequentist approach.
|
|
|
|
<p>
|
|
From this final result you might come away with the impression that the Bayesian method is unnecessarily complicated, and in this case it certainly is. Using an MCMC sampler to characterize a one-dimensional normal distribution is a bit like using the Death Star to destroy a beach ball, but we did this here because it demonstrates an approach that can scale to complicated posteriors in many, many dimensions, and can provide nice results in more complicated situations where an analytic likelihood approach is not possible.
|
|
|
|
<p>
|
|
Furthermore, as data and models grow in complexity, the two approaches can diverge greatly.
|
|
|
|
<p>
|
|
<p>
|
|
<!-- navigation buttons at the bottom of the page -->
|
|
<ul class="pagination">
|
|
<li><a href="._Bayesian-bs019.html">«</a></li>
|
|
<li><a href="._Bayesian-bs000.html">1</a></li>
|
|
<li><a href="">...</a></li>
|
|
<li><a href="._Bayesian-bs012.html">13</a></li>
|
|
<li><a href="._Bayesian-bs013.html">14</a></li>
|
|
<li><a href="._Bayesian-bs014.html">15</a></li>
|
|
<li><a href="._Bayesian-bs015.html">16</a></li>
|
|
<li><a href="._Bayesian-bs016.html">17</a></li>
|
|
<li><a href="._Bayesian-bs017.html">18</a></li>
|
|
<li><a href="._Bayesian-bs018.html">19</a></li>
|
|
<li><a href="._Bayesian-bs019.html">20</a></li>
|
|
<li class="active"><a href="._Bayesian-bs020.html">21</a></li>
|
|
<li><a href="._Bayesian-bs021.html">22</a></li>
|
|
<li><a href="._Bayesian-bs022.html">23</a></li>
|
|
<li><a href="._Bayesian-bs021.html">»</a></li>
|
|
</ul>
|
|
<!-- ------------------- end of main content --------------- -->
|
|
|
|
</div> <!-- end container -->
|
|
<!-- include javascript, jQuery *first* -->
|
|
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
|
|
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
|
|
|
|
<!-- Bootstrap footer
|
|
<footer>
|
|
<a href="http://..."><img width="250" align=right src="http://..."></a>
|
|
</footer>
|
|
-->
|
|
|
|
|
|
<center style="font-size:80%">
|
|
<!-- copyright only on the titlepage -->
|
|
</center>
|
|
|
|
|
|
</body>
|
|
</html>
|
|
|
|
|