-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathexstracs_classifierset.py
executable file
·1361 lines (1188 loc) · 63.9 KB
/
exstracs_classifierset.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Name: ExSTraCS_ClassifierSet.py
Authors: Ryan Urbanowicz - Written at Dartmouth College, Hanover, NH, USA
Contact: ryan.j.urbanowicz@darmouth.edu
Created: April 25, 2014
Description: This module handles all classifier sets (population, match set, correct set) along with mechanisms and heuristics that act on these sets.
---------------------------------------------------------------------------------------------------------------------------------------------------------
ExSTraCS V1.0: Extended Supervised Tracking and Classifying System - An advanced LCS designed specifically for complex, noisy classification/data mining tasks,
such as biomedical/bioinformatics/epidemiological problem domains. This algorithm should be well suited to any supervised learning problem involving
classification, prediction, data mining, and knowledge discovery. This algorithm would NOT be suited to function approximation, behavioral modeling,
or other multi-step problems. This LCS algorithm is most closely based on the "UCS" algorithm, an LCS introduced by Ester Bernado-Mansilla and
Josep Garrell-Guiu (2003) which in turn is based heavily on "XCS", an LCS introduced by Stewart Wilson (1995).
Copyright (C) 2014 Ryan Urbanowicz
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABLILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
---------------------------------------------------------------------------------------------------------------------------------------------------------
"""
#Import Required Modules-------------------------------
from exstracs_constants import *
from exstracs_classifier import Classifier
# from exstracs_tree import *
from GP_Tree import *
print()
import random
import copy
import sys
#------------------------------------------------------
class ClassifierSet:
def __init__(self, a=None):
""" Overloaded initialization: Handles creation of a new population or a rebooted population (i.e. a previously saved population). """
# Major Parameters-----------------------------------
self.popSet = [] # List of classifiers/rules
self.matchSet = [] # List of references to rules in population that match
self.correctSet = [] # List of references to rules in population that both match and specify correct phenotype
self.microPopSize = int(cons.popInitGP * cons.N) # Tracks the current micro population size, i.e. the population size which takes rule numerosity into account.
# #Epoch Pool Deletion---------------------------------
# self.ECPopSize = 0 #Epoch Complete - Micro Pop Size
# self.ENCPopSize = 0 #Epoch Not Complete - Micro Pop Size
#Evaluation Parameters-------------------------------
self.aveGenerality = 0.0
self.expRules = 0.0
self.attributeSpecList = []
self.attributeAccList = []
self.avePhenotypeRange = 0.0
#Test parameters ------------------------------------
self.tree_cross_count = 0
self.rule_cross_count = 0
self.both_cross_count = 0
#Parameter for continuous trees
self.tree_error = None #changing error threshold for trees to be considered in the correct set
#Set Constructors-------------------------------------
if a==None:
self.makePop() #Initialize a new population
elif isinstance(a,str):
self.rebootPop(a) #Initialize a population based on an existing saved rule population
else:
print("ClassifierSet: Error building population.")
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# POPULATION CONSTRUCTOR METHODS
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def makePop(self):
""" Initializes the rule population """
self.popSet = []
#Initialize Population of Trees----------------------
#hardcode num Trees for now
if cons.useGP:
#Initialize Population of Trees----------------------
gpInit = cons.popInitGP * cons.N
print("Initializing Tree population with "+str(int(gpInit))+" GP trees.")
#initialize marked tree for testing
for x in range(0, int(cons.popInitGP * cons.N)-1):
# newTree = Tree() ## For older DEAP code.
newTree = GP_Tree()
self.popSet.append(newTree)
print("Tree Initialization Complete")
def rebootPop(self, remakeFile):
""" Remakes a previously evolved population from a saved text file. """
print("Rebooting the following population: " + str(remakeFile)+"_RulePop.txt")
#*******************Initial file handling**********************************************************
try:
datasetList = []
f = open(remakeFile+"_RulePop.txt", 'rU')
self.headerList = f.readline().rstrip('\n').split('\t') #strip off first row
for line in f:
lineList = line.strip('\n').split('\t')
datasetList.append(lineList)
f.close()
except IOError as xxx_todo_changeme:
(errno, strerror) = xxx_todo_changeme.args
print ("Could not Read Remake File!")
print(("I/O error(%s): %s" % (errno, strerror)))
raise
except ValueError:
print ("Could not convert data to an integer.")
raise
except:
print(("Unexpected error:", sys.exc_info()[0]))
raise
#**************************************************************************************************
for each in datasetList:
cl = Classifier(each)
self.popSet.append(cl) #Add classifier to the population
numerosityRef = 5 #location of numerosity variable in population file.
self.microPopSize += int(each[numerosityRef])
# if cl.epochComplete:
# self.ECPopSize += int(each[numerosityRef])
# else:
# self.ENCPopSize += int(each[numerosityRef])
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# CLASSIFIER SET CONSTRUCTOR METHODS
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def makeMatchSet(self, state_phenotype, exploreIter):
""" Constructs a match set from the population. Covering is initiated if the match set is empty or a rule with the current correct phenotype is absent. """
#Initial values----------------------------------
state = state_phenotype[0]
phenotype = state_phenotype[1]
#--------------------------------------------------------
# Define phenotypes for trees
#--------------------------------------------------------
for i in range(len(self.popSet)):
cl = self.popSet[i]
if cl.isTree:
cl.setPhenotype(state)
#ContinuousCode #########################
#Calculate error threshold
if not cons.env.formatData.discretePhenotype:
totalError = 0
tree_count = 0
for cl in self.popSet:
if cl.isTree:
error = abs(float(phenotype) - float(cl.phenotype))
dataInfo = cons.env.formatData
if error > (dataInfo.phenotypeList[1] - dataInfo.phenotypeList[0]):
error = (dataInfo.phenotypeList[1] - dataInfo.phenotypeList[0])
totalError += error
#print abs(float(phenotype) - float(cl.phenotype))
tree_count += 1
newError = totalError / tree_count
if self.tree_error != None:
#change learning rate to be in constants
self.tree_error = self.tree_error + (0.2 * (newError - self.tree_error))
else:
self.tree_error = newError
#print("New Error: " + str(newError) + " Tree Error: " + str(self.tree_error) + "Total Error: " + str(totalError))
for cl in self.popSet:
if cl.isTree:
cl.calcPhenProb(self.tree_error)
doCovering = True # Covering check: Twofold (1)checks that a match is present, and (2) that at least one match dictates the correct phenotype.
setNumerositySum = 0
#-------------------------------------------------------
# MATCHING
#-------------------------------------------------------
cons.timer.startTimeMatching()
for i in range(len(self.popSet)): # Go through the population
cl = self.popSet[i] # One classifier at a time
epochCompleted = False
epochCompleted = cl.updateEpochStatus(exploreIter) # Note whether this classifier has seen all training data at this point.
# if epochCompleted:
# self.ECPopSize += cl.numerosity #Epoch Complete - Micro Pop Size
# self.ENCPopSize -= cl.numerosity #Epoch Not Complete - Micro Pop Size
#Fitness Update------------------------------
if not cl.epochComplete and (exploreIter - cl.lastMatch) >= cons.noMatchUpdate:
cl.briefUpdateFitness(exploreIter)
if cl.match(state): # Check for match
cl.lastMatch = exploreIter # Experimental::::: for brief fitness update.
self.matchSet.append(i) # If match - add classifier to match set
setNumerositySum += cl.numerosity # Increment the set numerosity sum
#Covering Check--------------------------------------------------------
if cons.env.formatData.discretePhenotype: # Discrete phenotype
if cl.phenotype == phenotype and not cl.isTree: # Check for phenotype coverage
doCovering = False
else: #ContinuousCode #########################
if not cl.isTree and float(cl.phenotype[0]) <= float(phenotype) <= float(cl.phenotype[1]): # Check for phenotype coverage
doCovering = False
cons.timer.stopTimeMatching()
#-------------------------------------------------------
# COVERING
#-------------------------------------------------------
if doCovering:
#print('Covered new rule')
pass
while doCovering:
cons.timer.startTimeCovering()
newCl = Classifier(setNumerositySum+1,exploreIter, state, phenotype)
self.addCoveredClassifierToPopulation(newCl)
self.matchSet.append(len(self.popSet)-1) # Add covered classifier to matchset
doCovering = False
cons.timer.stopTimeCovering()
"""
if exploreIter % 100 == 0 and exploreIter > 0:
numRules = 0
numTrees = 0
for i in range(len(self.popSet)):
cl = self.popSet[i]
if cl.isTree:
numTrees += 1
else:
numRules += 1
#print params of iteration
print "Iter: " + str(exploreIter) + " PopSize: " + str(len(self.popSet)) + " MatchSize: " + str(len(self.matchSet))
print "MicroPopSize: " + str(self.microPopSize) + " NumTrees: " + str(numTrees) + " NumRules: " + str(numRules)
print "Tree: " + str(self.tree_cross_count) + " Rule: " + str(self.rule_cross_count) + " Both: " + str(self.both_cross_count) + " Total: " + str(self.tree_cross_count + self.rule_cross_count + self.both_cross_count)
best = 0
best_tree = None
for cl in self.popSet:
if cl.isTree:
if cl.accuracy > best:
best = cl.accuracy
best_tree = cl
print "Best tree accuracy: " + str(best)
if best_tree:
print "Best Tree: " + str(best_tree.form)
#print "Fitness: " + str(best_tree.fitness)
print "ID: " + str(best_tree.id)
"""
"""
found = False
for cl in self.popSet:
if cl.marked:
print "Accuracy: " + str(cl.accuracy) + " Fitness: " + str(cl.fitness) + " MatchCount: " + str(cl.matchCount) + " CorrectCount: " + str(cl.correctCount)
#print cl.form
found = True
break
if not found:
print "Deleted"
"""
#track young tree
"""
for cl in self.popSet:
if cl.isTree:
if cl.initTimeStamp > 0:
print "Young Tree: " + str(cl.form)
print "Fitness: " + str(cl.fitness)
print "ID: " + str(cl.id)
"""
#Last used reporting!!!!!!!!!!!!!!!!!!!!
"""
numRules = 0
numTrees = 0
for i in range(len(self.popSet)):
cl = self.popSet[i]
if cl.isTree:
numTrees += 1
else:
numRules += 1
#print params of iteration
print("Iter: " + str(exploreIter) + " PopSize: " + str(len(self.popSet)) + " MatchSize: " + str(len(self.matchSet)))
print("MicroPopSize: " + str(self.microPopSize) + " NumTrees: " + str(numTrees) + " NumRules: " + str(numRules))
print("Tree: " + str(self.tree_cross_count) + " Rule: " + str(self.rule_cross_count) + " Both: " + str(self.both_cross_count) + " Total: " + str(self.tree_cross_count + self.rule_cross_count + self.both_cross_count))
best = 0
best_tree = None
for cl in self.popSet:
if cl.isTree:
if cl.fitness > best:
best = cl.fitness
best_tree = cl
print("Best tree fitness: " + str(best))
if best_tree:
print("Best Tree: " + str(best_tree.form))
print("AccuracyComp: " + str(best_tree.accuracyComponent))
print("CoverDiff: " + str(best_tree.coverDiff))
print("Ind Fitness: " + str(best_tree.indFitness))
print("Epoch Complete: " + str(best_tree.epochComplete) + " MatchCount: " + str(best_tree.matchCount))
#print "ID: " + str(best_tree.id)
"""
def makeCorrectSet(self, phenotype):
""" Constructs a correct set out of the given match set. """
for i in range(len(self.matchSet)):
ref = self.matchSet[i]
#-------------------------------------------------------
# DISCRETE PHENOTYPE
#-------------------------------------------------------
if cons.env.formatData.discretePhenotype:
if self.popSet[ref].phenotype == phenotype:
self.correctSet.append(ref)
#-------------------------------------------------------
# CONTINUOUS PHENOTYPE
#-------------------------------------------------------
else: #ContinuousCode #########################
if not self.popSet[ref].isTree: #RULES
if float(phenotype) <= float(self.popSet[ref].phenotype[1]) and float(phenotype) >= float(self.popSet[ref].phenotype[0]):
self.correctSet.append(ref)
else: #TREES
#We won't use any notion of a correct set for GP trees. USe error to determine correct set for att tracking downstream, but not used for accuracy update.
if abs(float(phenotype) - float(self.popSet[ref].phenotype)) <= self.tree_error:
self.correctSet.append(ref)
"""
if exploreIter % 100 == 0 and exploreIter > 0:
numRules = 0
numTrees = 0
for i in self.correctSet:
cl = self.popSet[i]
if cl.isTree:
numTrees += 1
else:
numRules += 1
print "CorrectSet - NumTrees: " + str(numTrees) + " NumRules: " + str(numRules)
"""
def makeEvalMatchSet(self, state):
""" Constructs a match set for evaluation purposes which does not activate either covering or deletion. """
for i in range(len(self.popSet)): # Go through the population
cl = self.popSet[i] # A single classifier
if cl.isTree: #In evaluation we still need to update the phenotype for each instance for trees
cl.setPhenotype(state)
if cl.match(state): # Check for match
self.matchSet.append(i) # Add classifier to match set
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# CLASSIFIER DELETION METHODS
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def deletion(self, exploreIter):
""" Returns the population size back to the maximum set by the user by deleting rules. """
cons.timer.startTimeDeletion()
while self.microPopSize > cons.N:
self.deleteFromPopulation()
cons.timer.stopTimeDeletion()
def deleteFromPopulation(self):
""" Deletes one classifier in the population. The classifier that will be deleted is chosen by roulette wheel selection
considering the deletion vote. Returns the macro-classifier which got decreased by one micro-classifier. """
meanFitness = self.getPopFitnessSum()/float(self.microPopSize)
#Calculate total wheel size------------------------------
sumCl = 0.0
voteList = []
for cl in self.popSet:
vote = cl.getDelProp(meanFitness)
sumCl += vote
voteList.append(vote)
#--------------------------------------------------------
choicePoint = sumCl * random.random() #Determine the choice point
newSum=0.0
for i in range(len(voteList)):
cl = self.popSet[i]
newSum = newSum + voteList[i]
if newSum > choicePoint or newSum == float('Inf'): #Select classifier for deletion
#Delete classifier----------------------------------
cl.updateNumerosity(-1)
self.microPopSize -= 1
if cl.numerosity < 1: # When all micro-classifiers for a given classifier have been depleted.
self.removeMacroClassifier(i)
self.deleteFromMatchSet(i)
self.deleteFromCorrectSet(i)
return
print(choicePoint)
print(sumCl)
print(newSum)
print("ClassifierSet: No eligible rules found for deletion in deleteFrom population.")
return
#
# def deleteFromPopulation(self, exploreIter):
# """ Deletes one classifier in the population. The classifier that will be deleted is chosen by roulette wheel selection
# considering the deletion vote. Returns the macro-classifier which got decreased by one micro-classifier. """
# meanFitness = self.getPopFitnessSum()/float(self.microPopSize)
#
# Epoch Pool Deletion:------------------------------------
# Three situations to deal with: too many EC - delete from EC: EC full - delete from ENC : EC not full - treat all equal
#
# maxEpochCompletePool = int(cons.N *0.5) #Half the rule pop is reserved for complete rules
# deleteFromEC = False
# deleteFromENC = False
# quickDelete = False
# print 'new'
# print self.ECPopSize
# print self.ENCPopSize
# if self.ECPopSize > maxEpochCompletePool:
# cons.epochPoolFull = True #One time switch - once full it should stay full.
# deleteFromEC = True
# print 'deleteFromEC'
# else:
# if self.ECPopSize == maxEpochCompletePool:
# deleteFromENC = True
# print 'deleteFromENC'
# Calculate total wheel size------------------------------
# sumCl = 0.0
# voteList = []
# x = 0
#
# for cl in self.popSet:
# vote = cl.getDelProp(meanFitness)
# vote = cl.getDeletionVote()
# if vote[1]:
# quickDelete = True
# break
# else:
# sumCl += vote[0]
# voteList.append(vote[0])
# x += 1
#
#
# choicePoint = sumCl * random.random() #Determine the choice point
# newSum=0.0
# for i in range(len(voteList)):
# cl = self.popSet[i]
# newSum = newSum + voteList[i]
# if newSum > choicePoint: #Select classifier for deletion
# Delete classifier----------------------------------
# cl.updateNumerosity(-1)
# self.microPopSize -= 1
# if cl.epochComplete:
# self.ECPopSize -= 1
# else:
# self.ENCPopSize -= 1
#
#
# if cl.numerosity < 1: # When all micro-classifiers for a given classifier have been depleted.
# self.removeMacroClassifier(i)
# self.deleteFromMatchSet(i)
# self.deleteFromCorrectSet(i)
# return
#
# if quickDelete:
# cl = self.popSet[x]
# self.microPopSize -= cl.numerosity
# if cl.epochComplete:
# self.ECPopSize -= cl.numerosity
# else:
# self.ENCPopSize -= cl.numerosity
# self.removeMacroClassifier(x)
# self.deleteFromMatchSet(x)
# self.deleteFromCorrectSet(x)
# else:
# choicePoint = sumCl * random.random() #Determine the choice point
# newSum=0.0
# for i in range(len(voteList)):
# cl = self.popSet[i]
# newSum = newSum + voteList[i]
# if newSum > choicePoint: #Select classifier for deletion
# #Delete classifier----------------------------------
# cl.updateNumerosity(-1)
# self.microPopSize -= 1
# if cl.epochComplete:
# self.ECPopSize -= 1
# else:
# self.ENCPopSize -= 1
#
#
# if cl.numerosity < 1: # When all micro-classifiers for a given classifier have been depleted.
# self.removeMacroClassifier(i)
# self.deleteFromMatchSet(i)
# self.deleteFromCorrectSet(i)
# return
#
# print "ClassifierSet: No eligible rules found for deletion in deleteFrom population."
# def deleteFromPopulation(self, exploreIter):
# """ Deletes one classifier in the population. The classifier that will be deleted is chosen by roulette wheel selection
# considering the deletion vote. Returns the macro-classifier which got decreased by one micro-classifier. """
# meanFitness = self.getPopFitnessSum()/float(self.microPopSize)
#
# #Epoch Pool Deletion:------------------------------------
# #Three situations to deal with: too many EC - delete from EC: EC full - delete from ENC : EC not full - treat all equal
#
# maxEpochCompletePool = int(cons.N *0.5) #Half the rule pop is reserved for complete rules
# deleteFromEC = False
# deleteFromENC = False
# quickDelete = False
## print 'new'
## print self.ECPopSize
## print self.ENCPopSize
# if self.ECPopSize > maxEpochCompletePool:
# cons.epochPoolFull = True #One time switch - once full it should stay full.
# deleteFromEC = True
# #print 'deleteFromEC'
# else:
# if self.ECPopSize == maxEpochCompletePool:
# deleteFromENC = True
# #print 'deleteFromENC'
#
# #Calculate total wheel size------------------------------
# sumCl = 0.0
# voteList = []
# if deleteFromEC:
# for cl in self.popSet:
# if cl.epochComplete:
# vote = cl.getDelProp(meanFitness)
# #vote = cl.getDeletionVote()
# sumCl += vote
# voteList.append(vote)
# else:
# voteList.append(0)
# elif deleteFromENC:
# for cl in self.popSet:
# if cl.epochComplete:
# voteList.append(0)
# else:
# vote = cl.getDelProp(meanFitness)
# #vote = cl.getDeletionVote()
# sumCl += vote
# voteList.append(vote)
# else: #All rules treated equally
# for cl in self.popSet:
# vote = cl.getDelProp(meanFitness)
# #vote = cl.getDeletionVote()
# sumCl += vote
# voteList.append(vote)
#
# #--------------------------------------------------------
# choicePoint = sumCl * random.random() #Determine the choice point
#
# newSum=0.0
# for i in range(len(voteList)):
# cl = self.popSet[i]
# newSum = newSum + voteList[i]
# if newSum > choicePoint: #Select classifier for deletion
# #Delete classifier----------------------------------
# cl.updateNumerosity(-1)
# self.microPopSize -= 1
# if cl.epochComplete:
# self.ECPopSize -= 1
# else:
# self.ENCPopSize -= 1
#
#
# if cl.numerosity < 1: # When all micro-classifiers for a given classifier have been depleted.
# self.removeMacroClassifier(i)
# self.deleteFromMatchSet(i)
# self.deleteFromCorrectSet(i)
# return
#
# print "ClassifierSet: No eligible rules found for deletion in deleteFrom population."
def removeMacroClassifier(self, ref):
""" Removes the specified (macro-) classifier from the population. """
self.popSet.pop(ref)
def deleteFromMatchSet(self, deleteRef):
""" Delete reference to classifier in population, contained in self.matchSet."""
if deleteRef in self.matchSet:
self.matchSet.remove(deleteRef)
#Update match set reference list--------
for j in range(len(self.matchSet)):
ref = self.matchSet[j]
if ref > deleteRef:
self.matchSet[j] -= 1
def deleteFromCorrectSet(self, deleteRef):
""" Delete reference to classifier in population, contained in self.matchSet."""
if deleteRef in self.correctSet:
self.correctSet.remove(deleteRef)
#Update match set reference list--------
for j in range(len(self.correctSet)):
ref = self.correctSet[j]
if ref > deleteRef:
self.correctSet[j] -= 1
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# GENETIC ALGORITHM
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def runGA(self, exploreIter, state, phenotype):
""" The genetic discovery mechanism in ExSTraCS is controlled here. """
#-------------------------------------------------------
# GA RUN REQUIREMENT
#-------------------------------------------------------
if (exploreIter - self.getIterStampAverage()) < cons.theta_GA: #Does the correct set meet the requirements for activating the GA?
return
#print "GA RUNNING ###############################################################"
self.setIterStamps(exploreIter) #Updates the iteration time stamp for all rules in the correct set (which the GA operates on).
changed = False
#-------------------------------------------------------
# SELECT PARENTS - Niche GA - selects parents from the correct class
#-------------------------------------------------------
cons.timer.startTimeSelection()
selectList = self.selectClassifierRW()
clP1 = selectList[0]
clP2 = selectList[1]
#test selection for tree and rule crossover
"""
if cons.selectionMethod == "roulette":
selectList = self.selectClassifierRW()
clP1 = selectList[0]
clP2 = selectList[1]
elif cons.selectionMethod == "tournament":
#selectList = self.selectClassifierT()
selectList = self.selectClassifierT(exploreIter)
clP1 = selectList[0]
clP2 = selectList[1]
else:
print "ClassifierSet: Error - requested GA selection method not available."
"""
cons.timer.stopTimeSelection()
#START GP INTEGRATION CODE*************************************************************************************************************************************
#-------------------------------------------------------
# INITIALIZE OFFSPRING
#-------------------------------------------------------
if clP1.isTree:
# cl1 = Tree(clP1, exploreIter) ## For older Deap code
cl1 = tree_Clone(clP1, exploreIter)
else:
cl1 = Classifier(clP1, exploreIter)
if clP2 == None: #If there was only one parent - then both 'parents' will be from the same source. No reason to do crossover if this is the case, only mutation.
#print("Only one parent available")
if clP1.isTree:
# cl2 = Tree(clP1, exploreIter) ## For older Deap code
cl2 = tree_Clone(clP1, exploreIter)
else:
cl2 = Classifier(clP1, exploreIter)
else:
if clP2.isTree:
# cl2 = Tree(clP2, exploreIter) ## For older Deap code
cl2 = tree_Clone(clP2, exploreIter);
else:
cl2 = Classifier(clP2, exploreIter)
#COUNTERS------------------ TEMPORARY
if cl1.isTree and cl2.isTree: #both entities are trees
self.tree_cross_count += 1
elif not cl1.isTree and not cl2.isTree:
self.rule_cross_count += 1
else:
self.both_cross_count += 1
#-------------------------------------------------------
# CROSSOVER OPERATOR - Uniform Crossover Implemented (i.e. all attributes have equal probability of crossing over between two parents)
#-------------------------------------------------------
if cl1.equals(cl2):
#print("it happened")
pass
if not cl1.equals(cl2) and random.random() < cons.chi: #If parents are the same don't do crossover.
cons.timer.startTimeCrossover()
#print('------------------------------Performing Crossover')
#REPORTING CROSSOVER EVENTS!------------TEMP
if cl1.isTree and cl2.isTree:
#print('Crossing 2 Trees')
#print(str(cl1.form)+str(cl1.specifiedAttList))
#print(str(cl2.form)+str(cl2.specifiedAttList))
pass
elif not cl1.isTree and not cl2.isTree:
#print('Crossing 2 Rules')
pass
else: #one of each
#print('Crossing a Tree with a Rule')
if cl1.isTree:
#print(str(cl1.form)+str(cl1.specifiedAttList))
#print(str(cl2.condition)+str(cl2.specifiedAttList))
pass
else:
#print(str(cl2.form)+str(cl2.specifiedAttList))
#print(str(cl1.condition)+str(cl1.specifiedAttList))
pass
#--------------------------------------------------
changed = cl1.uniformCrossover(cl2,state, phenotype) #PERFORM CROSSOVER! #calls either the rule or tree crossover method depending on whether cl1 is tree or rule.
cons.timer.stopTimeCrossover()
#-------------------------------------------------------
# INITIALIZE KEY OFFSPRING PARAMETERS
#-------------------------------------------------------
if changed:
cl1.setFitness(cons.fitnessReduction * (cl1.fitness + cl2.fitness)/2.0)
cl2.setFitness(cl1.fitness)
else:
cl1.setFitness(cons.fitnessReduction * cl1.fitness)
cl2.setFitness(cons.fitnessReduction * cl2.fitness)
#-------------------------------------------------------
# MUTATION OPERATOR
#-------------------------------------------------------
#cons.timer.startTimeMutation()
#nowchanged = cl1.Mutation(state, phenotype)
#howaboutnow = cl2.Mutation(state, phenotype)
nowchanged = True
howaboutnow = True
#cons.timer.stopTimeMutation()
#Get current data point evaluation on new tree - determine phenotype and detemine if correct.
if cl1.isTree:
#Get phenotype for current instance
cl1.setPhenotype(state)
#Update correct count accordingly.
cl1.updateClonePhenotype(phenotype)
if cl2.isTree:
#Get phenotype for current instance
cl2.setPhenotype(state)
#Update correct count accordingly.
cl2.updateClonePhenotype(phenotype)
#STOP GP INTEGRATION CODE*************************************************************************************************************************************
"""
for cl in self.popSet:
if cl.isTree:
cl.Mutation(state, phenotype)
"""
#print('Crossover output')
if cl1.isTree:
#print(str(cl1.form)+str(cl1.specifiedAttList))
pass
if cl2.isTree:
#print(str(cl2.form)+str(cl2.specifiedAttList))
pass
#Generalize any continuous attributes that span then entire range observed in the dataset.
if cons.env.formatData.continuousCount > 0:
cl1.rangeCheck()
cl2.rangeCheck()
#-------------------------------------------------------
# CONTINUOUS ENDPOINT - phenotype range probability correction
#-------------------------------------------------------
if not cons.env.formatData.discretePhenotype: #ContinuousCode #########################
cl1.setPhenProb()
cl2.setPhenProb()
#-------------------------------------------------------
# ADD OFFSPRING TO POPULATION
#-------------------------------------------------------
#print changed
#print nowchanged
#print howaboutnow
#print "##############################################"
if changed or nowchanged or howaboutnow:
self.insertDiscoveredClassifiers(cl1, cl2, clP1, clP2, exploreIter) #Includes subsumption if activated.
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# SELECTION METHODS
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#test method to force tree and rule crossover for testing purposes
def selectTreeRule(self):
setList = copy.deepcopy(self.correctSet) #correct set is a list of reference IDs
if len(setList) > 2:
selectList = [None, None]
tree_list = []
rule_list = []
for index in setList:
cl = self.popSet[index]
if cl.isTree:
tree_list.append(cl)
else:
rule_list.append(cl)
if len(tree_list) != 0:
random_index = random.randrange(0,len(tree_list))
selectList[0] = tree_list[random_index]
else:
raise NameError("Empty tree list")
if len(rule_list) != 0:
random_index = random.randrange(0,len(rule_list))
selectList[1] = rule_list[random_index]
else:
raise NameError("Empty rule list")
elif len(setList) == 2:
selectList = [self.popSet[setList[0]],self.popSet[setList[1]]]
elif len(setList) == 1:
selectList = [self.popSet[setList[0]],self.popSet[setList[0]]]
else:
print("ClassifierSet: Error in parent selection.")
return selectList
def selectClassifierRW(self):
""" Selects parents using roulette wheel selection according to the fitness of the classifiers. """
setList = copy.deepcopy(self.correctSet) #correct set is a list of reference IDs
if len(setList) > 2:
selectList = [None, None]
currentCount = 0
while currentCount < 2:
fitSum = self.getFitnessSum(setList)
choiceP = random.random() * fitSum
i=0
sumCl = self.popSet[setList[i]].fitness
while choiceP > sumCl:
i=i+1
sumCl += self.popSet[setList[i]].fitness
selectList[currentCount] = self.popSet[setList[i]] #store reference to the classifier
setList.remove(setList[i])
currentCount += 1
elif len(setList) == 2:
selectList = [self.popSet[setList[0]],self.popSet[setList[1]]]
elif len(setList) == 1:
selectList = [self.popSet[setList[0]],self.popSet[setList[0]]]
else:
print("ClassifierSet: Error in parent selection.")
return selectList
def selectClassifierT(self,exploreIter):
""" Selects parents using tournament selection according to the fitness of the classifiers. """
setList = copy.deepcopy(self.correctSet) #correct set is a list of reference IDs
if len(setList) > 2:
selectList = [None, None]
currentCount = 0
while currentCount < 2:
tSize = int(len(setList)*cons.theta_sel)
posList = random.sample(setList,tSize)
bestF = 0
bestC = setList[0]
percentExperience = None
for j in posList:
if self.popSet[j].epochComplete:
percentExperience = 1.0
else:
#print exploreIter - self.popSet[j].initTimeStamp
percentExperience = (exploreIter - self.popSet[j].initTimeStamp) / float(cons.env.formatData.numTrainInstances)
if percentExperience <= 0 or percentExperience > 1:
print('tournament selection error')
print(percentExperience)
#if self.popSet[j].fitness > bestF:
if self.popSet[j].fitness*percentExperience > bestF:
bestF = self.popSet[j].fitness*percentExperience
bestC = j
setList.remove(j) #select without re-sampling
selectList[currentCount] = self.popSet[bestC]
currentCount += 1
elif len(setList) == 2:
selectList = [self.popSet[setList[0]],self.popSet[setList[1]]]
elif len(setList) == 1:
selectList = [self.popSet[setList[0]],self.popSet[setList[0]]]
else:
print("ClassifierSet: Error in parent selection.")
return selectList
#Original Tournament Selection
# def selectClassifierT(self):
# """ Selects parents using tournament selection according to the fitness of the classifiers. """
# setList = copy.deepcopy(self.correctSet) #correct set is a list of reference IDs
# if len(setList) > 2:
# selectList = [None, None]
# currentCount = 0
# while currentCount < 2:
# tSize = int(len(setList)*cons.theta_sel)
# posList = random.sample(setList,tSize)
#
# bestF = 0
# bestC = setList[0]
# for j in posList:
# if self.popSet[j].fitness > bestF:
# bestF = self.popSet[j].fitness
# bestC = j
# setList.remove(j) #select without re-sampling
# selectList[currentCount] = self.popSet[bestC]
# currentCount += 1
# elif len(setList) == 2:
# selectList = [self.popSet[setList[0]],self.popSet[setList[1]]]
# elif len(setList) == 1:
# selectList = [self.popSet[setList[0]],self.popSet[setList[0]]]
# else:
# print "ClassifierSet: Error in parent selection."
#
# return selectList
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# SUBSUMPTION METHODS
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def subsumeClassifier(self, exploreIter, cl=None, cl1P=None, cl2P=None):
""" Tries to subsume a classifier in the parents. If no subsumption is possible it tries to subsume it in the current set. """
if cl.isTree:
self.addGAClassifierToPopulation(cl, exploreIter)
if cl1P!=None and cl1P.subsumes(cl):
self.microPopSize += 1
# if cl1P.epochComplete:
# self.ECPopSize += 1
# else:
# self.ENCPopSize += 1
cl1P.updateNumerosity(1)
elif cl2P!=None and cl2P.subsumes(cl):
self.microPopSize += 1
# if cl2P.epochComplete:
# self.ECPopSize += 1
# else:
# self.ENCPopSize += 1
cl2P.updateNumerosity(1)
else:
self.subsumeClassifier2(cl, exploreIter); #Try to subsume in the correct set.
def subsumeClassifier2(self, cl, exploreIter):
""" Tries to subsume a classifier in the correct set. If no subsumption is possible the classifier is simply added to the population considering
the possibility that there exists an identical classifier. """
choices = []
for ref in self.correctSet:
if self.popSet[ref].subsumes(cl):
choices.append(ref)
if len(choices) > 0: #Randomly pick one classifier to be subsumer
choice = int(random.random()*len(choices))
self.popSet[choices[choice]].updateNumerosity(1)
self.microPopSize += 1
# if self.popSet[choices[choice]].epochComplete:
# self.ECPopSize += 1
# else:
# self.ENCPopSize += 1
cons.timer.stopTimeSubsumption()
return
cons.timer.stopTimeSubsumption()
self.addGAClassifierToPopulation(cl, exploreIter) #If no subsumer was found, check for identical classifier, if not then add the classifier to the population
def doCorrectSetSubsumption(self):
""" Executes correct set subsumption. The correct set subsumption looks for the most general subsumer classifier in the correct set
and subsumes all classifiers that are more specific than the selected one. """
subsumer = None
for ref in self.correctSet:
cl = self.popSet[ref]
if cl.isSubsumer():
if subsumer == None or cl.isMoreGeneral(subsumer):
subsumer = cl
if subsumer != None: #If a subsumer was found, subsume all more specific classifiers in the correct set
i=0
while i < len(self.correctSet):
ref = self.correctSet[i]
if subsumer.isMoreGeneral(self.popSet[ref]):
subsumer.updateNumerosity(self.popSet[ref].numerosity)
# if subsumer.epochComplete:
# if not self.popSet[ref].epochComplete:
# self.ECPopSize += 1
# self.ENCPopSize -= 1
# else:
# if self.popSet[ref].epochComplete:
# self.ECPopSize -= 1
# self.ENCPopSize += 1
self.removeMacroClassifier(ref)
self.deleteFromMatchSet(ref)