定义自定义PyMC发行版 [英] Defining a custom PyMC distribution

查看:84
本文介绍了定义自定义PyMC发行版的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这也许是一个愚蠢的问题.

This is perhaps a silly question.

我正在尝试使用PyMC中的MCMC评估使数据适合非常奇怪的PDF.对于此示例,我只想弄清楚如何适应手动输入正常PDF的正态分布.我的代码是:

I'm trying to fit data to a very strange PDF using MCMC evaluation in PyMC. For this example I just want to figure out how to fit to a normal distribution where I manually input the normal PDF. My code is:

data = []; 
for count in range(1000): data.append(random.gauss(-200,15));

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

# @mc.potential
# def density(x = data, mu = mean, sigma = std_dev):
#   return (1./(sigma*np.sqrt(2*np.pi))*np.exp(-((x-mu)**2/(2*sigma**2))))

mc.Normal('process', mu=mean, tau=1./std_dev**2, value=data, observed=True)

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

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

我发现的示例都使用了mc.Normal或mc.Poisson之类的东西,但我想适合注释掉的密度函数.

The examples I've found all use something like mc.Normal, or mc.Poisson or whatnot, but I want to fit to the commented out density function.

任何帮助将不胜感激.

推荐答案

一种简单的方法是使用随机装饰器:

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'])

请注意,我的custom_stochastic函数返回对数似然率,而不是似然率,它是整个样本的对数似然率.

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.

这篇关于定义自定义PyMC发行版的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆