baffling error-handling problem

Chris Fonnesbeck fonnesbeck at gmail.com
Thu Jul 28 10:11:07 EDT 2005


I thought I knew how to do error handling in python, but apparently I
dont. I have a bunch of code to calculate statistical likelihoods, and
use error handling to catch invalid parameters. For example, for the
bernoulli distribution, I have:

    def bernoulli_like(self, x, p, name='bernoulli'):
        """Bernoulli log-likelihood"""

        # Ensure proper dimensionality of parameters
        dim = shape(x)
        p = resize(p,dim)

        # Ensure valid values of parameters
        if sum(p>=1 or p<=0): raise LikelihoodError

        ... etc.

where LikelihoodError is simply a subclass of ValueError that I created:

    class LikelihoodError(ValueError):
        "Log-likelihood is invalid or negative infinite"


I catch these errors with the following:

        try:
            like = self.calculate_likelihood()
        except LikelihoodError:
            return 0

So far, so good. When I calculate_likelihood is called in the above,
which contains a call to bernoulli_like:
           
            p = invlogit(beta0 + sum([b*h for b,h in zip(self.beta,hab)]))    
            
            like=self.bernoulli_like(x,p)

I get the following when an invalid parameter is passed:

Traceback (most recent call last):
  File "C:\Conroy\working\resource_selection_ms\analyses\IIbq\sampled\new_chris\model_000.py",
line 381, in ?
    model.sample(iterations=iter, burn=burn,plot=False)
  File "C:\Python23\Lib\site-packages\PyMC\MCMC.py", line 1691, in sample
    self._like = self.calculate_likelihood()
  File "C:\Conroy\working\resource_selection_ms\analyses\IIbq\sampled\new_chris\model_000.py",
line 194, in calculate_likelihood
    like+=self.bernoulli_like(x,p)
  File "C:\Python23\Lib\site-packages\PyMC\MCMC.py", line 868, in bernoulli_like
    if sum(p>=1 or p<=0): raise LikelihoodError
LikelihoodError


I have no idea how this can happen, given how I have coded this.
Anyone see what I must be missing?

Thanks,
C.



More information about the Python-list mailing list