Search code examples
bayesianpymcpymc3

Conditional prior in PyMC3


I am trying to build a model in which the prior assigned to a distribution is contingent on a particular value, and that value is another variable that is sampled. For example, a student answering a question correctly is modeled according to a Bernoulli trial with probability p. If the student has the given prerequisites (themselves part of the model), p should be drawn from Beta(20,5). If not, p should be drawn from Beta(5,20).

I got this to work in PyMC2 with the following code:

# prior for thetas - same for all students
lambda1 = pymc.Beta('lambda1',alpha=20,beta=5) 
#top-level node - one for each student
theta1 = []
for i in range(num_students):
    theta1.append(pymc.Bernoulli('theta1_%i' % i, p=lambda1, plot=False))

lambda2 = [
    pymc.Beta('lambda2_0', alpha=5,beta=20),
    pymc.Beta('lambda2_1', alpha=20,beta=5)
]
lambda2_choices = []
theta2 = []
for i in range(num_students):
    @pymc.deterministic(name='lambda2_choice_%i'%(i), plot=False)
    def lambda2_choice(theta1 = theta1[i],
                     lambda2 = lambda2):
        if theta1 == False:
            return lambda2[0]
        elif theta1 == True:
            return lambda2[1]
    lambda2_choices.append(lambda2_choice) 
    theta2.append(pymc.Bernoulli('theta2_%i' % i,p=lambda2_choice))    

In other words, the prior assigned to the Bernoulli random variable is a deterministic function that returns a stochastic variable depending on the SAMPLED value of some other value, in this case theta1[i].

I can't figure out how to do this in PyMC3, as the @deterministic decorator no longer exists and deterministic functions have to have input/output as Theano variables.

I'd really appreciate any insight or suggestions!!


Solution

  • Here you can use:

    pymc3.switch(theta[i], lambda2[1], lambda2[0])