VB.NET Tutorial Code 2: Performing Inference with a Bayesian Network

From DSL
Jump to: navigation, search
Public Sub InfereceWithBayesianNetwork()
 Try
   Dim net As New Network()
   net.ReadFile("tutorial_a.xdsl")
   
   
   ' ---- We want to compute P("Forecast" = Moderate) ----
   Updating the network:
   net.UpdateBeliefs()
   
   ' Getting the index of the "Moderate" outcome:
   Dim aForecastOutcomeIds() As String = net.GetOutcomeIds("Forecast")
   Dim outcomeIndex As Integer
   For outcomeIndex = 0 To aForecastOutcomeIds.Length - 1
     If ("Moderate".Equals(aForecastOutcomeIds(outcomeIndex))) Then
       Exit For
     End If
   Next
   
   ' Getting the value of the probability:
   Dim aValues() As Double = net.GetNodeValue("Forecast")
   Dim P_ForecastIsModerate As Double = aValues(outcomeIndex)
   
   Console.WriteLine("P(""Forecast"" = Moderate) = " + P_ForecastIsModerate.ToString())
   
   
   ' ---- We want to compute P("Success" = Failure | "Forecast" = Good) ----
   ' Introducing the evidence in node "Forecast":
   net.SetEvidence("Forecast", "Good")
   
   ' Updating the network:
   net.UpdateBeliefs()
   
   ' Getting the index of the "Failure" outcome:
   Dim aSuccessOutcomeIds() AS String = net.GetOutcomeIds("Success")
   For outcomeIndex = 0 To aSuccessOutcomeIds.Length - 1
     If ("Failure".Equals(aSuccessOutcomeIds(outcomeIndex))) Then
       Exit For
     End If
   Next
   
   ' Getting the value of the probability:
   aValues = net.GetNodeValue("Success")
   Dim P_SuccIsFailGivenForeIsGood As Double = aValues(outcomeIndex)
   
   Console.WriteLine("P(""Success"" = Failure | ""Forecast"" = Good) = " + 

P_SuccIsFailGivenForeIsGood.ToString())


   ' ---- We want to compute P("Success" = Success | "Forecast" = Poor) ----
   ' Clearing the evidence in node "Forecast":
   net.ClearEvidence("Forecast")
   
   ' Introducing the evidence in node "Forecast":
   net.SetEvidence("Forecast", "Good")
   
   ' Updating the network:
   net.UpdateBeliefs()
   
   ' Getting the index of the "Failure" outcome:
   aSuccessOutcomeIds = net.GetOutcomeIds("Success")
   For outcomeIndex = 0 To aSuccessOutcomeIds.Length - 1
     If ("Failure".Equals(aSuccessOutcomeIds(outcomeIndex))) Then
       Exit For
     End If
   Next
   
   ' Getting the value of the probability:
   aValues = net.GetNodeValue("Success")
   Dim P_SuccIsSuccGivenForeIsPoor As Double = aValues(outcomeIndex)
   
   Console.WriteLine("P(""Success"" = Success | ""Forecast"" = Poor) = " + 

P_SuccIsSuccGivenForeIsPoor.ToString())

 Catch e As SmileException
   Console.WriteLine(e.Message)
 End Try
End Sub
Personal tools