Hi guys, I’m very new to pyro and PPL. I have a question on how to make the pyro generate the conditional probability.
So, I’m trying to replicate this
int the terms of pyro code. I have found a thread which explained how to do it here
So I was following the code provided by fehiepsi and it seems going well
I was able to generate the conditional probability of P(grasswet|rain,sprinkler). But when I try to generate P(rain|grasswet,sprinkler) , the error occurs.
Here are the code I used to generate P(grasswet|rain,sprinkler)
import torch
import pyro
import pyro.distributions as dist
@pyro.infer.config_enumerate
def model(rain = None,sprinkler=None,grasswet=None):
rain = pyro.sample('rain', dist.Bernoulli(0.2))
sprinkler = pyro.sample('sprinkler',dist.Bernoulli(0.4)) if rain.bool() else
pyro.sample('sprinkler',dist.Bernoulli(0.01))
if (sprinkler == 0. and rain == 0.):
pyro.sample('grasswet',dist.Bernoulli(0.), obs = grasswet)
elif (sprinkler == 0. and rain == 1.):
pyro.sample('grasswet',dist.Bernoulli(0.8), obs = grasswet)
elif (sprinkler == 1. and rain == 0.):
pyro.sample('grasswet',dist.Bernoulli(0.9), obs = grasswet)
else:
pyro.sample('grasswet',dist.Bernoulli(0.99), obs = grasswet)
This above chunk defines the model
p_r_s_g = pyro.do(model, data={'rain': torch.tensor(0.),'sprinkler': torch.tensor(0.)})
p_r_s_g_enum = pyro.poutine.enum(p_r_s_g, first_available_dim=-1)
trace = pyro.poutine.trace(p_r_s_g_enum).get_trace( grasswet=torch.tensor(0.) )
trace1 = pyro.poutine.trace(p_r_s_g_enum).get_trace( grasswet=torch.tensor(1.) )
log_prob_evaluate = pyro.infer.mcmc.util.TraceEinsumEvaluator(
trace, has_enumerable_sites=True, max_plate_nesting=1)
print("p(grasswet=F|rain=F,sprinkler=F):", log_prob_evaluate.log_prob(trace).exp())
print("p(grasswet=T|rain=F,sprinkler=F):", log_prob_evaluate.log_prob(trace1).exp())
This chunk generates the conditional probability value.
But when I try to change the parameters, the error occurs.
The code is below
p_r_s_g = pyro.do(model, data={'grasswet':
torch.tensor(0.),'sprinkler':torch.tensor(0.)})
p_r_s_g_enum = pyro.poutine.enum(p_r_s_g, first_available_dim=-1)
trace = pyro.poutine.trace(p_r_s_g_enum).get_trace( rain =torch.tensor(0.) )
trace1 = pyro.poutine.trace(p_r_s_g_enum).get_trace( rain =torch.tensor(1.) )
log_prob_evaluate = pyro.infer.mcmc.util.TraceEinsumEvaluator(
trace, has_enumerable_sites=True, max_plate_nesting=1)
print("p(rain=F|grasswet=F,sprinkler=F):", log_prob_evaluate.log_prob(trace).exp())
print("p(rain=T|grasswet=F,sprinkler=F):", log_prob_evaluate.log_prob(trace1).exp())
The error said
bool value of Tensor with more than one value is ambiguous
Trace Shapes:
Param Sites:
Sample Sites:
rain dist |
value 2 |
I am thinking if this has to do with Plate and enumeration as mentioned here but I don’t know why this if-else wouldn’t work.