4 A vanilla Metropolis-Hastings sampler
8 from __future__
import (division, print_function, absolute_import,
11 __all__ = [
"MHSampler"]
15 from .sampler
import Sampler
21 The most basic possible Metropolis-Hastings style MCMC sampler
24 The covariance matrix to use for the proposal distribution.
27 Number of dimensions in the parameter space.
30 A function that takes a vector in the parameter space as input and
31 returns the natural logarithm of the posterior probability for that
34 :param args: (optional)
35 A list of extra arguments for ``lnpostfn``. ``lnpostfn`` will be
36 called with the sequence ``lnpostfn(p, *args)``.
39 def __init__(self, cov, *args, **kwargs):
40 super(MHSampler, self).__init__(*args, **kwargs)
44 super(MHSampler, self).reset()
45 self.
_chain = np.empty((0, self.dim))
48 def sample(self, p0, lnprob=None, randomstate=None, thin=1,
49 storechain=
True, iterations=1):
51 Advances the chain ``iterations`` steps as an iterator
54 The initial position vector.
56 :param lnprob0: (optional)
57 The log posterior probability at position ``p0``. If ``lnprob``
58 is not provided, the initial value is calculated.
60 :param rstate0: (optional)
61 The state of the random number generator. See the
62 :func:`random_state` property for details.
64 :param iterations: (optional)
65 The number of steps to run.
67 :param thin: (optional)
68 If you only want to store and yield every ``thin`` samples in the
69 chain, set thin to an integer greater than 1.
71 :param storechain: (optional)
72 By default, the sampler stores (in memory) the positions and
73 log-probabilities of the samples in the chain. If you are
74 using another method to store the samples to a file or if you
75 don't need to analyse the samples after the fact (for burn-in
76 for example) set ``storechain`` to ``False``.
78 At each iteration, this generator yields:
80 * ``pos`` — The current positions of the chain in the parameter
83 * ``lnprob`` — The value of the log posterior at ``pos`` .
85 * ``rstate`` — The current state of the random number generator.
93 lnprob = self.get_lnprob(p)
97 N = int(iterations / thin)
99 np.zeros((N, self.dim))), axis=0)
104 for i
in range(int(iterations)):
108 q = self._random.multivariate_normal(p, self.
cov)
109 newlnprob = self.get_lnprob(q)
110 diff = newlnprob - lnprob
114 diff = np.exp(diff) - self._random.rand()
121 if storechain
and i % thin == 0:
122 ind = i0 + int(i / thin)