forked from ryanurbs/ExSTraCS_2.0
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exstracs_output.py
368 lines (322 loc) · 18.8 KB
/
exstracs_output.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
"""
Name: ExSTraCS_OutputFileManager.py
Authors: Ryan Urbanowicz - Written at Dartmouth College, Hanover, NH, USA
Contact: [email protected]
Created: April 25, 2014
Modified: August 25,2014
Description: This module contains the methods for generating the different output files generated by ExSTraCS.
These files are generated at each learning checkpoint, and the last iteration. These include...
writePopStats: Summary of the population statistics
writePop: Outputs a snapshot of the entire rule population including classifier conditions, classes, and parameters.
attCo_Occurence: Calculates and outputs co-occurrence scores for each attribute pair in the dataset.
---------------------------------------------------------------------------------------------------------------------------------------------------------
ExSTraCS V2.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_at import *
import copy
#------------------------------------------------------
class OutputFileManager:
def writePopStats(self, outFile, trainEval, testEval, exploreIter, pop, correct):
""" Makes output text file which includes all of the parameter settings used in the run as well as all of the evaluation stats including Time Track Output. """
if cons.outputSummary:
try:
popStatsOut = open(outFile + '_'+ str(exploreIter)+'_PopStats.txt','w') # Outputs Population run stats
except Exception as inst:
print(type(inst))
print(inst.args)
print(inst)
print('cannot open', outFile + '_'+ str(exploreIter)+'_PopStats.txt')
raise
else:
print("Writing Population Statistical Summary File...")
#Evaluation of pop
popStatsOut.write("Performance Statistics:------------------------------------------------------------------------\n")
popStatsOut.write("Training Accuracy\tTesting Accuracy\tTraining Coverage\tTesting Coverage\n")
if cons.testFile != 'None':
popStatsOut.write(str(trainEval[0])+"\t")
popStatsOut.write(str(testEval[0])+"\t")
popStatsOut.write(str(trainEval[1]) +"\t")
popStatsOut.write(str(testEval[1])+"\n\n")
elif cons.trainFile != 'None':
popStatsOut.write(str(trainEval[0])+"\t")
popStatsOut.write("NA\t")
popStatsOut.write(str(trainEval[1]) +"\t")
popStatsOut.write("NA\n\n")
else:
popStatsOut.write("NA\t")
popStatsOut.write("NA\t")
popStatsOut.write("NA\t")
popStatsOut.write("NA\n\n")
popStatsOut.write("Population Characterization:------------------------------------------------------------------------\n")
popStatsOut.write("MacroPopSize\tMicroPopSize\tGenerality\n")
popStatsOut.write(str(len(pop.popSet))+"\t"+ str(pop.microPopSize)+"\t"+str(pop.aveGenerality)+"\n\n")
popStatsOut.write("SpecificitySum:------------------------------------------------------------------------\n")
headList = cons.env.formatData.trainHeaderList #preserve order of original dataset
for i in range(len(headList)):
if i < len(headList)-1:
popStatsOut.write(str(headList[i])+"\t")
else:
popStatsOut.write(str(headList[i])+"\n")
# Prints out the Specification Sum for each attribute
for i in range(len(pop.attributeSpecList)):
if i < len(pop.attributeSpecList)-1:
popStatsOut.write(str(pop.attributeSpecList[i])+"\t")
else:
popStatsOut.write(str(pop.attributeSpecList[i])+"\n")
popStatsOut.write("\nAccuracySum:------------------------------------------------------------------------\n")
for i in range(len(headList)):
if i < len(headList)-1:
popStatsOut.write(str(headList[i])+"\t")
else:
popStatsOut.write(str(headList[i])+"\n")
# Prints out the Accuracy Weighted Specification Count for each attribute
for i in range(len(pop.attributeAccList)):
if i < len(pop.attributeAccList)-1:
popStatsOut.write(str(pop.attributeAccList[i])+"\t")
else:
popStatsOut.write(str(pop.attributeAccList[i])+"\n")
if cons.onlyRC: # When RC ONLY, there is no AttributeTrackingGlobalSums
popStatsOut.write("\nAttributeTrackingGlobalSums:----Rule Compaction ONLY, Attribute Tracking not loaded-----------------\n")
for i in range(len(headList)):
if i < len(headList)-1:
popStatsOut.write(str(headList[i])+"\t")
else:
popStatsOut.write(str(headList[i])+"\n")
for i in range(len(headList)):
if i < len(headList)-1:
popStatsOut.write(str(0.0)+"\t")
else:
popStatsOut.write(str(0.0)+"\n")
elif cons.doAttributeTracking:
popStatsOut.write("\nAttributeTrackingGlobalSums:------------------------------------------------------------------------\n")
for i in range(len(headList)):
if i < len(headList)-1:
popStatsOut.write(str(headList[i])+"\t")
else:
popStatsOut.write(str(headList[i])+"\n")
sumGlobalAttTrack = cons.AT.sumGlobalAttTrack()
for i in range(len(sumGlobalAttTrack)):
if i < len(sumGlobalAttTrack)-1:
popStatsOut.write(str(sumGlobalAttTrack[i])+"\t")
else:
popStatsOut.write(str(sumGlobalAttTrack[i])+"\n")
else:
popStatsOut.write("\nAttributeTrackingGlobalSums:----Tracking not applied!-----------------------------------------------\n")
for i in range(len(headList)):
if i < len(headList)-1:
popStatsOut.write(str(headList[i])+"\t")
else:
popStatsOut.write(str(headList[i])+"\n")
for i in range(len(headList)):
if i < len(headList)-1:
popStatsOut.write(str(0.0)+"\t")
else:
popStatsOut.write(str(0.0)+"\n")
#Time Track ---------------------------------------------------------------------------------------------------------
popStatsOut.write("\nRun Time(in minutes):------------------------------------------------------------------------\n")
popStatsOut.write(cons.timer.reportTimes())
popStatsOut.write("\nCorrectTrackerSave:------------------------------------------------------------------------\n")
for i in range(len(correct)):
popStatsOut.write(str(correct[i])+"\t")
popStatsOut.close()
else:
pass
def writePop(self, outFile, exploreIter, pop):
""" Writes a tab delimited text file specifying the evolved rule population, including conditions, phenotypes, and all rule parameters. """
if cons.outputPopulation:
try:
rulePopOut = open(outFile + '_'+ str(exploreIter)+'_RulePop.txt','w') # Outputs tab delimited text file of rule population and respective rule stats
except Exception as inst:
print(type(inst))
print(inst.args)
print(inst)
print('cannot open', outFile + '_'+ str(exploreIter)+'_RulePop.txt')
raise
else:
print("Writing Population as Data File...")
rulePopOut.write("Specified\tCondition\tPhenotype\tFitness\tAccuracy\tNumerosity\tAveMatchSetSize\tTimeStampGA\tInitTimeStamp\tSpecificity\tDeletionProb\tCorrectCount\tMatchCount\tCorrectCover\tMatchCover\tEpochComplete\n")
#Write each classifier--------------------------------------------------------------------------------------------------------------------------------------
for cl in pop.popSet:
rulePopOut.write(str(cl.printClassifier()))
rulePopOut.close()
else:
pass
def attCo_Occurence(self, outFile, exploreIter, pop):
""" Calculates pairwise attribute co-occurence througout all rules in the population."""
if cons.outputAttCoOccur:
print("Calculating Attribute Co-occurence Scores...")
dataLink = cons.env.formatData
dim = dataLink.numAttributes
maxAtts = 50 #Test 10
attList = []
#-------------------------------------------------------
# IDENTIFY ATTRIBUBTES FOR CO-OCCRRENCE EVALUATION
#-------------------------------------------------------
if dim <= maxAtts:
for i in range(0,dim):
attList.append(i)
else:
tempList = copy.deepcopy(pop.attributeSpecList)
tempList = sorted(tempList,reverse=True)
maxVal = tempList[maxAtts]
overflow = []
for i in range(0,dim):
if pop.attributeSpecList[i] >= maxVal: #get roughly the top 50 specified attributes. (may grab some extras, depending on
attList.append(i)
if pop.attributeSpecList[i] == maxVal:
overflow.append(i)
while len(attList) > maxAtts:
target = random.choice(overflow)
attList.remove(target)
overflow.remove(target)
#print(attList)
#-------------------------------------------------------
# CO-OCCRRENCE EVALUATION
#-------------------------------------------------------
comboList = []
castList = [None,None,0,0] #att1, att2, Specificity, Accuracy Weighted Specificity
count = 0
dim = dataLink.numAttributes
#Specify all attribute pairs.
for i in range(0, len(attList)-1):
for j in range(i+1,len(attList)):
comboList.append(copy.deepcopy(castList))
comboList[count][0] = dataLink.trainHeaderList[attList[i]]
comboList[count][1] = dataLink.trainHeaderList[attList[j]]
count += 1
for cl in pop.popSet:
count = 0
for i in range(len(attList)-1):
for j in range(i+1,len(attList)):
if attList[i] in cl.specifiedAttList and attList[j] in cl.specifiedAttList:
comboList[count][2] += cl.numerosity
comboList[count][3] += cl.numerosity * cl.accuracy
count += 1
tupleList = []
for i in comboList:
tupleList.append((i[0],i[1],i[2],i[3]))
sortedComboList = sorted(tupleList,key=lambda test: test[3], reverse=True)
print("Writing Attribute Co-occurence scores as data file...")
try:
f = open(outFile + '_'+ str(exploreIter)+ '_CO.txt', 'w')
except Exception as inst:
print(type(inst))
print(inst.args)
print(inst)
print('cannot open', outFile + '_'+ str(exploreIter)+ '_CO.txt')
raise
else:
for i in range(len(sortedComboList)):
for j in range(len(sortedComboList[0])): #att1, att2, count, AWcount
if j < len(sortedComboList[0])-1:
f.write(str(sortedComboList[i][j])+'\t')
else:
f.write(str(sortedComboList[i][j])+'\n')
f.close()
else:
pass
def save_tracking(self, exploreIter, outFile):
if cons.doAttributeTracking:
""" Prints out Attribute Tracking scores to txt file. """
try:
f = open(outFile + '_'+ str(exploreIter + 1)+'_AttTrack.txt','w') # Outputs tab delimited text file of rule population and respective rule stats
except Exception as inst:
print(type(inst))
print(inst.args)
print(inst)
print('cannot open', outFile + '_'+ str(exploreIter + 1)+'_AttTrack.txt')
raise
else:
print("Writing Attribute Tracking as Data File...")
trackingSums = cons.AT.attAccuracySums
#-------------------------------------------------------------------
f.write(str(cons.labelInstanceID) + '\t') #Write InstanceID label
for att in cons.env.formatData.trainHeaderList:
f.write(str(att) + '\t')
f.write(str(cons.labelPhenotype)+ '\n') #Write phenotype label
#---------------------------------------------------------------
for i in range(len(trackingSums)):
trackList = trackingSums[i]
f.write(str(cons.env.formatData.trainFormatted[i][2])+ '\t') #Write InstanceID
for att in trackList:
f.write(str(att) + '\t')
f.write(str(cons.env.formatData.trainFormatted[i][1]) +'\n') #Write phenotype
f.close()
def writePredictions(self, exploreIter, outFile, predictionList, realList, predictionSets):
if cons.outputTestPredictions:
""" Prints out the Testing Predictions to txt file."""
try:
f = open(outFile + '_'+ str(exploreIter + 1)+'_Predictions.txt','w') # Outputs tab delimited text file of rule population and respective rule stats
except Exception as inst:
print(type(inst))
print(inst.args)
print(inst)
print('cannot open', outFile + '_'+ str(exploreIter + 1)+'_Predictions.txt')
raise
else:
print("Writing Predictions to File...")
f.write(str(cons.labelInstanceID) + '\t'+'Endpoint Predictions'+'\t' + 'True Endpoint')
if cons.env.formatData.discretePhenotype:
for eachClass in cons.env.formatData.phenotypeList:
f.write('\t'+ str(eachClass))
f.write('\n')
for i in range(len(predictionList)):
f.write(str(cons.env.formatData.testFormatted[i][2])+ '\t') #Write InstanceID
f.write(str(predictionList[i])+'\t'+str(realList[i]))
if cons.env.formatData.discretePhenotype:
propList = []
for eachClass in cons.env.formatData.phenotypeList:
propList.append(predictionSets[i][eachClass])
for each in propList:
f.write('\t'+ str(each))
f.write('\n')
f.close()
def editPopStats(self, testEval):
""" Takes an existing popStatsFile and edits it to report Testing Accuracy performance, and Testing coverage on a specified testing dataset. """
try:
fileObject = open(cons.popRebootPath+"_PopStats.txt", 'rU') # opens each datafile to read.
except Exception as inst:
print(type(inst))
print(inst.args)
print(inst)
print('cannot open', cons.popRebootPath+"_PopStats.txt")
raise
#Grab the existing file information (only a couple items will change, i.e. testing acccuracy and testing coverage)
fileStorage = []
for each in fileObject:
fileStorage.append(each)
fileObject.close()
try:
popStatsOut = open(cons.popRebootPath+'_PopStats_Testing.txt','w') # Outputs Population run stats
except Exception as inst:
print(type(inst))
print(inst.args)
print(inst)
print('cannot open', cons.popRebootPath+'_PopStats_Testing.txt')
raise
else:
print("Writing Population Statistical Summary File...")
for i in range(2):
popStatsOut.write(fileStorage[i])
tempList = fileStorage[2].strip().split('\t')
popStatsOut.write(str(tempList[0])+"\t")
popStatsOut.write(str(testEval[0])+"\t")
popStatsOut.write(str(tempList[2]) +"\t")
popStatsOut.write(str(testEval[1])+"\n\n")
for i in range(4,36):
popStatsOut.write(fileStorage[i])
popStatsOut.close()