0

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

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()
4

2 回答 2

3

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

  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(或pickle在 python 3 中)。请注意,这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)
    
于 2018-06-13T15:27:50.863 回答
0

这种方式对我有用:

# 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")
于 2021-10-04T15:36:22.203 回答