Using CustomDist in Gluten Sensitivity Example from Think Bayes 2

Hi,

I was trying to implement gluten sensitivity example from Think bayes 2. See here for details. I think it should be implemented using CustomDist like this

def my_dist(n_sensitive: TensorVariable, size: TensorVariable) -> TensorVariable:
  n_insensitive = 35-n_sensitive
  n1 = pm.Binomial.dist(n=n_sensitive,p=0.95,size=size)
  n2 = pm.Binomial.dist(n=n_insensitive,p=0.4,size=size)
  return n1+n2
  
with pm.Model() as model:
  sensitive = pm.DiscreteUniform(name="n_sensitive",lower=0,upper=35)
  total = pm.CustomDist("total",sensitive,dist=my_dist,observed=12)

  prior = pm.sample_prior_predictive()
  posterior = pm.sample()

but that fails:
The logprob terms of the following value variables could not be derived: {TensorConstant(TensorType(int64, shape=()), data=array(12))}

Returning only n1 or n2 works or if I comment last line. “Works” means that no error given.

Any ideas how to proceed?

br,

H

PyMC doesn’t know how to compute convolutions of random variables (yet!) – this is why you are getting an error when you try to add n1 + n2. Remember that addition of random variables is convolution.

In your specific case, you end up with a poisson-binomal distribution. This discussion is relevant.

Thanks for the really quick answer. This turns out to be more complex exercise than first expected :man_facepalming: