-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTAN.py
317 lines (208 loc) · 8.56 KB
/
TAN.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
import pyAgrum as gum
import pyAgrum.skbn as skbn
from sklearn.model_selection import KFold
import matplotlib
matplotlib.use('SVG')
def NB_TAN_k_fold_with_steps(jumpSteps, selection_parameter, dataset, class_var):
"""
Performs TAN classifier with k-fold cross-validation and visualization of the step-wise process.
Args:
jumpSteps (int): Number of steps to jump before recalculating weights and scores.
selection_parameter (str): Parameter for feature selection. Valid options: "Score" or "MI" (Mutual Information).
dataset (str): Path to the dataset file.
class_variable (str): The class variable of the classification problem.
Returns:
figures_list (list): List of tuples containing the figure, scores, and learned Bayesian network for each step.
"""
importr('utils')
importr('bnclassify')
figures_list = []
df_cars = pd.read_csv(dataset)
from rpy2.robjects import pandas2ri
from rpy2.robjects.conversion import localconverter
with localconverter(robjects.default_converter + pandas2ri.converter):
r_from_pd_df = robjects.conversion.py2rpy(df_cars)
robjects.globalenv['r_from_pd_df'] = r_from_pd_df
robjects.r('r_from_pd_df <- as.data.frame(unclass(r_from_pd_df), stringsAsFactors = TRUE)')
robjects.globalenv['class_variable'] = class_var
tan = robjects.r("bnc('nb',class_variable, r_from_pd_df, smooth= 0.01)")
robjects.globalenv["tan"] = tan
modelo = robjects.r('modelstring(tan)')[0]
class_var = robjects.r('class_var(tan)')[0]
features = list(robjects.r('features(tan)'))
#Graph construction
g = nx.DiGraph()
g.add_node(class_var)
g.add_nodes_from(features)
familia = robjects.r('families(tan)')
edges_class_var = []
rest_edges = []
for x in familia:
for i in range(1,len(x)):
g.add_edge(x[i],x[0])
if(x[i] == class_var):
edges_class_var.append((x[i],x[0]))
else:
rest_edges.append((x[i],x[0]))
distance = 0
fixed_distance = 0.25
fixed_distance_y = 0.5
features_pos = {}
for f in features:
features_pos[f] = (distance,0.25)
distance += fixed_distance
df = pd.read_csv(dataset)
df2 = pd.DataFrame()
a
g.clear()
def obtain_weight_features(features_list):
weight_list = []
for f in features_list:
order = "cmi('"+f+"','"+class_var+"', r_from_pd_df)"
weight = float(robjects.r(order)[0])
weight_list.append(weight)
return weight_list
weight_list = obtain_weight_features(features)
weight_list_aux = weight_list
features_list_aux = features
bn = gum.BayesNet()
df2[class_var] = df[class_var]
bn.add(class_var)
g.add_node(class_var)
nodes_added = []
distance = 0
fixed_distance = 0.25
fixed_distance_y = 0.5
features_pos = {}
steps_aux = jumpSteps
i=0
if len(df[class_var].unique()) == 2:
y = df[class_var].map({df[class_var].unique()[1]: True, df[class_var].unique()[0]: False})
else:
y = df[class_var]
while weight_list_aux:
index_max = np.argmax(weight_list_aux)
feature = features_list_aux.pop(index_max)
weight_list_aux.pop(index_max)
bn.add(feature)
df2[feature] = df[feature]
bn.addArc(class_var,feature)
g.add_edge(class_var, feature)
nodes_added.append(feature)
features_pos[feature] = (distance,0.25)
distance += fixed_distance
i+=1
if steps_aux == jumpSteps or not weight_list_aux:
steps_aux = 0
fig = plt.figure()
nx.draw_networkx_nodes(g,pos=features_pos,nodelist = nodes_added, node_size = 1500, margins= 0.2)
nx.draw_networkx_nodes(g,pos={class_var: ((distance-fixed_distance)/2,fixed_distance_y)},
nodelist=[class_var],node_color='#009900',node_size = 1500)
features_pos[class_var] = ((distance-fixed_distance)/2,fixed_distance_y)
nx.draw_networkx_labels(g, pos = features_pos, font_weight='bold', font_size = 5.5)
nx.draw_networkx_edges(g,features_pos,arrows = True, edgelist=[(class_var,node) for node in nodes_added],node_size = 1500)
kf = KFold(n_splits= 4,shuffle=True)
scores = []
for k in kf.split(df2):
df_train = df2.iloc[k[0]]
learner=gum.BNLearner(df_train)
learner.useSmoothingPrior()
bn2 = learner.learnParameters(bn.dag())
bnc=skbn.BNClassifier()
bnc.fromTrainedModel(bn2,targetAttribute=class_var)
yTest = y.iloc[k[1]]
scoreCSV1 = bnc.score(df.iloc[k[1]], y = yTest)
scores.append(scoreCSV1)
figures_list.append((fig, scores))
else:
steps_aux+=1
with localconverter(robjects.default_converter + pandas2ri.converter):
r_from_pd_df = robjects.conversion.py2rpy(df2)
robjects.globalenv['r_from_pd_df'] = r_from_pd_df
robjects.r('r_from_pd_df <- as.data.frame(unclass(r_from_pd_df), stringsAsFactors = TRUE)')
tan = robjects.r("bnc('tan_cl', class_variable , r_from_pd_df, smooth = 1, dag_args = list(score = 'aic'))")
robjects.globalenv["tan"] = tan
class_var = robjects.r('class_var(tan)')[0]
features = list(robjects.r('features(tan)'))
g = nx.DiGraph()
g.add_node(class_var)
g.add_nodes_from(features)
familia = robjects.r('families(tan)')
edges_class_var = []
rest_edges = []
for x in familia:
for i in range(1,len(x)):
g.add_edge(x[i],x[0])
if(x[i] == class_var):
edges_class_var.append((x[i],x[0]))
else:
rest_edges.append((x[i],x[0]))
def obtain_weight_edges(edges_list):
weight_list = []
for e in edges_list:
order = "cmi('"+e[0]+"','"+e[1]+"', z = '"+class_var+"', r_from_pd_df)"
weight = float(robjects.r(order)[0])
weight_list.append(weight)
return weight_list
edges = [k for k in g.edges if k[0]!=class_var]
edges_weights = obtain_weight_edges(edges)
index_max = np.argmax(edges_weights)
edges_weights_aux = edges_weights
#Añadir las aristas del Naive Bayes y crear la red bayesiana
g.clear_edges()
bn = gum.BayesNet()
for i in df2.columns:
#print(i)
bn.add(i)
for i in df2.columns:
if(i != class_var):
g.add_edge(class_var,i)
bn.addArc(class_var,i)
edges_added = []
steps_aux = jumpSteps
if len(df[class_var].unique()) == 2:
y = df[class_var].map({df[class_var].unique()[1]: True, df[class_var].unique()[0]: False})
else:
y = df[class_var]
while edges_weights_aux:
index_max = np.argmax(edges_weights_aux)
edge = edges.pop(index_max)
edges_weights_aux.pop(index_max)
bn.addArc(*edge)
g.add_edge(*edge)
edges_added.append(edge)
#Draw net
if steps_aux == jumpSteps or not edges_weights_aux:
steps_aux = 0
fig = plt.figure()
nx.draw_networkx_nodes(g,pos=features_pos,nodelist = features, node_size = 1500, margins= 0.2)
nx.draw_networkx_nodes(g,pos={class_var: ((distance-fixed_distance)/2,fixed_distance_y)},
nodelist=[class_var],node_color='#009900',node_size = 1500)
nx.draw_networkx_labels(g, pos = features_pos, font_weight='bold', font_size = 5.5)
nx.draw_networkx_edges(g,features_pos,arrows = True, edgelist=edges_class_var,node_size = 1500)
nx.draw_networkx_edges(g,features_pos,arrows = True, edgelist= edges_added, connectionstyle='arc3,rad=0.4',node_size = 1500)
#plt.show()
kf = KFold(n_splits= 4,shuffle=True)
scores = []
for k in kf.split(df2):
df_train = df2.iloc[k[0]]
learner=gum.BNLearner(df_train)
learner.useSmoothingPrior()
bn2 = learner.learnParameters(bn.dag())
bnc=skbn.BNClassifier()
bnc.fromTrainedModel(bn2,targetAttribute=class_var)
yTest = y.iloc[k[1]]
scoreCSV1 = bnc.score(df.iloc[k[1]], y =yTest)
#print("{0:.2f}% good predictions".format(100*scoreCSV1))
scores.append(scoreCSV1)
figures_list.append((fig, scores, bn2))
#bnc.showROC_PR('datos/cars_discrete.csv')
else:
steps_aux+=1
return figures_list