C Sharp Tutorial Code 2: Performing Inference with a Bayesian Network

From DSL
Jump to: navigation, search
public void InfereceWithBayesianNetwork() {
 try {
   Network net = 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:
   String[] aForecastOutcomeIds = net.GetOutcomeIds("Forecast");
   int outcomeIndex;
   for (outcomeIndex = 0; outcomeIndex < aForecastOutcomeIds.Length; outcomeIndex++)
     if ("Moderate".Equals(aForecastOutcomeIds[outcomeIndex]))
       break;
   
   // Getting the value of the probability:
   double[] aValues = net.GetNodeValue("Forecast");
   double P_ForecastIsModerate = aValues[outcomeIndex];
   
   Console.WriteLine("P(\"Forecast\" = Moderate) = " + P_ForecastIsModerate);
   
   
   // ---- 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:
   String[] aSuccessOutcomeIds = net.GetOutcomeIds("Success");
   for (outcomeIndex = 0; outcomeIndex < aSuccessOutcomeIds.Length; outcomeIndex++)
     if ("Failure".Equals(aSuccessOutcomeIds[outcomeIndex]))
       break;
   
   // Getting the value of the probability:
   aValues = net.GetNodeValue("Success");
   double P_SuccIsFailGivenForeIsGood = aValues[outcomeIndex];
   
   Console.WriteLine("P(\"Success\" = Failure | \"Forecast\" = Good) = " + P_SuccIsFailGivenForeIsGood);
   
   
   // ---- 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; outcomeIndex < aSuccessOutcomeIds.Length; outcomeIndex++)
     if ("Failure".Equals(aSuccessOutcomeIds[outcomeIndex]))
       break;
   
   // Getting the value of the probability:
   aValues = net.GetNodeValue("Success");
   double P_SuccIsSuccGivenForeIsPoor = aValues[outcomeIndex];
   
   Console.WriteLine("P(\"Success\" = Success | \"Forecast\" = Poor) = " + P_SuccIsSuccGivenForeIsPoor);
 }
 catch (SmileException e) {
   Console.WriteLine(e.Message);
 }
}
Personal tools