Search code examples
pymc

PyMC @observed decorator computed log-probability cannot be cast to float error


I am having a little trouble switching a custom @stochasitc variable to an @observed variable in PyMC. I have a stochastic variable set up like this:

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)

How do I switch this to an observed variable? I've tried this so far:

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

But I get TypeError: age: computed log-probability [-1.639897119918809, -1.3394107752210402, -1.0876723486297752, -1.0876723486297752, -3.1235656450638758, -1.0876723486297752] cannot be cast to float

How do I extend age to take an array of observed values?


Solution

  • You've switched things just right, but if you want to model multiple observed values as independent, you can sum them in the joint log-likelihood:

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

    You can combine them some other way if you prefer. The key is that age should return a scalar value.