/
DoubleBeam_Ref.py
334 lines (277 loc) · 15.6 KB
/
DoubleBeam_Ref.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import Orange
import orange
import sys
import operator
from datetime import datetime
from SDRule import *
true = 1
false = 0
class DoubleBeam:
def __init__(self, minSupport = 0.2, sb_width=10, rb_width = 10, g=1, refinement_heuristics = "Inverted Laplace", selection_heuristics = "Laplace", **kwds):
self.minSupport = minSupport
self.g = g
self.CandidatesList = set()
self.selectionBeamWidth = sb_width
self.refinementBeamWidth = rb_width
self.refinementCandidates = []
self.selectionCandidates = []
self.alredyRefinedRules = dict()
self.refinement_heuristics = refinement_heuristics
self.selection_heuristics = selection_heuristics
self.alreadySelectedRules = set()
def __call__(self, data, targetClass, num_of_rules ):
self.alredyRefinedRules[targetClass] = set()
if self.dataOK(data): # Checks weather targetClass is discrete
data_discretized = False
# If any of the attributes are continuous, discretize them
if data.domain.hasContinuousAttributes():
original_data = data
data_discretized = True
new_domain = []
discretize = orange.EntropyDiscretization(forceAttribute=True)
for attribute in data.domain.attributes:
if attribute.varType == orange.VarTypes.Continuous:
d_attribute = discretize(attribute, data)
new_domain.append(d_attribute)
else:
new_domain.append(attribute)
data = original_data.select(new_domain + [original_data.domain.classVar])
self.data = data
self.targetClass = targetClass
#Initialize CanditatesList (all features)
self.fillCandidatesList(data,targetClass)
#Initialize RefinementBeam, consisting of refinementBeamWidth empty rules
self.initializeRefinementBeam()
#Initialize SelectionBeam, consisting of selectionBeamWidth empty rules
self.initializeSelectionBeam()
#update RefinementBeam
self.updateRefinementBeam(self.refinementCandidates)
#update SelectionBeam
self.updateSelectionBeam(self.selectionCandidates)
improvements = True
refinement_improvements = True
i=2
max_steps=5
while improvements:
self.refinedRefinementBeam(targetClass)
self.updateRefinementBeam(self.refinementCandidates)
improvements = self.updateSelectionBeam(self.selectionCandidates)
i=i+1
beam = self.SelectionBeam
if num_of_rules != 0:
beam = self.ruleSubsetSelection(beam, num_of_rules, data)
self.SelectionBeam = beam
if data_discretized:
targetClassRule = SDRule(original_data, targetClass, conditions=[], g=self.g)
self.SelectionBeam = [rule.getUndiscretized(original_data) for rule in self.SelectionBeam]
else:
targetClassRule = SDRule(data, targetClass, conditions=[], g =self.g)
rules = SDRules(self.SelectionBeam, targetClassRule, "DoubleBeam-RL")
return rules
def fillCandidatesList(self, data, targetClass):
#first initialize empty rule
rule = SDRule(data=data, targetClass=targetClass, g=self.g, refinement_heuristics=self.refinement_heuristics, selection_heuristics=self.selection_heuristics)
newRefinementBeam = {}
newSelectionBeam = {}
self.alredyRefinedRules[targetClass].add(rule.orderedRuleToString())
for attr in data.domain.attributes:
value = attr.firstvalue()
while(value):
newRule = rule.cloneAndAddCondition(attr,value,rule,refinement_heuristics=self.refinement_heuristics,selection_heuristics=self.selection_heuristics)
newRule.filterAndStore(rule)
self.CandidatesList.add(newRule)
newRefinementBeam[newRule] = newRule.refinement_quality
newSelectionBeam[newRule] = newRule.selection_quality
value = attr.nextvalue(value)
no_candidates = len(self.CandidatesList)
#sort the rules according to their refinement qualities
sorted_newRefinementBeam = sorted(newRefinementBeam.items(), key=operator.itemgetter(1), reverse=True)
self.refinementCandidates = [i[0] for i in sorted_newRefinementBeam]
#sort the rules according to their selection quality
sorted_newSelectionBeam = sorted(newSelectionBeam.items(), key=operator.itemgetter(1), reverse=True)
l_sortedNewSelectionBeam = [i[0] for i in sorted_newSelectionBeam]
self.sortSelectionCandidates(l_sortedNewSelectionBeam)
def chooseSelectionCandidates(self,beam):
newSelectionBeam = {}
for rule in beam:
newSelectionBeam[rule]=rule.selection_quality
sorted_newSelectionBeam = sorted(newSelectionBeam.items(), key=operator.itemgetter(1), reverse=True)
self.selectionCandidates = [i[0] for i in sorted_newSelectionBeam]
def initializeRefinementBeam(self):
self.RefinementBeam = [SDRule(data=self.data, targetClass=self.targetClass, g=self.g, refinement_heuristics=self.refinement_heuristics, selection_heuristics=self.selection_heuristics)]*self.refinementBeamWidth
def initializeSelectionBeam(self):
self.SelectionBeam = [SDRule(data=self.data, targetClass=self.targetClass, g=self.g,refinement_heuristics=self.refinement_heuristics, selection_heuristics=self.selection_heuristics)]*self.selectionBeamWidth
def updateRefinementBeam(self, refinementCandidates):
empty_rule = [SDRule(data=self.data, targetClass=self.targetClass, g=self.g, refinement_heuristics=self.refinement_heuristics, selection_heuristics=self.selection_heuristics)]
newRefinementBeam = {}
alreadyRefined = []
refinement_improvement = False
for ref in self.RefinementBeam:
if ref.complexity != 0:
alreadyRefined.append(ref.orderedRuleToString())
for refinement in refinementCandidates:
if (refinement.orderedRuleToString() not in alreadyRefined):
newRefinementBeam[refinement] = refinement.refinement_quality
alreadyRefined.append(ref.orderedRuleToString())
sorted_newRefinementBeam = sorted(newRefinementBeam.items(), key=operator.itemgetter(1), reverse=True)
self.refinementCandidates = [i[0] for i in sorted_newRefinementBeam]
if len(self.refinementCandidates) > self.refinementBeamWidth:
self.RefinementBeam = self.refinementCandidates[:self.refinementBeamWidth]
else:
self.RefinementBeam = self.refinementCandidates + empty_rule*(self.refinementBeamWidth-len(self.refinementCandidates))
return refinement_improvement
def printBeam(self, beam, name):
print "#"*100
print "\n %s \n" %(name)
for rule in beam:
print "SQ: %.3f\tRQ: %.3f\tTP: %d\tFP: %d\t%s" %(rule.selection_quality,rule.refinement_quality,len(rule.TP),len(rule.FP),rule.ruleToString())
print "*"*100
def updateSelectionBeam(self, selectionCandidates):
empty_rule = [SDRule(data=self.data, targetClass=self.targetClass, g=self.g, \
refinement_heuristics=self.refinement_heuristics, selection_heuristics=self.selection_heuristics)]
newSelectionBeam = {}
changes = False
alreadySelected = []
for sel in self.SelectionBeam:
if sel.complexity != 0:
newSelectionBeam[sel] = sel.selection_quality
alreadySelected.append(sel.orderedRuleToString())
self.alreadySelectedRules.add(sel.orderedRuleToString())
for selection in selectionCandidates:
#if the selection quality is smaller than the worst rule for selection in SelectionBeam, ignore this rule and others that follow
if selection.selection_quality < self.SelectionBeam[-1].selection_quality:
break
if (selection.orderedRuleToString() not in alreadySelected) and (selection.orderedRuleToString() not in self.alreadySelectedRules):
newSelectionBeam[selection] = selection.selection_quality
alreadySelected.append(selection.orderedRuleToString())
changes = True
sorted_newSelectionBeam = sorted(newSelectionBeam.items(), key=operator.itemgetter(1), reverse=True)
self.selectionCandidates = [i[0] for i in sorted_newSelectionBeam]
if len(self.selectionCandidates) > self.selectionBeamWidth:
#the updated SelectionBeam should consist only of selectionBeamWidth elements
self.sortSelectionCandidates(self.selectionCandidates)
self.SelectionBeam = self.selectionCandidates[:self.selectionBeamWidth]
else:
self.SelectionBeam = self.selectionCandidates + empty_rule*(self.selectionBeamWidth-len(self.selectionCandidates))
return changes
def selectRelevantCandidates(self):
empty_rule = [SDRule(data=self.data, targetClass=self.targetClass, g=self.g, \
refinement_heuristics=self.refinement_heuristics, selection_heuristics=self.selection_heuristics)]
i=1
newSelectionBeam = [self.selectionCandidates[0]]
for j in range(1,len(self.selectionCandidates)):
candidate = self.selectionCandidates[j]
if self.isRelevant(candidate, newSelectionBeam):
i = i+1
newSelectionBeam.append(candidate)
if len(newSelectionBeam) > self.selectionBeamWidth:
self.SelectionBeam = newSelectionBeam[:self.selectionBeamWidth]
else:
self.SelectionBeam = newSelectionBeam + empty_rule*(self.selectionBeamWidth-len(newSelectionBeam))
def sortSelectionCandidates(self, selectionCandidates):
sortedSelectionCandidates = []
for i in range(len(selectionCandidates)-1):
temps = {}
for j in range(i+1,len(selectionCandidates)):
if selectionCandidates[j]==selectionCandidates[j-1]:
temps[j-1] = selectionCandidates[j-1].TP
temps[j] = selectionCandidates[j-1].TP
else:
temps[j-1] = selectionCandidates[j-1].TP
i = j
break
sorted_temps = sorted(temps.items(), key=operator.itemgetter(1), reverse=True)
l_sorted_temps = [k[0] for k in sorted_temps]
for st in l_sorted_temps:
sortedSelectionCandidates.append(selectionCandidates[st])
if len(sortedSelectionCandidates)<len(selectionCandidates):
sortedSelectionCandidates.append(selectionCandidates[-1])
self.selectionCandidates = sortedSelectionCandidates
def isRelevant(self, newRule, beam):
for rule in beam:
if newRule.isIrrelevant(rule):
return false
return true
def refinedRefinementBeam(self, targetClass):
min_sup = self.minSupport
newRefinementCandidates = {}
newSelectionCandidates = {}
for refinement in self.RefinementBeam:
if refinement.orderedRuleToString() not in self.alredyRefinedRules[targetClass] and refinement.complexity !=0:
attributes = refinement.conditions()
for attr in self.data.domain.attributes:
if attr.name not in attributes:
value = value = attr.firstvalue()
while value:
newRule = refinement.cloneAndAddCondition(attr,value,refinement,refinement_heuristics=self.refinement_heuristics, selection_heuristics=self.selection_heuristics)
newRule.filterAndStore(refinement)
if newRule.support > min_sup:
#if (len(newRule.TP) != len(refinement.TP)) and (len(newRule.FP) != len(refinement.FP)):
if len(newRule.FP) < len(refinement.FP):
newRefinementCandidates[newRule]=newRule.refinement_quality
newSelectionCandidates[newRule]=newRule.selection_quality
self.alredyRefinedRules[targetClass].add(refinement.orderedRuleToString())
value = attr.nextvalue(value)
sorted_newRefinementCandidates = sorted(newRefinementCandidates.items(), key=operator.itemgetter(1), reverse=True)
sorted_newSelectionCandidates = sorted(newSelectionCandidates.items(), key=operator.itemgetter(1), reverse=True)
self.refinementCandidates = [i[0] for i in sorted_newRefinementCandidates]
l_sortedSelectionCandidates = [i[0] for i in sorted_newSelectionCandidates]
self.sortSelectionCandidates(l_sortedSelectionCandidates)
def betterThanWorstRule(self, newRule, beam, worstRuleIndex):
if newRule.quality2 > beam[worstRuleIndex].quality2: # better quality
return true
elif newRule.quality2 == beam[worstRuleIndex].quality2 and newRule.complexity < beam[worstRuleIndex].complexity: # same quality and smaller complexity
return true
else:
return false
def replaceWorstRule(self, rule, beam, worstRuleIndex):
beam[worstRuleIndex] = rule
wri = 0
for i in range(len(beam)):
if beam[i].quality2 < beam[wri].quality2:
wri = i
return wri
def dataOK(self, data):
if data.domain.classVar.varType != orange.VarTypes.Discrete:
print "Target Variable must be discrete: %s"%(data.domain.classVar.name)
return false
return true
def ruleSubsetSelection(self, beam, num_of_rules, data):
SS = []
c = orange.newmetaid()
data.addMetaAttribute(c) #initialize to 1
if num_of_rules <= len(beam):
for i in range(num_of_rules):
best_score = 0
best_rule_index = 0
for i in range(len(beam)):
score = 0
for d in data: # calculate sum of weights of examples
if beam[i].filter(d):
score += 1.0/d.getweight(c)
if score>best_score:
best_score = score
best_rule_index = i
for d in data: # increase exampe counter
if beam[best_rule_index].filter(d):
d.setweight(c, d.getweight(c)+1)
SS.append(beam[best_rule_index])
del beam[best_rule_index]
data.removeMetaAttribute(c)
else:
return beam
return SS
def writeResults(self,file_name):
current_directory = os.path.dirname(os.path.realpath(__file__)) + r"/results"
print current_directory
#___________________________________________________________________________________
if __name__=="__main__":
dataset_directory = current_directory = os.path.dirname(os.path.realpath(__file__))+r"/20_DATASETS_TAB/"
dataset = "contact-lenses.tab"
filename = os.path.join(dataset_directory,dataset)
data = orange.ExampleTable(filename)
print
learner = DoubleBeam(minSupport=0.001, sb_width=1, refinement_heuristics = "Inverted Laplace", selection_heuristics="Laplace")
rules = learner(data, targetClass="none", num_of_rules=0)
learner.printBeam(learner.SelectionBeam, "SB")
rules.printRules()