python-通过蒙特卡洛马尔可夫链的简单贝叶斯网络移植到PyMC3
作者:互联网
我正在将Simple Bayesian Network via Monte Carlo Markov Chain的示例从PyMC2移植到PyMC3,并且可以正常工作.可以在GitHub上以下gist的pymc3_rain_sprinkler_grass_simple_bayesian_network.py文件中找到结果.
我想通过提供证据来扩展原始示例,例如知道草是湿的,然后让PyMC3给我答案,例如“给定的草是湿的,下雨的概率是多少?”.
似乎所得到的轨迹是“恒定的”,例如再也没有随机性的元素了.在主旨中查看pymc3_rain_sprinkler_grass_simple_bayesian_network_with_evidence.py并执行df.drop_duplicates()以了解我的意思.
我究竟做错了什么?
解决方法:
我设法解决了我的问题.要点是将testval设置为“ true”而不是“ false”.改善了将步进方法从Metropolis更改为BinaryGibbsMetropolis的情况.
供参考,这里是完整的解决方案.我还更新了要点.
import numpy as np
import pandas as pd
import pymc3 as pm
niter = 10000 # 10000
tune = 5000 # 5000
model = pm.Model()
with model:
tv = [1]
rain = pm.Bernoulli('rain', 0.2, shape=1, testval=tv)
sprinkler_p = pm.Deterministic('sprinkler_p', pm.math.switch(rain, 0.01, 0.40))
sprinkler = pm.Bernoulli('sprinkler', sprinkler_p, shape=1, testval=tv)
grass_wet_p = pm.Deterministic('grass_wet_p', pm.math.switch(rain, pm.math.switch(sprinkler, 0.99, 0.80), pm.math.switch(sprinkler, 0.90, 0.0)))
grass_wet = pm.Bernoulli('grass_wet', grass_wet_p, observed=np.array([1]), shape=1)
trace = pm.sample(20000, step=[pm.BinaryGibbsMetropolis([rain, sprinkler])], tune=tune, random_seed=124)
# pm.traceplot(trace)
dictionary = {
'Rain': [1 if ii[0] else 0 for ii in trace['rain'].tolist() ],
'Sprinkler': [1 if ii[0] else 0 for ii in trace['sprinkler'].tolist() ],
'Sprinkler Probability': [ii[0] for ii in trace['sprinkler_p'].tolist()],
'Grass Wet Probability': [ii[0] for ii in trace['grass_wet_p'].tolist()],
}
df = pd.DataFrame(dictionary)
p_rain = df[(df['Rain'] == 1)].shape[0] / df.shape[0]
print(p_rain)
p_sprinkler = df[(df['Sprinkler'] == 1)].shape[0] / df.shape[0]
print(p_sprinkler)
标签:pymc3,python 来源: https://codeday.me/bug/20191118/2024518.html