How to implement a function of a random variable in PyMC which could be sampled by MCMC Metropolis?

一笑奈何 提交于 2020-01-06 15:03:41

问题


If you have a random variable $X$ and a function $f$, you can define $y=f(X)$ as a new random variable with a probability density function as follows:

$p(y)=(f^{-1})'(y)p(x)$. For details see here.

Now I have defined a random variable alpha, with an exponential distribution in the following code. I want to add to my model, log(alpha) as a new random variable. How should I implement it in my model?

I already made an effort but it seems that it is wrong, and the reason as been pointed out in answers is the fact that I used stochastic decorator rather than a deterministic one. But because later I want to apply MCMC Metropolis on this variable I need it to be statistic! To clarify it more, I want to apply a Gaussian proposal on the log(alpha). So I need to hand in an stochastic input to Metropolis function.

So this is my model:

import numpy as np
import pymc
lambd=1;
__all__=['alpha']
alpha=pymc.Exponential('alpha', beta=lambd)

@pymc.stochastic(plot=False)
def logalpha(value=0,c=alpha):
    return np.log(c)

回答1:


log alpha is a deterministic function of your alpha, so you should model it as @deterministic. A good toy example that mirrors your own problem is the regression example.




回答2:


As @Max already mentioned, logalpha should be a deterministic variable, since it's value is uniquely determined by alpha. Whenever your model is sampled, the value of logalpha will be updated accordingly. For example:

>>> import numpy as np
>>> import pymc
>>> lambd = 1
>>> 
>>> alpha = pymc.Exponential('alpha', beta=lambd)
>>> 
>>> @pymc.deterministic(plot=False)
... def logalpha(value=0, c=alpha):
...     return np.log(c)
... 
>>> M = pymc.Model([alpha, logalpha])
>>> for i in range(3):
...     M.draw_from_prior()
...     print (alpha.value, logalpha.value)
... 
(array(1.888410537018971), 0.63573548954043602)
(array(0.23180935966225977), -1.4618399707110767)
(array(0.3381518219555991), -1.0842603069656513)


来源:https://stackoverflow.com/questions/19428338/how-to-implement-a-function-of-a-random-variable-in-pymc-which-could-be-sampled

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