Defining a custom PyMC distribution

旧巷老猫 提交于 2019-12-03 06:18:19

An easy way is to use the stochastic decorator:

import pymc as mc
import numpy as np

data = np.random.normal(-200,15,size=1000)

mean = mc.Uniform('mean', lower=min(data), upper=max(data))
std_dev = mc.Uniform('std_dev', lower=0, upper=50)

@mc.stochastic(observed=True)
def custom_stochastic(value=data, mean=mean, std_dev=std_dev):
    return np.sum(-np.log(std_dev) - 0.5*np.log(2) - 
                  0.5*np.log(np.pi) - 
                  (value-mean)**2 / (2*(std_dev**2)))


model = mc.MCMC([mean,std_dev,custom_stochastic])
model.sample(iter=5000)

print "!"
print(model.stats()['mean']['mean'])
print(model.stats()['std_dev']['mean'])

Note that my custom_stochastic function returns the log likelihood, not the likelihood, and that it is the log likelihood for the entire sample.

There are a few other ways to create custom stochastic nodes. This doc gives more details, and this gist contains an example using pymc.Stochastic to create a node with a kernel density estimator.

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