Download PyMC: Bayesian Stochastic Modelling in Python

Transcript
42
PyMC: Bayesian Stochastic Modelling in Python
array([ 2.28320992,
2.36982455,
3.14499489,
2.28320992,
2.36982455,
3.14499489,
2.28320992,
3.1669422 ,
3.14499489,
2.28320992,
3.1669422 ,
2.94672454,
2.28320992,
3.14499489,
3.10767686])
6.2. Saving data to disk
By default, the database backend selected by the MCMC sampler is the ram backend, which
simply holds the data in RAM. Now, we create a sampler that, instead, writes data to a pickle
file:
>>> M = pm.MCMC(DisasterModel, db='pickle', dbname='Disaster.pickle')
>>> M.db
<pymc.database.pickle.Database object at 0x7fa486623d90>
>>> M.sample(10)
>>> M.db.close()
Note that in this particular case, no data is written to disk before the call to db.close. The
close method will flush data to disk and prepare the database for a potential session exit.
Closing a Python session without calling close beforehand is likely to corrupt the database,
making the data irretrievable. To simply flush data to disk without closing the database, use
the commit method.
Some backends not only have the ability to store the traces, but also the state of the step
methods at the end of sampling. This is particularly useful when long warm-up periods are
needed to tune the jump parameters. When the database is loaded in a new session, the step
methods query the database to fetch the state they were in at the end of the last trace.
Check that you close the database before closing the Python session.
6.3. Loading back a database
To load a file created in a previous session, use the load function from the appropriate
backend:
>>> db = pymc.database.pickle.load('Disaster.pickle')
>>> len(db.trace('e')[:])
10
The db object also has a trace method identical to that of Sampler. You can hence inspect
the results of a model, even if you don’t have the model around.
To add a new trace to this file, we need to create an MCMC instance. This time, instead
of setting db=’pickle’, we will pass the existing Database instance and sample as usual. A
new trace will be appended to the first:
>>>
>>>
>>>
15
>>>
M = MCMC(DisasterModel, db=db)
M.sample(5)
len(M.trace('e', chain=None)[:])
M.db.close()