Porting pymc2 code to pymc3: custom likelihood function

孤街醉人 提交于 2019-12-13 19:50:37

问题


I am trying to implement the censored data example in Lee&Wagenmakers' book (Chapter 5.5, page 70). In pymc2, I have the following model:

nattempts = 950   
nfails = 949   
n = 50    # Number of questions
y = np.zeros(nattempts)
y[nattempts-1] = 1
z = 30
unobsmin = 15
unobsmax = 25
unobsrange = np.arange(unobsmin,unobsmax+1)

theta = pymc.Uniform("theta",lower = .25, upper = 1)

@pymc.observed
def Ylike(value=z, theta = theta, n=n, censorn=nfails, unobs=unobsrange):
    ylikeobs = pymc.binomial_like(x=value, n=n, p=theta)
    ylikeunobs = np.array([])
    for i in unobs:
        ylikeunobs = np.append(pymc.binomial_like(x=i, n=n, p=theta),ylikeunobs)
    return ylikeobs+sum(ylikeunobs)*censorn

testmodel = pymc.Model([theta,Ylike])
mcmc = pymc.MCMC(testmodel)
mcmc.sample(iter = 20000, burn = 50, thin = 2)

which involved the decorater @pymc.observed.
I think I need to express the likelihood using the pm.DensityDist, however, I could not figure it out how to.


回答1:


OK, I found out how to do it:

with pm.Model():
    theta = pm.Uniform("theta",lower = .25, upper = 1)
    def logp(value,n,p):
        return pm.dist_math.bound(
        pm.dist_math.binomln(n, value) 
      + pm.dist_math.logpow(p, value) 
      + pm.dist_math.logpow(1 - p, n - value),
        0 <= value, value <= n,
        0 <= p, p <= 1)
    def Censorlike(value=z, n=n, censorn=nfails, unobs=unobsrange):
        ylikeobs = logp(value=value, n=n, p=theta)
        ylikeunobs = 0
        for i in unobs:
            ylikeunobs += logp(value=i, n=n, p=theta)
        return ylikeobs+ylikeunobs*censorn

    ylike = pm.DensityDist('ylike', Censorlike, observed={'value':z,'n':n,'censorn':nfails,'unobs':unobsrange})
    trace = pm.sample(3e3)


来源:https://stackoverflow.com/questions/35552491/porting-pymc2-code-to-pymc3-custom-likelihood-function

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