/
module.py
293 lines (227 loc) · 7.54 KB
/
module.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
#
# Collective Knowledge (dealing with .dot graph files)
#
# See CK LICENSE.txt for licensing details
# See CK COPYRIGHT.txt for copyright details
#
# Developer: Grigori Fursin, Grigori.Fursin@cTuning.org, http://fursin.net
#
cfg={} # Will be updated by CK (meta description of this module)
work={} # Will be updated by CK (temporal data)
ck=None # Will be updated by CK (initialized CK kernel)
# Local settings
##############################################################################
# Initialize module
def init(i):
"""
Input: {}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
return {'return':0}
##############################################################################
# converting .dot file made by machine learning algorithms to active decision tree
def convert_to_decision_tree(i):
"""
Input: {
input_file - .dot file
output_file - CK json decision tree file
(caption) - add caption, if needed
(labels) - Yes/No by default (can be True/False)
(problem_threshold) - float; if samples1/samples2 in the final leaf is more than this threshold
add *X* to the final answer to show that there is a possible misprediction.
By default = 0.12
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
labels
decisions
link_yes
link_no
}
"""
dlabels=i.get('labels',[])
if len(dlabels)==0: dlabels=cfg['labels']
fi=i['input_file']
fo=i['output_file']
cap=i.get('caption','')
s=''
r=ck.load_text_file({'text_file':fi,
'split_to_list':'yes'})
if r['return']>0: return r
lst=r['lst']
pt=i.get('problem_threshold','')
if pt=='': pt=0.12
pt=float(pt)
jl=1
labels={}
kl=1
decisions={}
link={}
link_yes={}
link_no={}
mo=False
# Detecting all labels (leafs) and decisions
for j in range(0, len(lst)):
q=lst[j]
ll=''
j1=q.find(' ')
if j1>0:
ll=q[:j1].strip()
classes={}
j0=q.find('\\nvalue = [')
if j0>0 and q.find('"X[')<0:
j2=q.find('[label="')
if j2>0:
sjl=str(jl)
x=q[:j2+8]+'*L'+sjl+'*\\n'+q[j2+8:]
lst[j]=x
labels[sjl]={'dot_label':ll}
j3=q.find(']',j0+1)
vals=q[j0+11:j3].strip().replace('\\n',', ')
svalsx=vals.split(' ')
svals=[]
for vv in svalsx:
if vv!='':
if vv.endswith('.'):
vv=vv[:-1]
if vv.endswith(','):
vv=vv[:-1]
vv=int(vv)
svals.append(vv)
if len(svals)==2:
# True of False classifier
v0=svals[0]
v1=svals[1]
if v0>v1: value=False
else: value=True
else:
# Multiple objects
mo=True
im=max(svals)
xx=[]
value=-1
for ivv in range(0, len(svals)):
vv=svals[ivv]
if float(vv)==float(im):
value=ivv
break
if value!=-1:
classes[vals]={'class':value, 'count':vv, 'sum':sum(svals)}
labels[sjl]['value']=value
jl+=1
else:
j1=q.find('[label="')
if j1>0:
j2=q.find('\\n',j1+1)
j3=q.find(']',j1+1)
j4=q.find(' ',j1+1)
j5=q.find(' ',j4+1)
dx={}
dx['feature']=q[j1+10:j3]
dx['comparison']=q[j4+1:j5]
dx['value']=q[j5+1:j2]
j1=q.find(' ')
l1=q[:j1].strip()
decisions[ll]=dx
j1=q.find(' -> ')
if j1>0:
j2=q.find(';', j1+1)
j2x=q.find('[',j1+1)
if j2x<j2: j2=j2x
ll2=q[j1+4:j2].strip()
if ll in link:
lbb='no'
link_no[ll2]=ll
else:
link[ll]='+'
link_yes[ll2]=ll
lbb='yes'
lst[j]=q[:j2]+'[label="'+lbb+'"];'
# Remove gini (difficult to interpret)
q=lst[j]
qq=''
j1=q.find('value = [')
if j1>0:
j2=q.find(']',j1)
if j2>0:
qx=q[j1+9:j2].strip().replace('\\n',', ')
qa=qx.split(' ')
qb=[]
for vv in qa:
if vv!='':
if vv.endswith('.'):
vv=vv[:-1]
if vv.endswith(','):
vv=vv[:-1]
vv=int(vv)
qb.append(vv)
if len(qb)==2:
# YES/NO
final_answer=dlabels[0]
if qb[0]<qb[1]: final_answer=dlabels[1]
problem=False
if qb[0]<qb[1] and qb[1]!=0 and (float(qb[0])/float(qb[1]))>pt: problem=True
if qb[0]>=qb[1] and qb[0]!=0 and (float(qb[1])/float(qb[0]))>pt: problem=True
if problem: final_answer='*'+final_answer+'*'
q=q[:j1]+dlabels[0]+' ('+str(qb[0])+') / '+dlabels[1]+' ('+str(qb[1])+')\\n\\n'+final_answer+q[j2+1:]
else:
# Multiple
xx=classes.get(qx,{})
xxc=xx.get('class',-1)
xxn=xx.get('count',1)
xxs=xx.get('sum',1)
ss=''
if xxc!=-1:
ss='S'+str(xxc)+' ('+str(xxn)+')\\n'
q=q[:j1]+ss+q[j2+1:]
j1=q.find('gini = ')
if j1>0:
j2=q.find('\\n',j1)
if j2>0:
q=q[:j1]+qq+q[j2+2:]
s+=q+'\n'
# If first line, add caption
if j==0 and cap!='':
s+='label="'+cap+'";\n'
s+='fontsize=16;\n'
s+='fontname=Helvetica;\n'
s+='fontcolor=Blue;\n'
s+='labelloc=top;\n'
s+='labeljust=center;\n'
s+='\n'
# Finding path to a given leaf
for ll in labels:
l=labels[ll]
dl=l['dot_label']
dt=[]
lx=dl
value=''
while lx!='0':
x=''
if lx in link_yes:
lx=link_yes[lx]
else:
lx=link_no[lx]
x='not '
dt.append(x)
dt.append(decisions[lx])
# reverse for top bottom check
dt1=[]
ldt=len(dt)
for q in range(0, ldt, 2):
dt1.append(dt[ldt-q-2])
dt1.append(dt[ldt-q-1])
l['decision']=dt1
# Save labels + decisions file
r=ck.save_json_to_file({'json_file':fo, 'dict':labels})
if r['return']>0: return r
# Update .dot file
r=ck.save_text_file({'text_file':fi, 'string':s})
if r['return']>0: return r
return {'return':0, 'labels':labels, 'decisions':decisions, 'link_yes':link_yes, 'link_no':link_no}