Dirichlet process in PyMC 3

偶尔善良 提交于 2019-12-24 00:20:49

问题


I would like to implement to implement the Dirichlet process example referenced in Implementing Dirichlet processes for Bayesian semi-parametric models (source: here) in PyMC 3.

In the example the stick-breaking probabilities are computed using the pymc.deterministic decorator:

v = pymc.Beta('v', alpha=1, beta=alpha, size=N_dp)
@pymc.deterministic
def p(v=v):
    """ Calculate Dirichlet probabilities """

    # Probabilities from betas
    value = [u*np.prod(1-v[:i]) for i,u in enumerate(v)]
    # Enforce sum to unity constraint
    value[-1] = 1-sum(value[:-1])

    return value

 z = pymc.Categorical('z', p, size=len(set(counties)))

How would you implement this in PyMC 3 which is using Theano for the gradient computation?

edit: I tried the following solution using the theano.scan method:

with pm.Model() as mod:
    conc = Uniform('concentration', lower=0.5, upper=10)
    v = Beta('v', alpha=1, beta=conc, shape=n_dp)
    p, updates = theano.scan(fn=lambda stick, idx: stick * t.prod(1 - v[:idx]),
                             outputs_info=None,
                             sequences=[v, t.arange(n_dp)])
    t.set_subtensor(p[-1], 1 - t.sum(p[:-1]))
    category = Categorical('category', p, shape=n_algs)
    sd = Uniform('precs', lower=0, upper=20, shape=n_dp)
    means = Normal('means', mu=0, sd=100, shape=n_dp)
    points = Normal('obs',
                    means[category],
                    sd=sd[category],
                    observed=data)

    step1 = pm.Slice([conc, v, sd, means])
    step3 = pm.ElemwiseCategoricalStep(var=category, values=range(n_dp))
    trace = pm.sample(2000, step=[step1, step3], progressbar=True)

Which sadly is really slow and does not obtain the original parameters of the synthetic data.

Is there a better solution and is this even correct?


回答1:


Not sure I have a good answer but perhaps this could be sped up by instead using a theano blackbox op which allows you to write a distribution (or deterministic) in python code. E.g.: https://github.com/pymc-devs/pymc3/blob/master/pymc3/examples/disaster_model_arbitrary_deterministic.py



来源:https://stackoverflow.com/questions/25685104/dirichlet-process-in-pymc-3

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