I’m trying to implement the simple probabilistic programs from one of the white-papers of probabilistic programming. I ran into an issue for the cases including a while loop which will run forever, see both Example 3 and 4 from page two (fig two) in the paper above. The specific code below is for Example 3.
I am not using any underlying data(set), but solely interested in the kind of distributions that will be produced, and look into seeing patterns in the running time (and yes, this particular example could easily be calculated in R).
So here is what I tried:
# both theano functions are probably not needed, but did it for debugging
@theano.compile.ops.as_op(itypes=[tt.lscalar,tt.lscalar], otypes=[tt.lscalar])
def c_addition(c1,c2):
print(c1,c2,c1+c2)
return c1+c2
@theano.compile.ops.as_op(itypes=[tt.lscalar], otypes=[tt.lscalar])
def c_above_0(count):
return count < 1
with pm.Model() as model:
c1 = pm.Bernoulli('c1',p=0.5)
c2 = pm.Bernoulli('c2',p=0.5)
count = c_addition(c1,c2) # could just run c1+c2, but doing this explictly for debugging
z = pm.Deterministic('z', c1+c2)
iterr = 1
while c_above_0(count): # should be the same as `while count < 1:`
count = 0
c1 = pm.Bernoulli(f'c1{iterr}',p=0.5)
c2 = pm.Bernoulli(f'c2{iterr}',p=0.5)
count = c_addition(c1,c2)
z = pm.Deterministic(f'z{iterr}', c1+c2)
iterr +=1
step1 = pm.Metropolis([c1,c2,z])
trace2 = pm.sample(samples,return_inferencedata=0,step= step1)
Firstly, sorry if this is ugly code. So first thing, is that it gave errors when there were variables with the same name, so I had to use an f-string syntax. I believe this somehow ties together with the below, as I could imagine one shouldn’t initialize the variable several times.
Second (and actual issue), when it came to sampling it will just run forever, because the while loop condition will evaluate to true every time, because (I think) both c1 and c2 will start at 0 each time, and is reset for every while loop call. This is at least what it looked like with the print statement.
So the question is: How would I fix this?