PyMC @observed decorator计算的log-probability不能转换为float错误

时间:2015-01-09 23:28:13

标签: pymc

我在将自定义@stochasitc变量切换到PyMC中的@observed变量时遇到了一些麻烦。我有一个随机变量设置如下:

def age_logp(age):
    if age < 0 or age > 110:
        return -np.inf
    elif 0 <= age < 20:
        prob = age_dist['0-20']
    elif 20 <= age < 40:
        prob = age_dist['20-40']
    elif 40 <= age < 60:
        prob = age_dist['40-60']
    elif 60 <= age < 80:
        prob = age_dist['60-80']
    elif age >= 80:
        prob = age_dist['80-inf']
    return np.log(prob)


@pymc.stochastic
def age(value=0):
    def logp(value):
        return age_logp(value)

如何将其切换为观察变量?到目前为止我试过这个:

@pymc.observed
def age(value=np.array([12, 43, 28, 39, 87, 26])):
    return map(age_logp, value)

但我得到TypeError: age: computed log-probability [-1.639897119918809, -1.3394107752210402, -1.0876723486297752, -1.0876723486297752, -3.1235656450638758, -1.0876723486297752] cannot be cast to float

如何扩展age以获取一系列观察值?

1 个答案:

答案 0 :(得分:3)

你已经把事情做得恰到好处,但是如果你想将多个观察值建模为独立的,你可以在联合对数似然中对它们求和:

@pymc.observed
def age(value=np.array([12, 43, 28, 39, 87, 26])):
    return sum(map(age_logp, value))

如果您愿意,可以将它们组合起来。关键是age应该返回一个标量值。