Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
408 changes: 204 additions & 204 deletions .gitignore

Large diffs are not rendered by default.

374 changes: 356 additions & 18 deletions BNReasoner.py

Large diffs are not rendered by default.

456 changes: 228 additions & 228 deletions BayesNet.py

Large diffs are not rendered by default.

Binary file added MAP.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added MPE.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
64 changes: 64 additions & 0 deletions Part2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
from BNReasoner import BNReasoner
from BayesNet import BayesNet
import pandas as pd
import time
import os
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)

def main(folder_name, output_folder):
node_counts = range(10, 51, 2)
random_list = []
md_list = []
mf_list = []
random_list2 = []
md_list2 = []
mf_list2 = []

for node_count in node_counts:
net = folder_name +"/network_"+str(node_count)+".XMLBIF"
bn = BayesNet()
bn.load_from_bifxml(net)
bnr = BNReasoner(bn)
print(node_count)
methods = ['random', 'min_degree', 'min_fill']
variable_list = bn.get_all_variables()

for method in methods:
start = time.time()
outcome_mpe = bnr.MPE(pd.Series({variable_list[-1]: True, variable_list[-2]: True}),method)
end = time.time()
total_time = end - start
if(method == 'random'):
random_list.append(total_time)
elif(method == 'min_degree'):
md_list.append(total_time)
elif(method == 'min_fill'):
mf_list.append(total_time)

start = time.time()
outcome_map = bnr.MAP([variable_list[0], variable_list[1]], pd.Series({variable_list[-1]: True,variable_list[-2]: True}),method)
end = time.time()
total_time = end - start

if(method == 'random'):
random_list2.append(total_time)
elif(method == 'min_degree'):
md_list2.append(total_time)
elif(method == 'min_fill'):
mf_list2.append(total_time)


df1 = pd.DataFrame({'Node_Count': node_counts, 'Random': random_list, 'MinDegree': md_list, 'MinFill': mf_list})
df2 = pd.DataFrame({'Node_Count': node_counts, 'Random': random_list2, 'MinDegree': md_list2, 'MinFill': mf_list2})


if not os.path.exists(output_folder):
os.makedirs(output_folder)
df1.to_excel(output_folder+'/MPE.xlsx', index=False)
df2.to_excel(output_folder+'/MAP.xlsx', index=False)

if __name__ == "__main__":
folder_name = "testing/Part_2"
output_folder = "Output"
main(folder_name, output_folder)
25 changes: 24 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
# Useful Pointers for Assignment 2 of KR21

######### How to run the code ############

# PART 1

1. Run "python test.py"
2. For all methods the condition is True. If you want to run for specific helper method then make the other varibles false.


# Part 2

1. generate_bn.py is used to create random baysian networks.
2. folder testing->Part_2 consists of random baysian network part 2 was tested on.
3. to run the script to get the runtime of MAP and MPE for 3 different heuristics, run "python Part2.py" which will dump 2 excel in output folder.

# Part 3

1. run "python use_case.py"





# Useful Pointers for Assignment 2 of KR21
## BIFXML file format
The BIFXML file format is meant to provide an easy means of exchanging Bayesian networks. It works with standard XML
tags. The detailed description of the format can be found at
Expand Down Expand Up @@ -88,3 +110,4 @@ Beware that the returned value is always a tuple of (row_number, row_content).
## Networkx methods
It is likely, that you will not have to use this package at all. One possible methods that could be useful is
`networkx.neighbors(G, var)` which provides a list of all neighbors of the variable 'var' in the graph 'G'.

29 changes: 29 additions & 0 deletions generate_bn.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# import networkx as nx
import numpy as np
from pgmpy.models import BayesianNetwork


# Set random seed for reproducibility
np.random.seed(123)

# Set the range of node numbers to generate networks for
start = 10
end = 50
skip = 3
node_counts = range(start, end+1, skip)

# Set the number of networks to generate for each node number
n_networks = 1

# Set the probability of an edge between any two nodes
edge_prob1 = 0.03

# Iterate over the range of node numbers
for n_node in node_counts:

# Iterate over the number of networks
for i in range(n_networks):

G = BayesianNetwork.get_random(n_nodes=n_node, edge_prob=edge_prob1, n_states=2)

G.save(f'testing/Part_2/network_{n_node}.XMLBIF', filetype='XMLBIF')
6 changes: 3 additions & 3 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
networkx~=2.6.3
matplotlib~=3.4.3
pgmpy~=0.1.16
networkx~=2.6.3
matplotlib~=3.4.3
pgmpy~=0.1.16
pandas~=1.3.4
158 changes: 158 additions & 0 deletions test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
from BNReasoner import BNReasoner
from BayesNet import BayesNet
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
import warnings
warnings.filterwarnings("ignore")

if __name__ == "__main__":

Pruning = True
check_d_separation = True
Independence = True
Marginalization = True
MaxingOut = True
FactorMultiplication = True
Ordering_min_degree = True
Ordering_min_fill = True
Elimination = True
Marginal_distribution = True
checkMAP = True
checkMEP = True

### Test pruning
if Pruning:
net = 'testing/lecture_example.BIFXML'
bn = BayesNet()
bn.load_from_bifxml(net)
bnr = BNReasoner(bn)
print("#----------------------------------------Pruning---------------------------------------#")
outcome = bnr.pruning(["Wet Grass?"],{'Rain?': False,'Winter?':True})
print(outcome)

### D-seperation
if check_d_separation:
net = 'testing/dog_problem.BIFXML'
bn = BayesNet()
bn.load_from_bifxml(net)
bnr = BNReasoner(bn)
#outcome_d_not = bnr.d_separation(["family-out"], ["hear-bark"], ["light-on"]) # Not seperated
print("#-----------------------------------------D-seperation---------------------------------#")
outcome_d = bnr.d_separation(["family-out"], ["bowel-problem"], ["light-on"]) # Seperated

print(outcome_d)

## Test independence
if Independence:
net = 'testing/lecture_example.BIFXML'
bn = BayesNet()
bn.load_from_bifxml(net)
bnr = BNReasoner(bn)
Y = {"Winter?"}
X = {"Slippery Road?"}
Z = {}
if bnr.check_independence(bnr.bn, X,Y,Z):
print("#--------------------------------Independence--------------------------------------#")
print(X, "is independent from ", Y, "given ", Z)
else:
print("#--------------------------------Independence--------------------------------------#")
print(X, "is not independent from ", Y, "given ", Z)

### Test marginalization
if Marginalization:
net = 'testing/lecture_example.BIFXML'
bn = BayesNet()
bn.load_from_bifxml(net)
bnr = BNReasoner(bn)
X = "Wet Grass?"
Y = BayesNet.get_cpt(bnr.bn,X)
outcome_marg = bnr.sum_out_factors(Y,X)
print("#-------------------------------Marginalization--------------------------------------#")
print(outcome_marg)

### Test maxing out
if MaxingOut:
net = 'testing/lecture_example.BIFXML'
bn = BayesNet()
bn.load_from_bifxml(net)
bnr = BNReasoner(bn)
X = "Wet Grass?"
Y = BayesNet.get_cpt(bnr.bn,X)
outcome_max = bnr.maximise_out(Y,X)
print("#-------------------------------Maxing out-------------------------------------------#")
print(outcome_max)

### Test factor multiplication
if FactorMultiplication:
net = 'testing/lecture_example.BIFXML'
bn = BayesNet()
bn.load_from_bifxml(net)
bnr = BNReasoner(bn)
outcome_factor = bnr.factor_multiplication(['Rain?', 'Wet Grass?'])
print("#-------------------------------Factor multiplication-------------------------------#")
print(outcome_factor)

### Test ordering min
if Ordering_min_degree:
net = 'testing/lecture_example.BIFXML'
bn = BayesNet()
bn.load_from_bifxml(net)
bnr = BNReasoner(bn)
outcome_min_degree = bnr.min_degree()
print("#-------------------------------Ordering min degree----------------------------------#")
print(outcome_min_degree)


### Test ordering min fill
if Ordering_min_fill:
net = 'testing/lecture_example.BIFXML'
bn = BayesNet()
bn.load_from_bifxml(net)
bnr = BNReasoner(bn)
outcome_min_fill = bnr.min_fill()
print("#--------------------------------Ordering min fill----------------------------------#")
print(outcome_min_fill)

### Elimination
if Elimination:
net = 'testing/lecture_example.BIFXML'
bn = BayesNet()
bn.load_from_bifxml(net)
bnr = BNReasoner(bn)
outcome_elim = bnr.elimination(bn.get_cpt('Wet Grass?'), ['Rain?'])
print("#-------------------------------Elimination---------------------------------------#")
print(outcome_elim)

### Marginal distribution
if Marginal_distribution:
net = 'testing/lecture_example.BIFXML'
bn = BayesNet()
bn.load_from_bifxml(net)
bnr = BNReasoner(bn)
outcome_md = bnr.compute_marginal(['Wet Grass?', 'Slippery Road?'], order=bnr.min_degree())
print("#-------------------------------Marginal distribution-----------------------------#")
print(outcome_md)

### MAP
if checkMAP:
net = 'testing/lecture_example2.BIFXML'
bn = BayesNet()
bn.load_from_bifxml(net)
bnr = BNReasoner(bn)
outcome_map = bnr.MAP(['I', 'J'], pd.Series({'O': True}))
print("#-------------------------------------MAP-----------------------------------------#")
print(outcome_map)


## MPE
if checkMEP:
net = 'testing/lecture_example2.BIFXML'
bn = BayesNet()
bn.load_from_bifxml(net)
bnr = BNReasoner(net)
outcome_mpe = bnr.MPE(pd.Series({'J': True, 'O': False}))
print("#-------------------------------------MPE-----------------------------------------#")
print(outcome_mpe)

Loading