tarefa2.py
1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from pgmpy.readwrite import BIFReader
import networkx as nx
import pydot
from networkx.drawing.nx_pydot import graphviz_layout
from bninput import *
def get_yes_probabilities(model):
nodes = model.nodes()
yes_probabilities = {}
for node in nodes:
cpd = model.get_cpds(node)
state_names = cpd.state_names[node]
yes_index = state_names.index("yes")
yes_prob = cpd.values[yes_index]
yes_probabilities[node] = yes_prob
return yes_probabilities
if __name__ == "__main__":
summary = summary_dag("asia2.bif")
model = summary["bnmodel"]
probabilities = get_yes_probabilities(model)
for node, yes_prob in probabilities.items():
parents = model.get_parents(node)
s = ""
if len(parents) == 0:
s += str(yes_prob) + " :: " + str(node) +"\n"
print(s)
elif len(parents) == 1:
p = parents[0]
s += str(yes_prob[0]) + " :: " + str(node) + " <- " + str(p) + "\n"
s += str(yes_prob[1]) + " :: " + str(node) + " <- -" + str(p) + "\n"
print(s)
else:
yes1 = yes_prob[0]
yes2 = yes_prob[1]
p0 = parents[0]
p1 = parents[1]
s += str(yes1[0]) + " :: " + str(node) + " <- " + str(p0) + ", " + str(p1) + "\n"
s += str(yes2[0]) + " :: " + str(node) + " <- -" + str(p0) + ", " + str(p1) + "\n"
s += str(yes1[1]) + " :: " + str(node) + " <- " + str(p0) + ", -" + str(p1) + "\n"
s += str(yes2[1]) + " :: " + str(node) + " <- -" + str(p0) + ", -" + str(p1) + "\n"
print(s)