forked from ligerfotis/BayesianStructureStructureLearning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
structure_learning.py
79 lines (45 loc) · 1.35 KB
/
structure_learning.py
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import pandas as pd
import os
data = pd.read_csv("final_data.csv")
from pgmpy.estimators import BicScore,BdeuScore,ExhaustiveSearch,HillClimbSearch
est = HillClimbSearch(data, scoring_method=BdeuScore(data, equivalent_sample_size=10))
best_model = est.estimate()
print("Structure found!")
print("Best Model")
print(best_model.edges())
'''
Parameters Estimation and CPD tables
'''
from pgmpy.models import BayesianModel
from pgmpy.estimators import BayesianEstimator
model = BayesianModel(best_model.edges())
data = pd.read_csv("final_training_set.csv")
estimator = BayesianEstimator(model, data)
parameters = estimator.get_parameters(prior_type='BDeu', equivalent_sample_size=10)
for cpd in parameters:
model.add_cpds(cpd)
'''
Inference and Validation
'''
from pgmpy.inference import VariableElimination
import csv
f = open("validation_data.csv")
reader = csv.reader(f)
inference = VariableElimination(model)
valid=0
invalid=0
for row in reader:
br=row[3]
ig=row[1]
#map_quey returns Dictionary!!!
if int(row[0])==inference.map_query(["SC"], evidence={"BR": int(br)})["SC"]:
valid+=1
else:
invalid+=1
total=valid+invalid
print(valid)
print(invalid)
accuracy = float(valid/total)
print("Accuracy: ", accuracy)
f.close()
os.system('spd-say -i -10 -p 50 -t female3 "Training Finished!"')