<< Click to Display Table of Contents >> Navigation: Tutorials > Tutorial 2: Inference with a Bayesian Network |
Tutorial 2 begins with the model we have previously created. We will perform multiple calls to Bayesian inference algorithm through the Network.updateBeliefs, starting with network without any evidence. After each updateBeliefs call the posterior probabilities of nodes will be displayed.
The model is loaded with the Network.readFile.
Java:
Java:
net.readFile("tutorial1.xdsl");
Python:
net.read_file("tutorial1.xdsl");
C#:
net.ReadFile("tutorial1.xdsl");
We update the probabilities and proceed to display them using the helper method printAllPosteriors defined in this tutorial.
Java:
printf("Posteriors with no evidence set:\n");
net.updateBeliefs();
printAllPosteriors(net);
Python:
print("Posteriors with no evidence set:")
net.update_beliefs()
self.print_all_posteriors(net)
C#:
Console.WriteLine("Posteriors with no evidence set:");
net.UpdateBeliefs();
PrintAllPosteriors(net);
printAllPosteriors displays posterior probabilities calculated by updateBeliefs for each node. To iterate over the nodes, Network.getFirstNode and getNextNode are used. In the body of the loop we call another helper function, printPosteriors.
Java:
for (int h = net.getFirstNode(); h >= 0; h = net.getNextNode(h)) {
printPosteriors(net, h);
}
Python:
handle = net.get_first_node()
while (handle >= 0):
self.print_posteriors(net, handle)
handle = net.get_next_node(handle)
C#:
for (int h = net.GetFirstNode(); h >= 0; h = net.GetNextNode(h))
{
PrintPosteriors(net, h);
}
printPosteriors checks if node has evidence set by calling Network.isEvidence; if this is the case the name of the evidence state is displayed. Please note that for demonstration purposes this tutorial calls Network.getEvidence to obtain an integer representing the index of the evidence state, then converts the integer index to outcome id with Network.getOutcomeId. The Network.getEvidenceId method combines these two actions into one call.
If node is does not have any evidence set, printPosteriors iterates over all states and displays the posterior probability of each.
Back in the main function of the tutorial, we repeatedly call changeEvidenceAndUpdate helper function to change evidence, update network and display posteriors. Note that we need to call different methods of the Network class to set evidence to the specified outcome (setEvidence) and remove the evidence (clearEvidence).