/
Bayesian_Network_Construct.py
75 lines (55 loc) · 1.94 KB
/
Bayesian_Network_Construct.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
import pandas as pd
import numpy as np
import Read_Data as RD
from pomegranate import BayesianNetwork
def transfer(data, bounds, num_features, nominal_feature):
size = data.shape[0]
for k in range(size):
initial_sample = data[k, :]
z = np.linspace(0, 0, num_features)
for ii in range(num_features):
if ii not in nominal_feature:
z[ii] = np.max(np.where(bounds[:, ii] <= initial_sample[ii])[0])
if z[ii] > 99:
z[ii] -= 1
else:
z[ii] = initial_sample[ii]
data[k, :] = z
file = 'High_IR_Data/shuttle-2_vs_5.dat'
name = file.split('.')[0]
print(name)
RD.Initialize_Data(file)
print('Number of Positive: ', RD.Num_positive)
print('Number of Negative: ', RD.Num_negative)
nominal_feature = []
data = RD.get_feature()
num_samples = data.shape[0]
num_features = data.shape[1]
num_bins = 100
bounds = np.zeros((num_bins+1, num_features))
for i in range(num_features):
if i not in nominal_feature:
bounds[:, i] = np.histogram(data[:, i], bins=num_bins)[1]
nf = RD.get_negative_feature()
transfer(nf, bounds, num_features, nominal_feature)
pf = RD.get_positive_feature()
transfer(pf, bounds, num_features, nominal_feature)
bayes = BayesianNetwork.from_samples(nf, algorithm='chow-liu')
pt = bayes.log_probability(nf).sum()
print('Chow-Liu', pt)
'''
bayes = BayesianNetwork.from_samples(nf, algorithm='exact-dp')
pt = bayes.log_probability(nf).sum()
print('Exact Shortest:', pt)
bayes = BayesianNetwork.from_samples(nf, algorithm='exact') # Error
pt = bayes.log_probability(nf).sum()
print('Exact A*', pt)
bayes = BayesianNetwork.from_samples(nf, algorithm='greedy')
pt = bayes.log_probability(nf).sum()
print('Greedy', pt)
bayes = BayesianNetwork.from_samples(nf, algorithm='chow-liu')
pt = bayes.log_probability(nf).sum()
print('Chow-Liu', pt)
'''
with open(name+'_bayes_chow-liu.json', 'w') as w:
w.write(bayes.to_json())