pymc3 Multi-category Bayesian network - how to sam

2019-08-20 07:51发布

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)

标签: pymc pymc3
1条回答
太酷不给撩
2楼-- · 2019-08-20 08:24

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)) :-)

查看更多
登录 后发表回答