# What's wrong with my sprinkler/rain code (Migrated from community.research.microsoft.com)

• ### Question

• nxtruong_ac posted on 12-16-2010 7:48 PM

Hi all,

I'm learning infer.NET. I wrote an IronPython program for the sprinkler/rain example by Kevin Murphy (webpage,  following this C# code).  The Python code is as given below.  The problem is that the result is very wrong: S|W=T is Bernoulli(0.8333) and R|W=T is Bernoulli(0.3333), while the correct result should be 0.430 and 0.708 respectively.  I know it is approximated, but it's too far from the exact result.  What's wrong in my code?

BTW, I used Infer.NET 2.4 beta with .NET 4, VS 2010, on Windows 7 running inside a VMWare virtual machine.

Thanks,

Truong

######################

import System
from System import *
import clr

import sys
sys.path.append(r'C:\Program Files\Microsoft Research\Infer.NET 2.4 Beta\bin\Release')

# import all namespaces
import MicrosoftResearch.Infer
import MicrosoftResearch.Infer.Models
import MicrosoftResearch.Infer.Distributions
from MicrosoftResearch.Infer import *
from MicrosoftResearch.Infer.Models import *
from MicrosoftResearch.Infer.Distributions import *

##### The model
C = Variable.Bernoulli(0.5).Named("Cloudy")  # cloudy variable

# sprinkler & rain conditioned on C
with (Variable.If(C)):
S = Variable.Bernoulli(0.1)
R = Variable.Bernoulli(0.8)
with (Variable.IfNot(C)):
S = Variable.Bernoulli(0.5)
R = Variable.Bernoulli(0.2)

# wet grass
with (Variable.If(S)):
with (Variable.If(R)):
W = Variable.Bernoulli(0.99)
with (Variable.IfNot(R)):
W = Variable.Bernoulli(0.9)
with (Variable.IfNot(S)):
with (Variable.If(R)):
W = Variable.Bernoulli(0.9)
with (Variable.IfNot(R)):
W = Variable.Bernoulli(0.0)

## The inference
ie = InferenceEngine()
# ie.NumberOfIterations = 1000
W.ObservedValue = True
print "Probability of Sprinkler given Wet = True:", ie.Infer(S)
print "Probability of Rain given Wet = True:", ie.Infer(R)

Friday, June 3, 2011 6:10 PM

• nxtruong_ac replied on 12-17-2010 10:28 AM

It works perfectly.  Thank you!

Friday, June 3, 2011 6:10 PM

### All replies

• John Guiver replied on 12-17-2010 3:31 AM

You can do a direct translation of the C# code to the IronPython code, and it should work.  Specifically, note that

(a) you have not defined S, R, and W outside the with statements

(b) You have not used the SetTo method within the with loops.

For (a), you need:

S = Variable.New[bool]()
R = Variable.New[bool]()
W = Variable.New[bool]()

For (b) please see the section in the user guide on the importance of using SetTo which explains the need for this construct. You will need

S.SetTo(Variable.Bernoulli(0.1))
etc.

Friday, June 3, 2011 6:10 PM
• nxtruong_ac replied on 12-17-2010 10:28 AM

It works perfectly.  Thank you!

Friday, June 3, 2011 6:10 PM