在 PyMC3 中保存来自 traceplot 的数据

Saving data from traceplot in PyMC3

下面是简单贝叶斯线性回归的代码。在我获得参数的轨迹和绘图后,有什么方法可以将创建绘图的数据保存在文件中,这样如果我需要再次绘制它,我可以简单地从文件中的数据中绘制出来而不是再次 运行 整个模拟?

import pymc3 as pm
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0,9,5)
y = 2*x + 5
yerr=np.random.rand(len(x))

def soln(x, p1, p2):
    return p1+p2*x

with pm.Model() as model:
    # Define priors
    intercept = pm.Normal('Intercept', 15, sd=5)
    slope = pm.Normal('Slope', 20, sd=5)
    # Model solution
    sol = soln(x, intercept, slope)
    # Define likelihood
    likelihood = pm.Normal('Y', mu=sol,
                        sd=yerr, observed=y)

    # Sampling

    trace = pm.sample(1000, nchains = 1)


pm.traceplot(trace)
print pm.summary(trace, ['Slope'])
print pm.summary(trace, ['Intercept'])
plt.show()

有两种简单的方法可以做到这一点:

  1. 使用 3.4.1 之后的版本(目前这意味着从 master 安装,pip install git+https://github.com/pymc-devs/pymc3)。有一项新功能可以有效地保存和加载轨迹。请注意,您需要访问创建跟踪的模型:

    ...
    pm.save_trace(trace, 'linreg.trace') 
    
    # later
    with model:
       trace = pm.load_trace('linreg.trace') 
    
  2. 使用cPickle(或python 3 中的pickle)。请注意 pickle 至少有点不安全,不要从不受信任的来源中提取数据:

    import cPickle as pickle  # just `import pickle` on python 3
    
    ...
    with open('trace.pkl', 'wb') as buff:
        pickle.dump(trace, buff)
    
    #later
    with open('trace.pkl', 'rb') as buff:
        trace = pickle.load(buff)
    

这种方式适合我:

# saving trace
pm.save_trace(trace=trace_nb, directory=r"c:\Users\xxx\Documents\xxx\traces\trace_nb")

# loading saved traces
with model_nb:
    t_nb = pm.load_trace(directory=r"c:\Users\xxx\Documents\xxx\traces\trace_nb")