pymc3 Multi-category Bayesian network - how to sample?

醉酒当歌 提交于 2020-01-25 22:04:14

问题


I have set up a Bayes net with 3 states per node as below, and can read logp's for particular states from it (as in the code).

Next I would like to sample from it. In the code below, sampling runs but I don't see distributions over the three states in the outputs; rather, I see a mean and variance as if they were continuous nodes. How do I get the posterior over the three states?

import numpy as np import pymc3 as mc import pylab, math

model = mc.Model() with model:

rain = mc.Categorical('rain', p = np.array([0.5, 0. ,0.5]))

sprinkler = mc.Categorical('sprinkler', p=np.array([0.33,0.33,0.34]))

CPT = mc.math.constant(np.array([ [ [.1,.2,.7], [.2,.2,.6], [.3,.3,.4] ],\
                                  [ [.8,.1,.1], [.3,.4,.3], [.1,.1,.8] ],\
                                  [ [.6,.2,.2], [.4,.4,.2], [.2,.2,.6] ] ]))

p_wetgrass = CPT[rain, sprinkler]
wetgrass = mc.Categorical('wetgrass', p_wetgrass)

#brute force search (not working)
for val_rain in range(0,3):
    for val_sprinkler in range(0,3):
        for val_wetgrass in range(0,3):
            lik = model.logp(rain=val_rain, sprinkler=val_sprinkler, wetgrass=val_wetgrass )
            print([val_rain, val_sprinkler, val_wetgrass, lik])

#sampling (runs but don't understand output)
if 1:
    niter = 10000  # 10000
    tune = 5000  # 5000
    print("SAMPLING:")
    #trace = mc.sample(20000, step=[mc.BinaryGibbsMetropolis([rain, sprinkler])], tune=tune, random_seed=124)
    trace = mc.sample(20000, tune=tune, random_seed=124)

    print("trace summary")
    mc.summary(trace)

回答1:


answering own question: the trace does contain the discrete values but the mc.summary(trace) function is set up to compute continuous mean and variance stats. To make a histogram of the discrete states, use h = hist(trace.get_values(sprinkler)) :-)



来源:https://stackoverflow.com/questions/43540977/pymc3-multi-category-bayesian-network-how-to-sample

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!