使用pymc3定义随机和确定性变量

1 投票
1 回答
2894 浏览
提问于 2025-04-18 18:44

我正在尝试在pymc3中自己写一些随机确定性变量,但之前在pymc2.3上发布的老方法已经不适用了。比如,我尝试使用这种直接的方法,但失败了:

def x_logp(value, x_l, x_h):
    if ((value>x_h) or (value<x_l)):
        return -np.inf
    else:
        return -np.log(x_h-x_l+1)
def x_rand(x_l,x_h):
    return np.round((x_h-x_l)*np.random.random_sample())+x_l

Xpos=pm.stochastic(logp=x_logp,
                   doc="X position of halo center ",
                   observed=False, 
                   trace=True,
                   name='Xpos',
                   random=x_rand,
                   value=25.32,
                   parents={'x_l':0,'x_h'=500},
                   dtype=float64,
                   plot=True,
                   verbose=0)

我收到了以下错误信息:

ERROR: AttributeError: 'module' object has no attribute 'Stochastic' [unknown]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'Stochastic'

我想知道在pymc3中,如何定义我自己的先验分布或似然函数,而不使用装饰器和现有的pymc分布?

1 个回答

4

添加自定义密度的方法主要有两种:

  1. 使用Theano表达式(可以使用基于梯度的采样器)

    你可以用DensityDist来实现,比如说:

    https://github.com/pymc-devs/pymc/blob/master/pymc/examples/custom_dists.py

  2. 使用黑箱Python函数(只能用非梯度的采样器,比如Metropolis或Slice)

    Theano有一个装饰器可以这样使用:


@theano.compile.ops.as_op(itypes=[t.lscalar, t.dscalar, t.dscalar],otypes=[t.dvector])
def rate(switchpoint,early_mean, late_mean):
    ''' Concatenate Poisson means '''
    out = empty(years)
    out[:switchpoint] = early_mean
    out[switchpoint:] = late_mean
    return out

这个例子取自这里:https://github.com/pymc-devs/pymc/blob/master/pymc/examples/disaster_model_arbitrary_determinisitc.py

确定性变量可以通过直接组合随机变量来实现,或者如果你想让它们在追踪中显示,可以使用例如pm.Determinstic('sum', alpha + beta)

撰写回答