├── test ├── __init__.py ├── DataSets │ ├── Tests │ │ ├── NumericTests │ │ │ ├── numericFloatsNAN.csv │ │ │ ├── numericFloats.csv │ │ │ ├── numericInts.csv │ │ │ ├── numericFloatsMissing.csv │ │ │ ├── numericFloatsString.csv │ │ │ ├── .DS_Store │ │ │ ├── numericInts.xlsx │ │ │ ├── numericFloats.xlsx │ │ │ ├── numericFloatsNAN.xlsx │ │ │ ├── numericFloatsString.xlsx │ │ │ └── numericFloatsMissing.xlsx │ │ ├── .DS_Store │ │ ├── MissingFeatureData.csv │ │ ├── MissingFeatureAndPhenotypeData.csv │ │ ├── StringData.xlsx │ │ ├── StringData2.xlsx │ │ ├── StringData.csv │ │ ├── ContinuousPhenotype.xlsx │ │ ├── MissingFeatureData.xlsx │ │ ├── SpecificityTests │ │ │ ├── .DS_Store │ │ │ ├── Specifics.csv │ │ │ └── Specifics.xlsx │ │ ├── StringData2.csv │ │ ├── MissingFeatureAndPhenotypeData.xlsx │ │ └── ContinuousPhenotype.csv │ ├── .DS_Store │ └── Real │ │ ├── .DS_Store │ │ ├── Multiplexer6.csv │ │ └── Multiplexer6Modified.csv ├── test_StringEnumerator.py └── test_XCS.py ├── setup.cfg ├── requirements.txt ├── defaultExportDir ├── .DS_Store ├── savedModel1 ├── savedModel2 └── savedModel3 ├── .travis.yml ├── MANIFEST.in ├── skXCS ├── Environment.py ├── __init__.py ├── Timer.py ├── PredictionArray.py ├── IterationRecord.py ├── DataManagement.py ├── StringEnumerator.py ├── ClassifierSet.py ├── Classifier.py └── XCS.py ├── setup.py ├── README.md └── LICENSE /test/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md 3 | 4 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | 2 | numpy==1.16.2 3 | pandas==0.24.2 4 | scikit-learn==0.20.3 5 | -------------------------------------------------------------------------------- /test/DataSets/Tests/NumericTests/numericFloatsNAN.csv: -------------------------------------------------------------------------------- 1 | N1,N2,N3,class ,2,0,2 1,,4,0.3 0.5,2,4, -------------------------------------------------------------------------------- /test/DataSets/Tests/NumericTests/numericFloats.csv: -------------------------------------------------------------------------------- 1 | N1,N2,N3,class 1,2,0,2 1,0.1,4,0.3 0.5,2,-0.2,2 -------------------------------------------------------------------------------- /test/DataSets/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UrbsLab/scikit-XCS/HEAD/test/DataSets/.DS_Store -------------------------------------------------------------------------------- /test/DataSets/Tests/NumericTests/numericInts.csv: -------------------------------------------------------------------------------- 1 | N1,N2,N3,class 2 | 1,2,1,2 3 | 1,3,4,3 4 | 2,2,1,2 -------------------------------------------------------------------------------- /defaultExportDir/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UrbsLab/scikit-XCS/HEAD/defaultExportDir/.DS_Store -------------------------------------------------------------------------------- /defaultExportDir/savedModel1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UrbsLab/scikit-XCS/HEAD/defaultExportDir/savedModel1 -------------------------------------------------------------------------------- /defaultExportDir/savedModel2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UrbsLab/scikit-XCS/HEAD/defaultExportDir/savedModel2 -------------------------------------------------------------------------------- /defaultExportDir/savedModel3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UrbsLab/scikit-XCS/HEAD/defaultExportDir/savedModel3 -------------------------------------------------------------------------------- /test/DataSets/Real/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UrbsLab/scikit-XCS/HEAD/test/DataSets/Real/.DS_Store -------------------------------------------------------------------------------- /test/DataSets/Tests/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UrbsLab/scikit-XCS/HEAD/test/DataSets/Tests/.DS_Store -------------------------------------------------------------------------------- /test/DataSets/Tests/NumericTests/numericFloatsMissing.csv: -------------------------------------------------------------------------------- 1 | N1,N2,N3,class 2 | 1,2,, 3 | 1,,4,0.3 4 | ,2,-0.2, -------------------------------------------------------------------------------- /test/DataSets/Tests/NumericTests/numericFloatsString.csv: -------------------------------------------------------------------------------- 1 | N1,N2,N3,class 2 | ,2,0,2 3 | 1,,4,0.3 4 | 0.5,2,hi,2 -------------------------------------------------------------------------------- /test/DataSets/Tests/MissingFeatureData.csv: -------------------------------------------------------------------------------- 1 | N1,N2,N3,phenotype,N4 1,NA,1,1,4 2,0,1,0,NaN 4,,1,1,2 NULL,1,NA,0,1 6,,1,1,1 -------------------------------------------------------------------------------- /test/DataSets/Tests/MissingFeatureAndPhenotypeData.csv: -------------------------------------------------------------------------------- 1 | N1,N2,N3,phenotype,N4 1,,1,1,4 2,0,1,NA,NaN 4,NaN,1,,2 ,1,,0,1 6,,1,1,1 -------------------------------------------------------------------------------- /test/DataSets/Tests/StringData.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UrbsLab/scikit-XCS/HEAD/test/DataSets/Tests/StringData.xlsx -------------------------------------------------------------------------------- /test/DataSets/Tests/StringData2.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UrbsLab/scikit-XCS/HEAD/test/DataSets/Tests/StringData2.xlsx -------------------------------------------------------------------------------- /test/DataSets/Tests/StringData.csv: -------------------------------------------------------------------------------- 1 | N1,N2,N3,phenotype male,1.2,young,china female,0.3,NA,japan female,-0.4,old,china NA,0,young,russia -------------------------------------------------------------------------------- /test/DataSets/Tests/NumericTests/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UrbsLab/scikit-XCS/HEAD/test/DataSets/Tests/NumericTests/.DS_Store -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - '3.7' 4 | install: 5 | - pip install -r requirements.txt 6 | script: python3 -m unittest 7 | -------------------------------------------------------------------------------- /test/DataSets/Tests/ContinuousPhenotype.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UrbsLab/scikit-XCS/HEAD/test/DataSets/Tests/ContinuousPhenotype.xlsx -------------------------------------------------------------------------------- /test/DataSets/Tests/MissingFeatureData.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UrbsLab/scikit-XCS/HEAD/test/DataSets/Tests/MissingFeatureData.xlsx -------------------------------------------------------------------------------- /test/DataSets/Tests/SpecificityTests/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UrbsLab/scikit-XCS/HEAD/test/DataSets/Tests/SpecificityTests/.DS_Store -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | include LICENSE 3 | global-include test/* 4 | global-include *.csv 5 | global-exclude defaultExportDir/* 6 | prune venv/ -------------------------------------------------------------------------------- /test/DataSets/Tests/NumericTests/numericInts.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UrbsLab/scikit-XCS/HEAD/test/DataSets/Tests/NumericTests/numericInts.xlsx -------------------------------------------------------------------------------- /test/DataSets/Tests/StringData2.csv: -------------------------------------------------------------------------------- 1 | N1,N2,N3,phenotype 2 | male,1.2,young,china 3 | female,0.3,NA, 4 | female,-0.4,old,china 5 | NA,0,young,russia -------------------------------------------------------------------------------- /test/DataSets/Tests/NumericTests/numericFloats.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UrbsLab/scikit-XCS/HEAD/test/DataSets/Tests/NumericTests/numericFloats.xlsx -------------------------------------------------------------------------------- /test/DataSets/Tests/SpecificityTests/Specifics.csv: -------------------------------------------------------------------------------- 1 | N1,N2,N3,class 1,1,1,1 2,1,,2 3,2,2,3 4,3,3,4 5,4,4,5 6,5,5,6 7,6,6,7 8,7,7,8 9,8,8,8 10,9,9,9 11,10,10,10 -------------------------------------------------------------------------------- /test/DataSets/Tests/SpecificityTests/Specifics.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UrbsLab/scikit-XCS/HEAD/test/DataSets/Tests/SpecificityTests/Specifics.xlsx -------------------------------------------------------------------------------- /test/DataSets/Tests/NumericTests/numericFloatsNAN.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UrbsLab/scikit-XCS/HEAD/test/DataSets/Tests/NumericTests/numericFloatsNAN.xlsx -------------------------------------------------------------------------------- /test/DataSets/Tests/MissingFeatureAndPhenotypeData.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UrbsLab/scikit-XCS/HEAD/test/DataSets/Tests/MissingFeatureAndPhenotypeData.xlsx -------------------------------------------------------------------------------- /test/DataSets/Tests/NumericTests/numericFloatsString.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UrbsLab/scikit-XCS/HEAD/test/DataSets/Tests/NumericTests/numericFloatsString.xlsx -------------------------------------------------------------------------------- /test/DataSets/Tests/NumericTests/numericFloatsMissing.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UrbsLab/scikit-XCS/HEAD/test/DataSets/Tests/NumericTests/numericFloatsMissing.xlsx -------------------------------------------------------------------------------- /test/DataSets/Tests/ContinuousPhenotype.csv: -------------------------------------------------------------------------------- 1 | N1,N2,N3,N4,N5,class 1,3,2,1,2,12 2,6,1,1,2,11 3,9,4,1,2,10 4,2,3,2,3,9 5,0,7,2,3,8 6,5,5,2,7,7 7,1,6,1,0,6 8,2,0,8,0,5 9,3,7,0,0,4 10,8,8,1,0,3 11,7,6,0,1,2 12,6,12,3,1,1 -------------------------------------------------------------------------------- /skXCS/Environment.py: -------------------------------------------------------------------------------- 1 | 2 | from skXCS.DataManagement import DataManagement 3 | 4 | class Environment: 5 | def __init__(self,X,y,xcs): 6 | self.dataRef = 0 7 | self.formatData = DataManagement(X,y,xcs) 8 | self.max_payoff = xcs.max_payoff 9 | 10 | self.currentTrainState = self.formatData.trainFormatted[0][self.dataRef] 11 | self.currentTrainPhenotype = self.formatData.trainFormatted[1][self.dataRef] 12 | 13 | def getTrainState(self): 14 | return self.currentTrainState 15 | 16 | def newInstance(self): 17 | if self.dataRef < self.formatData.numTrainInstances-1: 18 | self.dataRef+=1 19 | self.currentTrainState = self.formatData.trainFormatted[0][self.dataRef] 20 | self.currentTrainPhenotype = self.formatData.trainFormatted[1][self.dataRef] 21 | else: 22 | self.resetDataRef() 23 | 24 | def resetDataRef(self): 25 | self.dataRef = 0 26 | self.currentTrainState = self.formatData.trainFormatted[0][self.dataRef] 27 | self.currentTrainPhenotype = self.formatData.trainFormatted[1][self.dataRef] 28 | 29 | def executeAction(self,action): 30 | if action == self.currentTrainPhenotype: 31 | return self.max_payoff 32 | return 0 33 | 34 | -------------------------------------------------------------------------------- /test/DataSets/Real/Multiplexer6.csv: -------------------------------------------------------------------------------- 1 | A_0,A_1,R_0,R_1,R_2,R_3,class 2 | 0,0,0,0,0,0,0 3 | 0,0,0,0,0,1,0 4 | 0,0,0,0,1,0,0 5 | 0,0,0,0,1,1,0 6 | 0,0,0,1,0,0,0 7 | 0,0,0,1,0,1,0 8 | 0,0,0,1,1,0,0 9 | 0,0,0,1,1,1,0 10 | 0,0,1,0,0,0,1 11 | 0,0,1,0,0,1,1 12 | 0,0,1,0,1,0,1 13 | 0,0,1,0,1,1,1 14 | 0,0,1,1,0,0,1 15 | 0,0,1,1,0,1,1 16 | 0,0,1,1,1,0,1 17 | 0,0,1,1,1,1,1 18 | 0,1,0,0,0,0,0 19 | 0,1,0,0,0,1,0 20 | 0,1,0,0,1,0,0 21 | 0,1,0,0,1,1,0 22 | 0,1,0,1,0,0,1 23 | 0,1,0,1,0,1,1 24 | 0,1,0,1,1,0,1 25 | 0,1,0,1,1,1,1 26 | 0,1,1,0,0,0,0 27 | 0,1,1,0,0,1,0 28 | 0,1,1,0,1,0,0 29 | 0,1,1,0,1,1,0 30 | 0,1,1,1,0,0,1 31 | 0,1,1,1,0,1,1 32 | 0,1,1,1,1,0,1 33 | 0,1,1,1,1,1,1 34 | 1,0,0,0,0,0,0 35 | 1,0,0,0,0,1,0 36 | 1,0,0,0,1,0,1 37 | 1,0,0,0,1,1,1 38 | 1,0,0,1,0,0,0 39 | 1,0,0,1,0,1,0 40 | 1,0,0,1,1,0,1 41 | 1,0,0,1,1,1,1 42 | 1,0,1,0,0,0,0 43 | 1,0,1,0,0,1,0 44 | 1,0,1,0,1,0,1 45 | 1,0,1,0,1,1,1 46 | 1,0,1,1,0,0,0 47 | 1,0,1,1,0,1,0 48 | 1,0,1,1,1,0,1 49 | 1,0,1,1,1,1,1 50 | 1,1,0,0,0,0,0 51 | 1,1,0,0,0,1,1 52 | 1,1,0,0,1,0,0 53 | 1,1,0,0,1,1,1 54 | 1,1,0,1,0,0,0 55 | 1,1,0,1,0,1,1 56 | 1,1,0,1,1,0,0 57 | 1,1,0,1,1,1,1 58 | 1,1,1,0,0,0,0 59 | 1,1,1,0,0,1,1 60 | 1,1,1,0,1,0,0 61 | 1,1,1,0,1,1,1 62 | 1,1,1,1,0,0,0 63 | 1,1,1,1,0,1,1 64 | 1,1,1,1,1,0,0 65 | 1,1,1,1,1,1,1 -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | with open("README.md","r") as fh: 4 | ld = fh.read() 5 | 6 | setup( 7 | name = 'scikit-XCS', 8 | packages = ['skXCS'], 9 | version = '1.0.8', 10 | license='License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 11 | description = 'XCS Learning Classifier System', 12 | long_description_content_type="text/markdown", 13 | author = 'Robert Zhang, Ryan J. Urbanowicz', 14 | author_email = 'robertzh@seas.upenn.edu,ryanurb@upenn.edu', 15 | url = 'https://github.com/UrbsLab/scikit-XCS', 16 | download_url = 'https://github.com/UrbsLab/scikit-XCS/archive/refs/tags/v_1.0.8.tar.gz', 17 | keywords = ['machine learning','data analysis','data science','learning classifier systems','xcs'], 18 | install_requires=['numpy','pandas','scikit-learn'], 19 | classifiers=[ 20 | 'Development Status :: 5 - Production/Stable', 21 | 'Intended Audience :: Developers', 22 | 'Intended Audience :: Information Technology', 23 | 'Intended Audience :: Science/Research', 24 | 'Topic :: Utilities', 25 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 26 | 'Programming Language :: Python :: 3', 27 | 'Programming Language :: Python :: 3.4', 28 | 'Programming Language :: Python :: 3.5', 29 | 'Programming Language :: Python :: 3.6', 30 | 'Programming Language :: Python :: 3.7' 31 | ], 32 | long_description=ld 33 | ) 34 | -------------------------------------------------------------------------------- /skXCS/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | scikit-XCS was primarily developed at the University of Pennsylvania by: 3 | - Robert Zhang (robertzh@seas.upenn.edu) 4 | - Ryan J. Urbanowicz (ryanurb@upenn.edu) 5 | - and many more generous open source contributors 6 | 7 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software 8 | and associated documentation files (the "Software"), to deal in the Software without restriction, 9 | including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 10 | and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, 11 | subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all copies or substantial 14 | portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT 17 | LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 19 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 20 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | """ 22 | 23 | from .Classifier import Classifier 24 | from .ClassifierSet import ClassifierSet 25 | from .DataManagement import DataManagement 26 | from .IterationRecord import IterationRecord 27 | from .Environment import Environment 28 | from .PredictionArray import PredictionArray 29 | from .StringEnumerator import StringEnumerator 30 | from .Timer import Timer 31 | from .XCS import XCS -------------------------------------------------------------------------------- /skXCS/Timer.py: -------------------------------------------------------------------------------- 1 | # Import Required Modules--------------- 2 | import time 3 | 4 | 5 | # -------------------------------------- 6 | 7 | class Timer: 8 | def __init__(self): 9 | # Global Time objects 10 | self.globalStartRef = time.time() 11 | self.globalTime = 0.0 12 | self.globalAdd = 0 13 | 14 | # Match Time Variables 15 | self.startRefMatching = 0.0 16 | self.globalMatching = 0.0 17 | 18 | # Deletion Time Variables 19 | self.startRefDeletion = 0.0 20 | self.globalDeletion = 0.0 21 | 22 | # Subsumption Time Variables 23 | self.startRefSubsumption = 0.0 24 | self.globalSubsumption = 0.0 25 | 26 | # GA Time Variables 27 | self.startRefGA = 0.0 28 | self.globalGA = 0.0 29 | 30 | # Evaluation Time Variables 31 | self.startRefEvaluation = 0.0 32 | self.globalEvaluation = 0.0 33 | 34 | # ************************************************************ 35 | 36 | def startTimeMatching(self): 37 | """ Tracks MatchSet Time """ 38 | self.startRefMatching = time.time() 39 | 40 | def stopTimeMatching(self): 41 | """ Tracks MatchSet Time """ 42 | diff = time.time() - self.startRefMatching 43 | self.globalMatching += diff 44 | 45 | # ************************************************************ 46 | 47 | def startTimeDeletion(self): 48 | """ Tracks Deletion Time """ 49 | self.startRefDeletion = time.time() 50 | 51 | def stopTimeDeletion(self): 52 | """ Tracks Deletion Time """ 53 | diff = time.time() - self.startRefDeletion 54 | self.globalDeletion += diff 55 | 56 | # ************************************************************ 57 | def startTimeSubsumption(self): 58 | """Tracks Subsumption Time """ 59 | self.startRefSubsumption = time.time() 60 | 61 | def stopTimeSubsumption(self): 62 | """Tracks Subsumption Time """ 63 | diff = time.time() - self.startRefSubsumption 64 | self.globalSubsumption += diff 65 | 66 | # ************************************************************ 67 | 68 | def startTimeGA(self): 69 | """ Tracks Selection Time """ 70 | self.startRefGA = time.time() 71 | 72 | def stopTimeGA(self): 73 | """ Tracks Selection Time """ 74 | diff = time.time() - self.startRefGA 75 | self.globalGA += diff 76 | 77 | # ************************************************************ 78 | def startTimeEvaluation(self): 79 | """ Tracks Evaluation Time """ 80 | self.startRefEvaluation = time.time() 81 | 82 | def stopTimeEvaluation(self): 83 | """ Tracks Evaluation Time """ 84 | diff = time.time() - self.startRefEvaluation 85 | self.globalEvaluation += diff 86 | 87 | # ************************************************************ 88 | 89 | def updateGlobalTimer(self): 90 | """ Set the global end timer, call at very end of algorithm. """ 91 | self.globalTime = (time.time() - self.globalStartRef) + self.globalAdd 92 | return self.globalTime 93 | -------------------------------------------------------------------------------- /skXCS/PredictionArray.py: -------------------------------------------------------------------------------- 1 | import random 2 | import numpy as np 3 | 4 | class PredictionArray: 5 | def __init__(self,population,xcs): 6 | self.predictionArray = {} 7 | self.fitnesses = {} 8 | self.actionList = xcs.env.formatData.phenotypeList 9 | self.probabilities = {} 10 | self.hasMatch = len(population.matchSet) != 0 11 | 12 | for eachClass in self.actionList: 13 | self.predictionArray[eachClass] = 0.0 14 | self.fitnesses[eachClass] = 0.0 15 | 16 | for ref in population.matchSet: 17 | cl = population.popSet[ref] 18 | self.predictionArray[cl.action] += cl.prediction*cl.fitness 19 | self.fitnesses[cl.action] += cl.fitness 20 | 21 | for eachClass in self.actionList: 22 | if self.fitnesses[eachClass] != 0: 23 | self.predictionArray[eachClass] /= self.fitnesses[eachClass] 24 | else: 25 | self.predictionArray[eachClass] = 0 26 | 27 | #Populate Probabilities 28 | probabilitySum = 0 29 | for action,value in sorted(self.predictionArray.items()): 30 | self.probabilities[action] = value 31 | probabilitySum += value 32 | if probabilitySum == 0: 33 | for action, prob in sorted(self.probabilities.items()): 34 | self.probabilities[action] = 0 35 | else: 36 | for action, prob in sorted(self.probabilities.items()): 37 | self.probabilities[action] = prob/probabilitySum 38 | 39 | def getBestValue(self): 40 | return max(self.predictionArray,key=self.predictionArray.get) 41 | 42 | def getValue(self,action): 43 | return self.predictionArray[action] 44 | 45 | ##*************** Action selection functions **************** 46 | def randomActionWinner(self): 47 | """ Selects an action randomly. The function assures that the chosen action is represented by at least one classifier. """ 48 | while True: 49 | ret = random.choice(self.actionList) 50 | if self.fitnesses[ret] != 0: 51 | break 52 | return ret 53 | 54 | def bestActionWinner(self): 55 | """ Selects the action in the prediction array with the best value. 56 | *MODIFIED so that in the case of a tie between actions - an action is selected randomly between the tied highest actions. """ 57 | highVal = 0.0 58 | for action,value in self.predictionArray.items(): 59 | if value > highVal: 60 | highVal = value 61 | bestIndexList = [] 62 | for action,value in self.predictionArray.items(): 63 | if value == highVal: 64 | bestIndexList.append(action) 65 | #return random.choice(bestIndexList) 66 | return bestIndexList[0] 67 | 68 | ##*************** Get ActionProbabilities **************** 69 | def getProbabilities(self): 70 | probabilityList = np.empty(len(sorted(self.probabilities.items()))) 71 | counter = 0 72 | for action,prob in sorted(self.probabilities.items()): 73 | probabilityList[counter] = prob 74 | counter += 1 75 | return probabilityList 76 | -------------------------------------------------------------------------------- /skXCS/IterationRecord.py: -------------------------------------------------------------------------------- 1 | import csv 2 | import numpy as np 3 | 4 | class IterationRecord(): 5 | ''' 6 | IterationRecord Tracks 1 dictionary: 7 | 1) Tracking Dict: Cursory Iteration Evaluation. Frequency determined by trackingFrequency param in eLCS. For each iteration evaluated, it saves: 8 | KEY-iteration number 9 | 0-accuracy (approximate from correct array in eLCS) 10 | 1-average population generality 11 | 2-macropopulation size 12 | 3-micropopulation size 13 | 4-match set size 14 | 5-correct set size 15 | 6-average iteration age of action set classifiers 16 | 7-number of classifiers subsumed (in iteration) 17 | 8-number of crossover operations performed (in iteration) 18 | 9-number of mutation operations performed (in iteration) 19 | 10-number of covering operations performed (in iteration) 20 | 11-number of deleted macroclassifiers performed (in iteration) 21 | 12-total global time at end of iteration 22 | 13-total matching time at end of iteration 23 | 14-total deletion time at end of iteration 24 | 15-total subsumption time at end of iteration 25 | 16-total selection time at end of iteration 26 | 17-total evaluation time at end of iteration 27 | ''' 28 | 29 | def __init__(self): 30 | self.trackingDict = {} 31 | 32 | def addToTracking(self,iterationNumber,accuracy,avgPopGenerality,macroSize,microSize,mSize,aSize,iterAvg, 33 | subsumptionCount,crossoverCount,mutationCount,coveringCount,deletionCount, 34 | globalTime,matchingTime,deletionTime,subsumptionTime,gaTime,evaluationTime): 35 | 36 | self.trackingDict[iterationNumber] = [accuracy,avgPopGenerality,macroSize,microSize,mSize,aSize,iterAvg, 37 | subsumptionCount,crossoverCount,mutationCount,coveringCount,deletionCount, 38 | globalTime,matchingTime,deletionTime,subsumptionTime,gaTime,evaluationTime] 39 | 40 | def exportTrackingToCSV(self,filename='iterationData.csv'): 41 | #Exports each entry in Tracking Array as a column 42 | with open(filename,mode='w') as file: 43 | writer = csv.writer(file,delimiter=',',quotechar='"',quoting=csv.QUOTE_MINIMAL) 44 | 45 | writer.writerow(["Iteration","Accuracy (approx)", "Average Population Generality","Macropopulation Size", 46 | "Micropopulation Size", "Match Set Size", "Action Set Size", "Average Iteration Age of Action Set Classifiers", 47 | "# Classifiers Subsumed in Iteration","# Crossover Operations Performed in Iteration","# Mutation Operations Performed in Iteration", 48 | "# Covering Operations Performed in Iteration","# Deletion Operations Performed in Iteration", 49 | "Total Global Time","Total Matching Time","Total Deletion Time","Total Subsumption Time","Total GA Time","Total Evaluation Time"]) 50 | 51 | for k,v in sorted(self.trackingDict.items()): 52 | writer.writerow([k,v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7],v[8],v[9],v[10],v[11],v[12],v[13],v[14],v[15],v[16],v[17]]) 53 | file.close() -------------------------------------------------------------------------------- /skXCS/DataManagement.py: -------------------------------------------------------------------------------- 1 | 2 | import numpy as np 3 | 4 | class DataManagement: 5 | def __init__(self,X,y,xcs): 6 | self.savedRawTrainingData = [X,y] 7 | self.numAttributes = X.shape[1] 8 | self.attributeInfoType = [0] * self.numAttributes # stores false (d) or true (c) depending on its type, which points to parallel reference in one of the below 2 arrays 9 | self.attributeInfoContinuous = [[np.inf,-np.inf] for _ in range(self.numAttributes)] #stores continuous ranges and NaN otherwise 10 | self.attributeInfoDiscrete = [0] * self.numAttributes # stores arrays of discrete values or NaN otherwise. 11 | for i in range(0,self.numAttributes): 12 | self.attributeInfoDiscrete[i] = AttributeInfoDiscreteElement() 13 | self.discretePhenotype = True 14 | self.phenotypeList = [] # Stores all possible discrete phenotype values 15 | 16 | self.isDefault = True # Is discrete attribute limit an int or string 17 | try: 18 | int(xcs.discrete_attribute_limit) 19 | except: 20 | self.isDefault = False 21 | 22 | self.numTrainInstances = X.shape[0] # The number of instances in the training data 23 | self.discriminateClasses(y) 24 | self.isBinaryClassification = len(self.phenotypeList) == 2 25 | self.numberOfActions = len(self.phenotypeList) 26 | 27 | self.discriminateAttributes(X, xcs) 28 | self.characterizeAttributes(X) 29 | self.trainFormatted = self.formatData(X, y) 30 | 31 | def discriminateClasses(self,phenotypes): 32 | currentPhenotypeIndex = 0 33 | classCount = {} 34 | while (currentPhenotypeIndex < self.numTrainInstances): 35 | target = phenotypes[currentPhenotypeIndex] 36 | if target in self.phenotypeList: 37 | classCount[target]+=1 38 | else: 39 | self.phenotypeList.append(target) 40 | classCount[target] = 1 41 | currentPhenotypeIndex+=1 42 | 43 | def discriminateAttributes(self,features,xcs): 44 | for att in range(self.numAttributes): 45 | attIsDiscrete = True 46 | if self.isDefault: 47 | currentInstanceIndex = 0 48 | stateDict = {} 49 | while attIsDiscrete and len(list(stateDict.keys())) <= xcs.discrete_attribute_limit and currentInstanceIndex < self.numTrainInstances: 50 | target = features[currentInstanceIndex,att] 51 | if target in list(stateDict.keys()): 52 | stateDict[target] += 1 53 | elif np.isnan(target): 54 | pass 55 | else: 56 | stateDict[target] = 1 57 | currentInstanceIndex+=1 58 | 59 | if len(list(stateDict.keys())) > xcs.discrete_attribute_limit: 60 | attIsDiscrete = False 61 | elif xcs.discrete_attribute_limit == "c": 62 | if att in xcs.specified_attributes: 63 | attIsDiscrete = False 64 | else: 65 | attIsDiscrete = True 66 | elif xcs.discrete_attribute_limit == "d": 67 | if att in xcs.specified_attributes: 68 | attIsDiscrete = True 69 | else: 70 | attIsDiscrete = False 71 | 72 | if attIsDiscrete: 73 | self.attributeInfoType[att] = False 74 | else: 75 | self.attributeInfoType[att] = True 76 | 77 | 78 | def characterizeAttributes(self,features): 79 | for currentFeatureIndexInAttributeInfo in range(self.numAttributes): 80 | for currentInstanceIndex in range(self.numTrainInstances): 81 | target = features[currentInstanceIndex,currentFeatureIndexInAttributeInfo] 82 | if not self.attributeInfoType[currentFeatureIndexInAttributeInfo]:#if attribute is discrete 83 | if target in self.attributeInfoDiscrete[currentFeatureIndexInAttributeInfo].distinctValues or np.isnan(target): 84 | pass 85 | else: 86 | self.attributeInfoDiscrete[currentFeatureIndexInAttributeInfo].distinctValues.append(target) 87 | else: #if attribute is continuous 88 | if np.isnan(target): 89 | pass 90 | elif float(target) > self.attributeInfoContinuous[currentFeatureIndexInAttributeInfo][1]: 91 | self.attributeInfoContinuous[currentFeatureIndexInAttributeInfo][1] = float(target) 92 | elif float(target) < self.attributeInfoContinuous[currentFeatureIndexInAttributeInfo][0]: 93 | self.attributeInfoContinuous[currentFeatureIndexInAttributeInfo][0] = float(target) 94 | else: 95 | pass 96 | 97 | def formatData(self,features,phenotypes): 98 | formatted = np.insert(features,self.numAttributes,phenotypes,1) #Combines features and phenotypes into one array 99 | np.random.shuffle(formatted) 100 | shuffledFeatures = formatted[:,:-1].tolist() 101 | shuffledLabels = formatted[:,self.numAttributes].tolist() 102 | for i in range(len(shuffledFeatures)): 103 | for j in range(len(shuffledFeatures[i])): 104 | if np.isnan(shuffledFeatures[i][j]): 105 | shuffledFeatures[i][j] = None 106 | if np.isnan(shuffledLabels[i]): 107 | shuffledLabels[i] = None 108 | return [shuffledFeatures,shuffledLabels] 109 | 110 | 111 | class AttributeInfoDiscreteElement(): 112 | def __init__(self): 113 | self.distinctValues = [] 114 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Master Status: [![Build Status](https://travis-ci.com/UrbsLab/scikit-xCS.svg?branch=master)](https://travis-ci.com/UrbsLab/scikit-XCS) 2 | 3 | # scikit-XCS 4 | 5 | The scikit-XCS package includes a sklearn-compatible Python implementation of XCS, the most popular and best studied learning classifier system algorithm to date. In general, Learning Classifier Systems (LCSs) are a classification of Rule Based Machine Learning Algorithms that have been shown to perform well on problems involving high amounts of heterogeneity and epistasis. Well designed LCSs are also highly human interpretable. LCS variants have been shown to adeptly handle supervised and reinforced, classification and regression, online and offline learning problems, as well as missing or unbalanced data. These characteristics of versatility and interpretability give LCSs a wide range of potential applications, notably those in biomedicine. This package is **still under active development** and we encourage you to check back on this repository for updates. 6 | 7 | This version of scikit-XCS is suitable for single step, classification problems. It has not yet been developed for multi-step reinforcement learning problems nor regression problems. Within these bounds however, scikit-XCS can be applied to almost any supervised classification data set and supports: 8 | 9 | 15 | 16 | Built into this code, is a strategy to 'automatically' detect from the loaded data, these relevant above characteristics so that they don't need to be parameterized at initialization. 17 | 18 | The core Scikit package only supports numeric data. However, an additional StringEnumerator Class is provided that allows quick data conversion from any type of data into pure numeric data, making it possible for natively string/non-numeric data to be run by scikit-XCS. 19 | 20 | In addition, powerful data tracking collection methods are built into the scikit package, that continuously tracks features every iteration such as: 21 | 22 | 31 | 32 | These values can then be exported as a csv after training is complete for analysis using the built in "export_iteration_tracking_data" method. 33 | 34 | In addition, the package includes functionality that allows the final rule population to be exported as a csv after training. 35 | 36 | ## Usage 37 | For more information on how to use scikit-XCS, please refer to the [scikit-XCS User Guide](https://github.com/UrbsLab/scikit-XCS/blob/master/scikit-XCS%20User%20Guide.ipynb) Jupyter Notebook inside this repository. 38 | 39 | ## Usage TLDR 40 | ```python 41 | #Import Necessary Packages/Modules 42 | from skXCS import XCS 43 | import numpy as np 44 | import pandas as pd 45 | from sklearn.model_selection import cross_val_score 46 | 47 | #Load Data Using Pandas 48 | data = pd.read_csv('myDataFile.csv') #REPLACE with your own dataset .csv filename 49 | dataFeatures = data.drop(actionLabel,axis=1).values #DEFINE actionLabel variable as the Str at the top of your dataset's action column 50 | dataActions = data[actionLabel].values 51 | 52 | #Shuffle Data Before CV 53 | formatted = np.insert(dataFeatures,dataFeatures.shape[1],dataActions,1) 54 | np.random.shuffle(formatted) 55 | dataFeatures = np.delete(formatted,-1,axis=1) 56 | dataActions = formatted[:,-1] 57 | 58 | #Initialize XCS Model 59 | model = XCS(learning_iterations = 5000) 60 | 61 | #3-fold CV 62 | print(np.mean(cross_val_score(model,dataFeatures,dataActions,cv=3))) 63 | ``` 64 | 65 | ## License 66 | Please see the repository [license](https://github.com/UrbsLab/scikit-XCS/blob/master/LICENSE) for the licensing and usage information for scikit-XCS. 67 | 68 | Generally, we have licensed scikit-XCS to make it as widely usable as possible. 69 | 70 | ## Installation 71 | scikit-XCS is built on top of the following Python packages: 72 |
    73 |
  1. numpy
  2. 74 |
  3. pandas
  4. 75 |
  5. scikit-learn
  6. 76 |
77 | 78 | Once the prerequisites are installed, you can install scikit-XCS with a pip command: 79 | ``` 80 | pip/pip3 install scikit-XCS 81 | ``` 82 | We strongly recommend you use Python 3. scikit-XCS does not support Python 2, given its depreciation in Jan 1 2020. If something goes wrong during installation, make sure that your pip is up to date and try again. 83 | ``` 84 | pip/pip3 install --upgrade pip 85 | ``` 86 | 87 | ## Contributing to scikit-XCS 88 | scikit-XCS is an open source project and we'd love if you could suggest changes! 89 | 90 |
    91 |
  1. Fork the project repository to your personal account and clone this copy to your local disk
  2. 92 |
  3. Create a branch from master to hold your changes: (e.g. git checkout -b my-contribution-branch)
  4. 93 |
  5. Commit changes on your branch. Remember to never work on any other branch but your own!
  6. 94 |
  7. When you are done, push your changes to your forked GitHub repository with git push -u origin my-contribution-branch
  8. 95 |
  9. Create a pull request to send your changes to the scikit-XCS maintainers for review.
  10. 96 |
97 | 98 | **Before submitting your pull request** 99 | 100 | If your contribution changes XCS in any way, make sure you update the Jupyter Notebook documentation and the README with relevant details. If your contribution involves any code changes, update the project unit tests to test your code changes, and make sure your code is properly commented to explain your rationale behind non-obvious coding practices. 101 | 102 | **After submitting your pull request** 103 | 104 | After submitting your pull request, Travis CI will run all of the project's unit tests. Check back shortly after submitting to make sure your code passes these checks. If any checks come back failed, do your best to address the errors. 105 | -------------------------------------------------------------------------------- /test/DataSets/Real/Multiplexer6Modified.csv: -------------------------------------------------------------------------------- 1 | A_0,A_1,R_0,R_1,R_2,R_3,Class 2 | 0,0,0,1,0,0,0 3 | 0,1,1,0,1,1,0 4 | 1,1,1,0,1,0,0 5 | 1,0,0,0,0,0,0 6 | 1,0,0,0,1,1,1 7 | 0,1,0,1,1,0,1 8 | 0,1,1,0,1,0,0 9 | 0,1,1,0,0,0,0 10 | 0,0,0,0,0,0,0 11 | 1,1,1,0,1,1,1 12 | 1,1,1,1,1,0,0 13 | 0,1,0,1,1,1,1 14 | 1,0,1,0,0,0,0 15 | 0,1,0,0,1,1,0 16 | 1,1,1,0,0,1,1 17 | 0,1,1,1,1,1,1 18 | 1,1,1,1,1,0,0 19 | 0,0,0,0,0,0,0 20 | 0,0,1,0,0,0,1 21 | 1,1,1,0,1,1,1 22 | 1,0,1,1,1,0,1 23 | 1,1,0,1,0,0,0 24 | 1,1,1,0,0,1,1 25 | 0,0,0,1,0,1,0 26 | 1,1,0,0,1,0,0 27 | 1,1,1,0,1,0,0 28 | 0,1,0,0,0,1,0 29 | 0,0,1,1,1,0,1 30 | 1,1,1,1,1,1,1 31 | 0,1,1,1,1,1,1 32 | 1,0,1,1,0,0,0 33 | 0,1,1,0,0,1,0 34 | 0,0,0,1,0,1,0 35 | 0,0,1,0,1,1,1 36 | 0,0,1,0,1,0,1 37 | 0,1,0,1,1,0,1 38 | 1,0,1,1,0,0,0 39 | 1,0,1,0,0,1,0 40 | 0,0,0,0,0,0,0 41 | 1,1,0,0,0,1,1 42 | 0,1,0,0,1,0,0 43 | 0,1,0,1,0,0,1 44 | 0,1,1,0,1,0,0 45 | 1,1,0,0,1,1,1 46 | 0,1,0,1,1,1,1 47 | 1,0,0,1,0,0,0 48 | 1,1,0,1,1,1,1 49 | 1,1,0,0,1,1,1 50 | 1,1,0,0,0,0,0 51 | 1,1,0,1,1,1,1 52 | 1,0,0,0,0,0,0 53 | 0,1,0,1,1,1,1 54 | 1,0,0,1,0,1,0 55 | 1,1,0,0,0,0,0 56 | 1,1,1,0,0,0,0 57 | 0,1,1,0,1,1,0 58 | 0,0,0,1,0,1,0 59 | 1,0,0,0,0,1,0 60 | 0,1,1,1,1,1,1 61 | 0,0,0,1,0,1,0 62 | 0,1,1,0,1,0,0 63 | 0,0,1,1,0,0,1 64 | 0,0,0,1,0,0,0 65 | 0,1,0,0,1,1,0 66 | 1,1,0,0,0,1,1 67 | 1,1,1,0,0,1,1 68 | 0,0,1,1,1,0,1 69 | 0,1,0,0,1,0,0 70 | 1,1,0,1,0,0,0 71 | 1,1,1,0,1,1,1 72 | 0,1,0,0,1,1,0 73 | 1,1,1,0,1,0,0 74 | 1,1,0,1,1,1,1 75 | 1,0,0,1,1,1,1 76 | 1,1,1,1,1,1,1 77 | 0,0,0,1,0,1,0 78 | 0,1,1,0,1,0,0 79 | 1,0,1,1,1,0,1 80 | 1,0,0,1,1,0,1 81 | 0,1,0,0,0,1,0 82 | 0,1,0,1,0,0,1 83 | 0,1,1,1,0,1,1 84 | 1,1,1,1,1,0,0 85 | 0,0,0,1,0,1,0 86 | 0,1,0,1,1,0,1 87 | 1,0,0,0,1,0,1 88 | 0,1,0,1,0,1,1 89 | 1,1,0,0,0,1,1 90 | 0,0,0,1,1,1,0 91 | 1,1,0,1,1,0,0 92 | 0,0,0,0,0,0,0 93 | 0,0,0,0,0,0,0 94 | 0,0,1,1,0,1,1 95 | 1,1,1,1,1,0,0 96 | 1,1,1,1,1,1,1 97 | 1,0,0,1,1,1,1 98 | 1,1,0,0,0,0,0 99 | 0,0,1,1,0,1,1 100 | 0,1,0,0,0,0,0 101 | 0,0,1,1,1,0,1 102 | 0,0,0,0,0,1,0 103 | 0,1,1,1,1,1,1 104 | 0,1,0,1,1,0,1 105 | 1,1,0,1,1,0,0 106 | 0,0,1,0,0,0,1 107 | 1,0,1,1,1,0,1 108 | 1,0,0,1,1,1,1 109 | 0,0,1,0,0,1,1 110 | 1,1,0,0,0,1,1 111 | 0,1,0,1,1,0,1 112 | 0,0,1,0,1,1,1 113 | 1,0,0,0,0,0,0 114 | 0,0,1,0,0,0,1 115 | 1,0,1,1,0,1,0 116 | 1,0,1,1,1,0,1 117 | 1,0,0,1,1,0,1 118 | 0,0,0,0,0,1,0 119 | 0,0,1,0,0,1,1 120 | 1,1,1,1,1,0,0 121 | 0,0,1,1,1,1,1 122 | 0,1,0,0,1,0,0 123 | 0,0,1,0,1,0,1 124 | 0,1,1,1,1,0,1 125 | 0,0,1,0,1,1,1 126 | 1,0,1,0,0,1,0 127 | 1,1,1,1,1,0,0 128 | 0,1,0,0,0,1,0 129 | 1,0,0,0,0,1,0 130 | 1,1,1,1,1,1,1 131 | 1,1,0,1,0,0,0 132 | 0,0,0,0,1,1,0 133 | 1,0,1,1,1,0,1 134 | 0,0,1,1,1,0,1 135 | 0,0,0,1,0,0,0 136 | 1,1,1,0,0,0,0 137 | 1,0,0,1,1,1,1 138 | 1,0,1,0,1,0,1 139 | 1,1,1,1,1,0,0 140 | 0,0,1,1,0,0,1 141 | 1,1,0,1,0,1,1 142 | 0,1,1,0,0,0,0 143 | 0,1,0,0,1,0,0 144 | 0,1,0,1,0,0,1 145 | 0,1,1,1,0,0,1 146 | 0,0,0,0,1,1,0 147 | 0,0,1,0,0,0,1 148 | 0,1,0,1,1,0,1 149 | 1,1,1,1,0,1,1 150 | 0,0,0,0,1,1,0 151 | 0,1,1,0,0,1,0 152 | 1,1,0,1,1,1,1 153 | 0,1,0,0,1,0,0 154 | 1,0,1,1,1,1,1 155 | 0,1,1,0,0,0,0 156 | 0,1,1,0,1,0,0 157 | 0,1,0,1,1,0,1 158 | 0,0,0,1,1,1,0 159 | 1,1,0,1,1,0,0 160 | 1,1,0,1,0,0,0 161 | 1,0,0,1,1,1,1 162 | 0,0,0,0,0,0,0 163 | 0,0,1,1,1,1,1 164 | 0,1,0,1,0,1,1 165 | 1,1,0,1,0,1,1 166 | 1,1,0,1,0,0,0 167 | 0,1,0,1,0,0,1 168 | 1,0,1,1,1,1,1 169 | 0,0,1,1,0,1,1 170 | 0,1,0,1,1,1,1 171 | 0,0,1,1,0,0,1 172 | 1,0,0,1,1,1,1 173 | 0,1,1,1,1,0,1 174 | 1,0,0,0,1,1,1 175 | 1,0,0,0,0,1,0 176 | 0,1,0,0,1,0,0 177 | 0,0,1,1,0,0,1 178 | 1,0,0,1,0,1,0 179 | 1,0,0,0,0,1,0 180 | 0,0,1,0,1,1,1 181 | 0,0,0,1,0,0,0 182 | 1,0,1,0,1,1,1 183 | 0,0,0,1,1,0,0 184 | 0,1,0,0,0,1,0 185 | 0,1,0,0,0,1,0 186 | 0,0,1,1,1,0,1 187 | 1,0,0,0,1,1,1 188 | 0,1,1,0,0,0,0 189 | 1,1,0,1,0,0,0 190 | 1,0,1,1,1,1,1 191 | 0,1,1,0,0,0,0 192 | 1,1,1,1,0,0,0 193 | 0,0,1,0,1,0,1 194 | 0,0,1,0,0,0,1 195 | 0,1,0,0,0,0,0 196 | 0,1,1,0,0,0,0 197 | 1,0,1,0,1,1,1 198 | 1,0,1,1,0,1,0 199 | 1,1,1,0,0,0,0 200 | 0,1,1,1,0,0,1 201 | 1,1,0,0,0,1,1 202 | 1,0,0,0,1,0,1 203 | 1,0,1,1,1,0,1 204 | 0,0,0,0,1,1,0 205 | 1,0,1,0,0,1,0 206 | 1,1,1,1,1,0,0 207 | 0,0,0,0,1,1,0 208 | 1,0,1,0,1,1,1 209 | 0,0,1,1,1,1,1 210 | 0,0,1,0,0,0,1 211 | 1,1,1,1,1,1,1 212 | 1,0,0,1,1,1,1 213 | 0,1,0,1,1,1,1 214 | 0,1,1,1,1,1,1 215 | 0,1,1,0,0,1,0 216 | 0,0,1,0,1,0,1 217 | 1,0,0,1,0,0,0 218 | 0,1,0,0,0,0,0 219 | 1,0,0,1,0,0,0 220 | 0,0,0,1,1,0,0 221 | 1,1,0,1,0,0,0 222 | 1,0,0,1,0,0,0 223 | 1,1,0,0,1,1,1 224 | 0,1,1,1,0,1,1 225 | 0,0,0,0,1,1,0 226 | 0,0,1,1,0,1,1 227 | 1,0,1,1,1,1,1 228 | 0,0,0,1,0,0,0 229 | 1,1,1,1,0,1,1 230 | 1,1,1,0,1,0,0 231 | 1,0,0,1,0,1,0 232 | 1,1,0,1,0,0,0 233 | 0,1,1,1,1,1,1 234 | 1,1,0,1,1,1,1 235 | 0,0,0,1,1,0,0 236 | 0,1,1,0,0,0,0 237 | 1,1,1,0,0,0,0 238 | 0,0,0,1,0,0,0 239 | 1,0,0,1,1,0,1 240 | 1,0,1,1,0,0,0 241 | 1,1,1,1,0,0,0 242 | 0,1,1,0,0,0,0 243 | 0,1,1,0,0,1,0 244 | 0,0,0,0,1,1,0 245 | 1,1,0,1,0,1,1 246 | 1,1,1,0,0,1,1 247 | 1,1,0,1,0,1,1 248 | 0,1,1,1,1,0,1 249 | 1,1,0,0,1,1,1 250 | 1,1,1,1,1,0,0 251 | 0,0,1,1,1,0,1 252 | 1,0,1,1,1,1,1 253 | 1,0,0,0,0,0,0 254 | 0,0,0,1,0,0,0 255 | 1,0,0,0,1,0,1 256 | 1,0,1,1,1,1,1 257 | 0,1,1,1,1,1,1 258 | 1,1,0,0,0,1,1 259 | 1,1,0,0,0,1,1 260 | 1,1,0,1,1,0,0 261 | 1,1,0,1,0,0,0 262 | 0,1,1,1,0,1,1 263 | 0,0,0,1,0,1,0 264 | 0,0,0,1,1,0,0 265 | 1,0,0,0,0,1,0 266 | 0,1,0,0,1,0,0 267 | 1,0,1,1,0,1,0 268 | 1,0,0,1,0,0,0 269 | 0,0,1,1,1,0,1 270 | 1,1,1,0,0,0,0 271 | 0,1,1,0,1,0,0 272 | 1,1,1,0,1,1,1 273 | 1,1,0,0,0,0,0 274 | 1,0,1,0,1,1,1 275 | 1,1,0,0,1,1,1 276 | 1,1,1,1,0,0,0 277 | 1,0,1,0,1,0,1 278 | 1,0,0,1,1,1,1 279 | 0,0,0,0,1,1,0 280 | 1,0,0,0,1,0,1 281 | 0,0,0,1,1,0,0 282 | 1,0,0,1,0,0,0 283 | 0,0,0,0,1,0,0 284 | 1,1,0,1,1,0,0 285 | 0,1,0,0,0,0,0 286 | 0,1,0,1,0,0,1 287 | 0,0,1,0,0,1,1 288 | 0,0,0,1,1,0,0 289 | 0,0,1,1,0,0,1 290 | 0,1,0,1,0,0,1 291 | 1,0,0,0,0,1,0 292 | 0,0,1,0,1,1,1 293 | 0,0,0,1,0,1,0 294 | 0,1,1,1,1,1,1 295 | 1,0,0,0,0,0,0 296 | 1,1,1,0,0,1,1 297 | 0,0,0,1,0,1,0 298 | 1,0,0,0,1,1,1 299 | 0,1,0,1,0,1,1 300 | 0,0,0,0,1,1,0 301 | 1,0,0,1,0,1,0 302 | 1,1,0,0,1,1,1 303 | 0,0,0,0,0,1,0 304 | 0,1,1,1,0,1,1 305 | 0,1,0,1,1,0,1 306 | 0,0,1,0,1,1,1 307 | 0,1,1,0,0,1,0 308 | 1,0,1,1,0,0,0 309 | 0,0,0,0,1,1,0 310 | 0,1,0,0,1,0,0 311 | 0,1,1,1,0,0,1 312 | 1,0,1,0,0,0,0 313 | 1,0,1,0,1,0,1 314 | 0,0,0,0,0,1,0 315 | 0,0,0,1,1,1,0 316 | 0,1,1,1,1,1,1 317 | 1,0,1,0,0,1,0 318 | 0,0,0,1,1,0,0 319 | 1,1,1,0,0,0,0 320 | 0,1,0,0,0,0,0 321 | 1,0,0,0,1,1,1 322 | 0,0,1,0,0,1,1 323 | 0,0,1,0,0,0,1 324 | 1,1,1,1,1,1,1 325 | 1,0,1,0,0,1,0 326 | 0,0,1,0,0,0,1 327 | 1,0,0,0,1,1,1 328 | 0,0,0,0,0,1,0 329 | 0,0,0,1,1,1,0 330 | 0,0,0,0,0,1,0 331 | 1,1,0,0,1,0,0 332 | 0,0,1,0,0,1,1 333 | 0,0,0,1,1,0,0 334 | 0,0,1,1,0,0,1 335 | 1,0,1,1,1,0,1 336 | 0,0,0,0,0,1,0 337 | 0,1,1,0,0,1,0 338 | 1,1,1,1,1,1,1 339 | 0,1,0,1,1,1,1 340 | 0,0,0,0,0,1,0 341 | 0,1,0,0,1,1,0 342 | 1,1,0,0,0,0,0 343 | 0,0,0,0,0,1,0 344 | 0,1,1,0,1,1,0 345 | 0,0,0,0,0,1,0 346 | 1,1,0,0,1,0,0 347 | 0,0,1,1,0,0,1 348 | 0,1,0,1,0,0,1 349 | 0,1,1,1,1,0,1 350 | 1,1,1,0,0,0,0 351 | 0,1,1,1,1,0,1 352 | 1,1,1,1,0,1,1 353 | 1,0,1,1,1,1,1 354 | 1,0,0,0,0,0,0 355 | 1,1,0,1,1,1,1 356 | 0,1,1,0,0,1,0 357 | 0,0,1,0,0,0,1 358 | 1,1,1,1,0,0,0 359 | 0,1,0,1,0,0,1 360 | 0,0,0,0,1,1,0 361 | 0,0,1,0,1,1,1 362 | 0,0,0,0,1,0,0 363 | 0,1,1,0,0,1,0 364 | 1,0,1,1,0,0,0 365 | 1,1,1,0,0,0,0 366 | 1,0,0,1,0,0,0 367 | 1,1,1,0,1,0,0 368 | 0,1,0,0,1,0,0 369 | 1,1,0,0,0,0,0 370 | 0,0,0,0,1,1,0 371 | 0,0,1,1,0,0,1 372 | 1,0,0,0,1,1,1 373 | 1,0,1,1,1,1,1 374 | 1,0,0,1,0,0,0 375 | 0,1,0,0,0,1,0 376 | 0,1,1,0,0,0,0 377 | 1,0,1,0,0,1,0 378 | 1,0,1,1,1,0,1 379 | 0,1,0,1,1,0,1 380 | 1,1,1,0,1,0,0 381 | 0,1,1,0,1,1,0 382 | 0,1,0,0,0,0,0 383 | 0,1,0,1,1,0,1 384 | 0,1,0,0,0,1,0 385 | 1,1,1,1,1,0,0 386 | 0,1,1,0,0,0,0 387 | 1,0,1,1,0,0,0 388 | 0,0,1,1,1,0,1 389 | 1,1,1,1,0,0,0 390 | 1,1,0,0,0,1,1 391 | 1,1,1,0,1,0,0 392 | 1,1,1,1,1,0,0 393 | 0,1,0,1,0,1,1 394 | 0,1,1,0,0,0,0 395 | 1,1,0,0,0,0,0 396 | 1,1,0,0,0,1,1 397 | 0,1,1,1,0,1,1 398 | 1,1,1,1,0,1,1 399 | 0,0,1,0,1,1,1 400 | 0,1,1,0,1,1,0 401 | 1,0,0,1,0,0,0 402 | 0,0,1,0,0,0,1 403 | 0,1,1,1,1,0,1 404 | 1,0,1,0,1,1,1 405 | 1,0,0,1,0,1,0 406 | 0,0,1,0,1,0,1 407 | 1,1,1,0,1,1,1 408 | 1,0,0,1,0,0,0 409 | 1,1,1,1,1,0,0 410 | 1,0,1,1,0,1,0 411 | 0,0,0,1,1,0,0 412 | 1,1,1,0,0,1,1 413 | 0,0,1,0,0,0,1 414 | 1,1,0,1,0,1,1 415 | 1,1,0,0,0,0,0 416 | 1,1,1,0,1,1,1 417 | 0,1,0,1,1,1,1 418 | 1,0,0,0,0,1,0 419 | 1,1,1,0,0,1,1 420 | 1,1,1,0,1,1,1 421 | 1,0,1,0,0,1,0 422 | 0,1,1,1,1,1,1 423 | 1,1,1,0,0,0,0 424 | 0,0,0,1,1,1,0 425 | 0,1,1,1,1,0,1 426 | 0,1,0,1,0,0,1 427 | 0,1,0,0,0,1,0 428 | 1,1,1,1,0,1,1 429 | 1,0,1,0,1,1,1 430 | 0,0,1,0,1,0,1 431 | 0,0,1,0,0,0,1 432 | 1,1,1,0,1,0,0 433 | 1,0,1,1,0,0,0 434 | 0,1,0,1,0,0,1 435 | 1,1,1,0,1,1,1 436 | 0,0,1,1,1,1,1 437 | 0,0,0,0,0,1,0 438 | 1,1,0,1,0,0,0 439 | 0,1,1,0,0,1,0 440 | 0,1,0,0,0,0,0 441 | 1,1,1,0,0,0,0 442 | 0,0,1,0,1,0,1 443 | 1,0,0,0,1,0,1 444 | 0,1,1,1,0,1,1 445 | 0,1,1,1,1,1,1 446 | 0,0,1,0,1,1,1 447 | 1,0,0,0,0,1,0 448 | 1,1,1,0,0,1,1 449 | 0,0,0,1,1,0,0 450 | 0,0,1,1,0,1,1 451 | 0,1,1,1,1,1,1 452 | 0,1,1,0,0,0,0 453 | 1,0,0,1,0,1,0 454 | 0,0,0,0,0,0,0 455 | 1,1,0,0,0,0,0 456 | 1,0,1,1,1,1,1 457 | 1,1,0,0,0,1,1 458 | 1,0,1,1,1,1,1 459 | 0,0,1,1,0,1,1 460 | 0,1,0,0,1,0,0 461 | 1,1,1,0,1,0,0 462 | 0,1,0,0,1,0,0 463 | 0,1,0,0,0,0,0 464 | 0,0,1,0,0,1,1 465 | 0,0,1,1,0,0,1 466 | 0,1,1,1,1,1,1 467 | 1,0,0,0,0,0,0 468 | 0,0,0,0,1,0,0 469 | 0,1,0,0,0,0,0 470 | 1,1,0,0,0,0,0 471 | 0,0,0,0,0,0,0 472 | 0,1,1,0,0,0,0 473 | 1,1,0,0,0,0,0 474 | 0,0,1,0,0,1,1 475 | 0,0,0,0,0,1,0 476 | 0,0,1,1,0,0,1 477 | 1,1,0,1,0,1,1 478 | 0,1,1,1,0,0,1 479 | 0,0,0,1,1,0,0 480 | 1,1,0,1,1,1,1 481 | 1,1,0,1,0,1,1 482 | 0,0,0,1,1,0,0 483 | 0,0,1,0,1,1,1 484 | 1,0,1,0,0,1,0 485 | 1,0,1,1,0,0,0 486 | 1,1,0,0,0,0,0 487 | 0,1,1,1,1,0,1 488 | 0,0,0,1,0,0,0 489 | 1,0,0,0,0,1,0 490 | 0,0,1,0,1,0,1 491 | 0,0,1,0,0,1,1 492 | 0,1,0,0,0,1,0 493 | 1,1,1,0,1,0,0 494 | 1,0,0,0,1,0,1 495 | 1,0,1,0,1,1,1 496 | 1,0,1,1,0,0,0 497 | 1,1,0,0,0,1,1 498 | 0,0,0,1,1,1,0 499 | 1,0,1,1,0,1,0 500 | 1,1,0,1,0,1,1 501 | 0,0,0,0,1,0,0 -------------------------------------------------------------------------------- /skXCS/StringEnumerator.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import numpy as np 4 | import pandas as pd 5 | from warnings import simplefilter 6 | # ignore all future warnings 7 | simplefilter(action='ignore', category=FutureWarning) 8 | 9 | class StringEnumerator: 10 | def __init__(self, inputFile, classLabel): 11 | self.classLabel = classLabel 12 | self.map = {} #Dictionary of header names: Attribute dictionaries 13 | data = pd.read_csv(inputFile, sep=',') # Puts data from csv into indexable np arrays 14 | data = data.fillna("NA") 15 | self.dataFeatures = data.drop(classLabel, axis=1).values #splits into an array of instances 16 | self.dataPhenotypes = data[classLabel].values 17 | self.dataHeaders = data.drop(classLabel, axis=1).columns.values 18 | 19 | tempPhenoArray = np.empty(len(self.dataPhenotypes),dtype=object) 20 | for instanceIndex in range(len(self.dataPhenotypes)): 21 | tempPhenoArray[instanceIndex] = str(self.dataPhenotypes[instanceIndex]) 22 | self.dataPhenotypes = tempPhenoArray 23 | 24 | tempFeatureArray = np.empty((len(self.dataPhenotypes),len(self.dataHeaders)),dtype=object) 25 | for instanceIndex in range(len(self.dataFeatures)): 26 | for attrInst in range(len(self.dataHeaders)): 27 | tempFeatureArray[instanceIndex][attrInst] = str(self.dataFeatures[instanceIndex][attrInst]) 28 | self.dataFeatures = tempFeatureArray 29 | 30 | self.delete_all_instances_without_phenotype() 31 | 32 | def print_invalid_attributes(self): 33 | print("ALL INVALID ATTRIBUTES & THEIR DISTINCT VALUES") 34 | for attr in range(len(self.dataHeaders)): 35 | distinctValues = [] 36 | isInvalid = False 37 | for instIndex in range(len(self.dataFeatures)): 38 | val = self.dataFeatures[instIndex,attr] 39 | if not val in distinctValues and val != "NA": 40 | distinctValues.append(self.dataFeatures[instIndex,attr]) 41 | if val != "NA": 42 | try: 43 | float(val) 44 | except: 45 | isInvalid = True 46 | if isInvalid: 47 | print(str(self.dataHeaders[attr])+": ",end="") 48 | for i in distinctValues: 49 | print(str(i)+"\t",end="") 50 | print() 51 | 52 | distinctValues = [] 53 | isInvalid = False 54 | for instIndex in range(len(self.dataPhenotypes)): 55 | val = self.dataPhenotypes[instIndex] 56 | if not val in distinctValues and val != "NA": 57 | distinctValues.append(self.dataPhenotypes[instIndex]) 58 | if val != "NA": 59 | try: 60 | float(val) 61 | except: 62 | isInvalid = True 63 | if isInvalid: 64 | print(str(self.classLabel)+" (the phenotype): ",end="") 65 | for i in distinctValues: 66 | print(str(i)+"\t",end="") 67 | print() 68 | 69 | def change_class_name(self,newName): 70 | if newName in self.dataHeaders: 71 | raise Exception("New Class Name Cannot Be An Already Existing Data Header Name") 72 | if self.classLabel in self.map.keys(): 73 | self.map[self.newName] = self.map.pop(self.classLabel) 74 | self.classLabel = newName 75 | 76 | def change_header_name(self,currentName,newName): 77 | if newName in self.dataHeaders or newName == self.classLabel: 78 | raise Exception("New Class Name Cannot Be An Already Existing Data Header or Phenotype Name") 79 | if currentName in self.dataHeaders: 80 | headerIndex = np.where(self.dataHeaders == currentName)[0][0] 81 | self.dataHeaders[headerIndex] = newName 82 | if currentName in self.map.keys(): 83 | self.map[newName] = self.map.pop(currentName) 84 | else: 85 | raise Exception("Current Header Doesn't Exist") 86 | 87 | def add_attribute_converter(self,headerName,array):#map is an array of strings, ordered by how it is to be enumerated enumeration 88 | if headerName in self.dataHeaders and not (headerName in self.map): 89 | newAttributeConverter = {} 90 | for index in range(len(array)): 91 | if str(array[index]) != "NA" and str(array[index]) != "" and str(array[index]) != "NaN": 92 | newAttributeConverter[str(array[index])] = str(index) 93 | self.map[headerName] = newAttributeConverter 94 | 95 | def add_attribute_converter_map(self,headerName,map): 96 | if headerName in self.dataHeaders and not (headerName in self.map) and not("" in map) and not("NA" in map) and not("NaN" in map): 97 | self.map[headerName] = map 98 | else: 99 | raise Exception("Invalid Map") 100 | 101 | def add_attribute_converter_random(self,headerName): 102 | if headerName in self.dataHeaders and not (headerName in self.map): 103 | headerIndex = np.where(self.dataHeaders == headerName)[0][0] 104 | uniqueItems = [] 105 | for instance in self.dataFeatures: 106 | if not(instance[headerIndex] in uniqueItems) and instance[headerIndex] != "NA": 107 | uniqueItems.append(instance[headerIndex]) 108 | self.add_attribute_converter(headerName,np.array(uniqueItems)) 109 | 110 | def add_class_converter(self,array): 111 | if not (self.classLabel in self.map.keys()): 112 | newAttributeConverter = {} 113 | for index in range(len(array)): 114 | newAttributeConverter[str(array[index])] = str(index) 115 | self.map[self.classLabel] = newAttributeConverter 116 | 117 | def add_class_converter_random(self): 118 | if not (self.classLabel in self.map.keys()): 119 | uniqueItems = [] 120 | for instance in self.dataPhenotypes: 121 | if not (instance in uniqueItems) and instance != "NA": 122 | uniqueItems.append(instance) 123 | self.add_class_converter(np.array(uniqueItems)) 124 | 125 | def convert_all_attributes(self): 126 | for attribute in self.dataHeaders: 127 | if attribute in self.map.keys(): 128 | i = np.where(self.dataHeaders == attribute)[0][0] 129 | for state in self.dataFeatures:#goes through each instance's state 130 | if (state[i] in self.map[attribute].keys()): 131 | state[i] = self.map[attribute][state[i]] 132 | 133 | if self.classLabel in self.map.keys(): 134 | for state in self.dataPhenotypes: 135 | if (state in self.map[self.classLabel].keys()): 136 | i = np.where(self.dataPhenotypes == state) 137 | self.dataPhenotypes[i] = self.map[self.classLabel][state] 138 | 139 | def delete_attribute(self,headerName): 140 | if headerName in self.dataHeaders: 141 | i = np.where(headerName == self.dataHeaders)[0][0] 142 | self.dataHeaders = np.delete(self.dataHeaders,i) 143 | if headerName in self.map.keys(): 144 | del self.map[headerName] 145 | 146 | newFeatures = [] 147 | for instanceIndex in range(len(self.dataFeatures)): 148 | instance = np.delete(self.dataFeatures[instanceIndex],i) 149 | newFeatures.append(instance) 150 | self.dataFeatures = np.array(newFeatures) 151 | else: 152 | raise Exception("Header Doesn't Exist") 153 | 154 | def delete_all_instances_without_header_data(self,headerName): 155 | newFeatures = [] 156 | newPhenotypes = [] 157 | attributeIndex = np.where(self.dataHeaders == headerName)[0][0] 158 | 159 | for instanceIndex in range(len(self.dataFeatures)): 160 | instance = self.dataFeatures[instanceIndex] 161 | if instance[attributeIndex] != "NA": 162 | newFeatures.append(instance) 163 | newPhenotypes.append(self.dataPhenotypes[instanceIndex]) 164 | 165 | self.dataFeatures = np.array(newFeatures) 166 | self.dataPhenotypes = np.array(newPhenotypes) 167 | 168 | def delete_all_instances_without_phenotype(self): 169 | newFeatures = [] 170 | newPhenotypes = [] 171 | for instanceIndex in range(len(self.dataFeatures)): 172 | instance = self.dataPhenotypes[instanceIndex] 173 | if instance != "NA": 174 | newFeatures.append(self.dataFeatures[instanceIndex]) 175 | newPhenotypes.append(instance) 176 | 177 | self.dataFeatures = np.array(newFeatures) 178 | self.dataPhenotypes = np.array(newPhenotypes) 179 | 180 | def print(self): 181 | isFullNumber = self.check_is_full_numeric() 182 | print("Converted Data Features and Phenotypes") 183 | for header in self.dataHeaders: 184 | print(header,end="\t") 185 | print() 186 | for instanceIndex in range(len(self.dataFeatures)): 187 | for attribute in self.dataFeatures[instanceIndex]: 188 | if attribute != "NA": 189 | if (isFullNumber): 190 | print(float(attribute), end="\t") 191 | else: 192 | print(attribute, end="\t\t") 193 | else: 194 | print("NA", end = "\t") 195 | if self.dataPhenotypes[instanceIndex] != "NA": 196 | if (isFullNumber): 197 | print(float(self.dataPhenotypes[instanceIndex])) 198 | else: 199 | print(self.dataPhenotypes[instanceIndex]) 200 | else: 201 | print("NA") 202 | print() 203 | 204 | def print_attribute_conversions(self): 205 | print("Changed Attribute Conversions") 206 | for headerName,conversions in self.map: 207 | print(headerName + " conversions:") 208 | for original,numberVal in conversions: 209 | print("\tOriginal: "+original+" Converted: "+numberVal) 210 | print() 211 | print() 212 | 213 | def check_is_full_numeric(self): 214 | try: 215 | for instance in self.dataFeatures: 216 | for value in instance: 217 | if value != "NA": 218 | float(value) 219 | for value in self.dataPhenotypes: 220 | if value != "NA": 221 | float(value) 222 | 223 | except: 224 | return False 225 | 226 | return True 227 | 228 | def get_params(self): 229 | if not(self.check_is_full_numeric()): 230 | raise Exception("Features and Phenotypes must be fully numeric") 231 | 232 | newFeatures = [] 233 | newPhenotypes = [] 234 | for instanceIndex in range(len(self.dataFeatures)): 235 | newInstance = [] 236 | for attribute in self.dataFeatures[instanceIndex]: 237 | if attribute == "NA": 238 | newInstance.append(np.nan) 239 | else: 240 | newInstance.append(float(attribute)) 241 | 242 | newFeatures.append(np.array(newInstance,dtype=float)) 243 | if self.dataPhenotypes[instanceIndex] == "NA": #Should never happen. All NaN phenotypes should be removed automatically at init. Just a safety mechanism. 244 | newPhenotypes.append(np.nan) 245 | else: 246 | newPhenotypes.append(float(self.dataPhenotypes[instanceIndex])) 247 | 248 | return self.dataHeaders,self.classLabel,np.array(newFeatures,dtype=float),np.array(newPhenotypes,dtype=float) -------------------------------------------------------------------------------- /test/test_StringEnumerator.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from skXCS.StringEnumerator import StringEnumerator 3 | import pandas as pd 4 | import numpy as np 5 | import os 6 | 7 | THIS_DIR = os.path.dirname(os.path.abspath("test_eLCS.py")) 8 | if THIS_DIR[-4:] == "test": #Patch that ensures testing from Scikit not test directory 9 | THIS_DIR = THIS_DIR[:-5] 10 | 11 | class test_StringEnumerator(unittest.TestCase): 12 | 13 | def testInitMissingData(self): 14 | # Tests if init filters missing data into NAs 15 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Tests/MissingFeatureData.csv") 16 | se = StringEnumerator(dataPath, "phenotype") 17 | cFeatures = np.array([["1.0","NA","1.0","4.0"],["2.0","0.0","1.0","NA"],["4.0","NA","1.0","2.0"],["NA","1.0","NA","1.0"],["6.0","NA","1.0","1.0"]]) 18 | self.assertTrue(np.array_equal(cFeatures,se.dataFeatures)) 19 | 20 | def testInitHeaders(self): 21 | # Tests if init gets the headers correct 22 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Tests/MissingFeatureData.csv") 23 | se = StringEnumerator(dataPath, "phenotype") 24 | cHeaders = np.array(["N1","N2","N3","N4"]) 25 | self.assertTrue(np.array_equal(cHeaders, se.dataHeaders)) 26 | 27 | def testInitFeaturesAndClass(self): 28 | # Tests if init gets the features and class arrays correct 29 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Tests/MissingFeatureData.csv") 30 | se = StringEnumerator(dataPath, "phenotype") 31 | cFeatures = np.array([["1.0", "NA", "1.0", "4.0"], ["2.0", "0.0", "1.0", "NA"], ["4.0", "NA", "1.0", "2.0"], ["NA", "1.0", "NA", "1.0"],["6.0", "NA", "1.0", "1.0"]]) 32 | cClasses = np.array(["1", "0", "1", "0", "1"]) 33 | self.assertTrue(np.array_equal(cFeatures, se.dataFeatures)) 34 | self.assertTrue(np.array_equal(cClasses, se.dataPhenotypes)) 35 | 36 | def testInitFeaturesAndClassRemoval(self): 37 | # Tests if init gets the features and class arrays correct given missing phenotype data 38 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Tests/MissingFeatureAndPhenotypeData.csv") 39 | se = StringEnumerator(dataPath, "phenotype") 40 | cFeatures = np.array([["1.0", "NA", "1.0", "4.0"], ["NA", "1.0", "NA", "1.0"], ["6.0", "NA", "1.0", "1.0"]]) 41 | cClasses = np.array(["1.0", "0.0", "1.0"]) 42 | self.assertTrue(np.array_equal(cFeatures, se.dataFeatures)) 43 | self.assertTrue(np.array_equal(cClasses, se.dataPhenotypes)) 44 | 45 | def testChangeClassAndHeaderNames(self): 46 | # Changes header and class names. Checks map, and classLabel/dataHeaders correctness 47 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Tests/StringData.csv") 48 | se = StringEnumerator(dataPath, "phenotype") 49 | se.change_class_name("country") 50 | se.change_header_name("N1","gender") 51 | se.change_header_name("N2","N1") 52 | se.change_header_name("N1","floats") 53 | se.change_header_name("N3","phenotype") 54 | se.change_header_name("phenotype","age") 55 | cHeaders = np.array(["gender","floats","age"]) 56 | self.assertTrue(np.array_equal(cHeaders,se.dataHeaders)) 57 | self.assertTrue(np.array_equal("country", se.classLabel)) 58 | 59 | def testChangeClassAndHeaderNames2(self): 60 | # Changes header and class names. Checks map, and classLabel/dataHeaders correctness 61 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Tests/StringData.csv") 62 | se = StringEnumerator(dataPath, "phenotype") 63 | se.add_class_converter_random() 64 | se.change_header_name("N1","gender") 65 | se.add_attribute_converter_random("gender") 66 | se.change_header_name("gender","Gender") 67 | se.add_attribute_converter_random("Gender") 68 | se.add_attribute_converter_random("Gender") 69 | se.add_attribute_converter_random("gender") 70 | se.add_attribute_converter_random("N3") 71 | se.change_header_name("N3","Age") 72 | 73 | cHeaders = np.array(["Gender","N2","Age"]) 74 | cMap = {"phenotype":{"china":"0","japan":"1","russia":"2"},"Gender":{"male":"0","female":"1"},"Age":{"young":"0","old":"1"}} 75 | self.assertTrue(np.array_equal(cHeaders,se.dataHeaders)) 76 | self.assertTrue(np.array_equal("phenotype", se.classLabel)) 77 | self.assertTrue(se.map == cMap) 78 | 79 | def testchange_class_nameInvalid(self): 80 | # Changes class name to an existing header name should raise exception 81 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Tests/StringData.csv") 82 | se = StringEnumerator(dataPath, "phenotype") 83 | with self.assertRaises(Exception) as context: 84 | se.change_class_name("N1") 85 | 86 | self.assertTrue("New Class Name Cannot Be An Already Existing Data Header Name" in str(context.exception)) 87 | 88 | 89 | def testchange_header_nameInvalid(self): 90 | # Changes header name to an existing header or class name should raise exception 91 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Tests/StringData.csv") 92 | se = StringEnumerator(dataPath, "phenotype") 93 | with self.assertRaises(Exception) as context: 94 | se.change_header_name("N1","N2") 95 | 96 | self.assertTrue("New Class Name Cannot Be An Already Existing Data Header or Phenotype Name" in str(context.exception)) 97 | 98 | def testchange_header_nameInvalid2(self): 99 | # Changes non existing header name should raise exception 100 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Tests/StringData.csv") 101 | se = StringEnumerator(dataPath, "phenotype") 102 | with self.assertRaises(Exception) as context: 103 | se.change_header_name("N", "N5") 104 | self.assertTrue("Current Header Doesn't Exist" in str(context.exception)) 105 | 106 | def testdelete_attribute(self): 107 | # Deletes attributes and checks map, headers, and arrays for correctness 108 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Tests/StringData.csv") 109 | se = StringEnumerator(dataPath, "phenotype") 110 | se.change_header_name("N1","gender") 111 | se.add_attribute_converter_random("gender") 112 | se.add_attribute_converter_random("N3") 113 | se.delete_attribute("gender") 114 | cHeaders = np.array(["N2","N3"]) 115 | cMap = {"N3": {"young": "0", "old": "1"}} 116 | self.assertTrue(np.array_equal(cHeaders, se.dataHeaders)) 117 | self.assertTrue(np.array_equal("phenotype", se.classLabel)) 118 | self.assertTrue(se.map == cMap) 119 | 120 | def testDeleteNonexistentAttribute(self): 121 | # Deletes nonexistent attribute 122 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Tests/StringData.csv") 123 | se = StringEnumerator(dataPath, "phenotype") 124 | with self.assertRaises(Exception) as context: 125 | se.delete_attribute("N") 126 | self.assertTrue("Header Doesn't Exist" in str(context.exception)) 127 | 128 | def testDeleteInstancesWithMissing(self): 129 | # Deletes instances and checks arrays for correctness 130 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Tests/StringData.csv") 131 | se = StringEnumerator(dataPath, "phenotype") 132 | se.change_header_name("N1","gender") 133 | se.add_attribute_converter_random("gender") 134 | se.add_attribute_converter_random("N3") 135 | se.add_class_converter_random() 136 | se.convert_all_attributes() 137 | se.delete_all_instances_without_header_data("gender") 138 | se.delete_all_instances_without_header_data("N2") 139 | se.delete_all_instances_without_header_data("N3") 140 | cHeaders = np.array(["gender","N2","N3"]) 141 | cMap = {"phenotype":{"china":"0","japan":"1","russia":"2"},"gender":{"male":"0","female":"1"},"N3":{"young":"0","old":"1"}} 142 | cArray = np.array([["0","1.2","0"],["1","-0.4","1"]]) 143 | cPArray = np.array(["0","0"]) 144 | self.assertTrue(np.array_equal(cHeaders, se.dataHeaders)) 145 | self.assertTrue(np.array_equal("phenotype", se.classLabel)) 146 | self.assertTrue(np.array_equal(cArray, se.dataFeatures)) 147 | self.assertTrue(np.array_equal(cPArray, se.dataPhenotypes)) 148 | self.assertTrue(se.map == cMap) 149 | 150 | def testDeleteInstancesWithMissing2(self): 151 | # Deletes instances and checks arrays for correctness 152 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Tests/StringData.csv") 153 | se = StringEnumerator(dataPath, "phenotype") 154 | se.change_header_name("N1","gender") 155 | se.delete_all_instances_without_header_data("gender") 156 | se.delete_all_instances_without_header_data("N2") 157 | se.delete_all_instances_without_header_data("N3") 158 | 159 | se.add_attribute_converter_random("gender") 160 | se.add_attribute_converter_random("N3") 161 | se.add_class_converter_random() 162 | se.convert_all_attributes() 163 | 164 | cHeaders = np.array(["gender","N2","N3"]) 165 | cMap = {"phenotype":{"china":"0"},"gender":{"male":"0","female":"1"},"N3":{"young":"0","old":"1"}} 166 | cArray = np.array([["0","1.2","0"],["1","-0.4","1"]]) 167 | cPArray = np.array(["0","0"]) 168 | self.assertTrue(np.array_equal(cHeaders, se.dataHeaders)) 169 | self.assertTrue(np.array_equal("phenotype", se.classLabel)) 170 | self.assertTrue(np.array_equal(cArray, se.dataFeatures)) 171 | self.assertTrue(np.array_equal(cPArray, se.dataPhenotypes)) 172 | self.assertTrue(se.map == cMap) 173 | 174 | def testNumericCheck(self): 175 | # Checks non missing numeric 176 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Tests/StringData.csv") 177 | se = StringEnumerator(dataPath, "phenotype") 178 | self.assertFalse(se.check_is_full_numeric()) 179 | se.add_attribute_converter_random("N1") 180 | se.convert_all_attributes() 181 | self.assertFalse(se.check_is_full_numeric()) 182 | se.add_attribute_converter_random("N3") 183 | se.add_class_converter_random() 184 | se.convert_all_attributes() 185 | self.assertTrue(se.check_is_full_numeric()) 186 | 187 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Tests/MissingFeatureData.csv") 188 | se2 = StringEnumerator(dataPath, "phenotype") 189 | self.assertTrue(se2.check_is_full_numeric()) 190 | 191 | def testget_paramsFail(self): 192 | # Get params when not all features/class have been enumerated 193 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Tests/StringData.csv") 194 | se = StringEnumerator(dataPath, "phenotype") 195 | with self.assertRaises(Exception) as context: 196 | se.get_params() 197 | self.assertTrue("Features and Phenotypes must be fully numeric" in str(context.exception)) 198 | 199 | def testget_params1(self): 200 | # Get Params Test 201 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Tests/StringData.csv") 202 | se = StringEnumerator(dataPath, "phenotype") 203 | se.change_header_name("N1","gender") 204 | se.change_header_name("N2","floats") 205 | se.change_header_name("N3","age") 206 | se.change_class_name("country") 207 | se.add_attribute_converter_random("gender") 208 | se.add_attribute_converter_random("age") 209 | #se.add_attribute_converter_random("floats") #You can convert "floats" to discrete values as well 210 | se.add_class_converter_random() 211 | se.convert_all_attributes() 212 | dataHeaders,classLabel,dataFeatures,dataPhenotypes = se.get_params() 213 | cHeaders = np.array(["gender","floats","age"]) 214 | cFeatures = np.array([[0,1.2,0],[1,0.3,np.nan],[1,-0.4,1],[np.nan,0,0]]) 215 | cPhenotypes = np.array([0,1,0,2]) 216 | self.assertEqual("country",classLabel) 217 | self.assertTrue(np.array_equal(cHeaders,dataHeaders)) 218 | self.assertTrue(np.allclose(cFeatures,dataFeatures,equal_nan=True)) 219 | self.assertTrue(np.allclose(cPhenotypes, dataPhenotypes, equal_nan=True)) 220 | 221 | def testget_params2(self): 222 | # Get Params Test 223 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Tests/StringData.csv") 224 | se = StringEnumerator(dataPath, "phenotype") 225 | se.change_header_name("N1", "gender") 226 | se.change_header_name("N2", "floats") 227 | se.change_header_name("N3", "age") 228 | se.change_class_name("country") 229 | se.add_attribute_converter("gender",np.array(["female","male","NA","other"])) 230 | se.add_attribute_converter("age",np.array(["old","young"])) 231 | se.add_class_converter_random() 232 | se.convert_all_attributes() 233 | dataHeaders, classLabel, dataFeatures, dataPhenotypes = se.get_params() 234 | cHeaders = np.array(["gender", "floats", "age"]) 235 | cFeatures = np.array([[1, 1.2, 1], [0, 0.3, np.nan], [0, -0.4, 0], [np.nan, 0, 1]]) 236 | cPhenotypes = np.array([0, 1, 0, 2]) 237 | self.assertEqual("country", classLabel) 238 | self.assertTrue(np.array_equal(cHeaders, dataHeaders)) 239 | self.assertTrue(np.allclose(cFeatures, dataFeatures, equal_nan=True)) 240 | self.assertTrue(np.allclose(cPhenotypes, dataPhenotypes, equal_nan=True)) 241 | # 242 | # def testPrintInvalids(self): 243 | # dataPath = os.path.join(THIS_DIR, "test/DataSets/Tests/StringData2.csv") 244 | # se = DataCleanup.StringEnumerator(dataPath, "phenotype") 245 | # se.print_invalid_attributes() -------------------------------------------------------------------------------- /skXCS/ClassifierSet.py: -------------------------------------------------------------------------------- 1 | 2 | import copy 3 | import random 4 | from skXCS.Classifier import Classifier 5 | 6 | class ClassifierSet: 7 | def __init__(self): 8 | self.popSet = [] 9 | self.matchSet = [] 10 | self.actionSet = [] 11 | self.microPopSize = 0 12 | 13 | ####Match Set Creation#### 14 | def createMatchSet(self,state,xcs): 15 | xcs.timer.startTimeMatching() 16 | actionsNotCovered = copy.deepcopy(xcs.env.formatData.phenotypeList) 17 | totalNumActions = len(xcs.env.formatData.phenotypeList) 18 | 19 | for i in range(len(self.popSet)): 20 | classifier = self.popSet[i] 21 | if classifier.match(state,xcs): 22 | self.matchSet.append(i) 23 | if classifier.action in actionsNotCovered: 24 | actionsNotCovered.remove(classifier.action) 25 | 26 | if xcs.env.formatData.isBinaryClassification: 27 | doCovering = totalNumActions - len(actionsNotCovered) < xcs.theta_matching or len(self.matchSet) < 5 #Second condition only holds for 1 covering round 28 | else: 29 | doCovering = totalNumActions - len(actionsNotCovered) < xcs.theta_matching 30 | 31 | while doCovering: 32 | if len(actionsNotCovered) != 0: 33 | action = random.choice(actionsNotCovered) 34 | else: 35 | action = random.choice(copy.deepcopy(xcs.env.formatData.phenotypeList)) 36 | coveredClassifier = Classifier(xcs) 37 | coveredClassifier.initializeWithMatchingStateAndGivenAction(1,state,action,xcs) 38 | self.addClassifierToPopulation(xcs,coveredClassifier,True) 39 | self.matchSet.append(len(self.popSet)-1) 40 | if len(actionsNotCovered) != 0: 41 | actionsNotCovered.remove(action) 42 | xcs.trackingObj.coveringCount += 1 43 | 44 | doCovering = totalNumActions - len(actionsNotCovered) < xcs.theta_matching 45 | 46 | for ref in self.matchSet: 47 | self.popSet[ref].matchCount += 1 48 | xcs.timer.stopTimeMatching() 49 | 50 | def getIdenticalClassifier(self,xcs,newClassifier): 51 | for classifier in self.popSet: 52 | if newClassifier.equals(classifier): 53 | return classifier 54 | return None 55 | 56 | def addClassifierToPopulation(self,xcs,classifier,isCovering): 57 | oldCl = None 58 | if not isCovering: 59 | oldCl = self.getIdenticalClassifier(xcs,classifier) 60 | if oldCl != None: 61 | oldCl.updateNumerosity(1) 62 | self.microPopSize += 1 63 | else: 64 | self.popSet.append(classifier) 65 | self.microPopSize += 1 66 | 67 | ####Action Set Creation#### 68 | def createActionSet(self,action): 69 | for ref in self.matchSet: 70 | if self.popSet[ref].action == action: 71 | self.actionSet.append(ref) 72 | 73 | ####Update Action Set Statistics#### 74 | def updateActionSet(self,reward,xcs): 75 | P = reward 76 | 77 | actionSetNumerositySum = 0 78 | for i in self.actionSet: 79 | ref = self.popSet[i] 80 | actionSetNumerositySum += ref.numerosity 81 | 82 | for cl in self.actionSet: 83 | classifier = self.popSet[cl] 84 | classifier.increaseExperience() 85 | classifier.updatePrediction(P,xcs) 86 | classifier.updatePredictionError(P,xcs) 87 | classifier.updateActionSetSize(actionSetNumerositySum,xcs) 88 | 89 | self.updateFitnessSet(xcs) 90 | if xcs.do_action_set_subsumption: 91 | xcs.timer.startTimeSubsumption() 92 | self.do_action_set_subsumption(xcs) 93 | xcs.timer.stopTimeSubsumption() 94 | 95 | def updateFitnessSet(self,xcs): 96 | accuracySum = 0 97 | accuracies = [] 98 | 99 | i = 0 100 | for clRef in self.actionSet: 101 | classifier = self.popSet[clRef] 102 | accuracies.append(classifier.getAccuracy(xcs)) 103 | accuracySum = accuracySum + accuracies[i]*classifier.numerosity 104 | i+=1 105 | 106 | i = 0 107 | for clRef in self.actionSet: 108 | classifier = self.popSet[clRef] 109 | classifier.updateFitness(accuracySum,accuracies[i],xcs) 110 | i+=1 111 | 112 | ####Action Set Subsumption#### 113 | def do_action_set_subsumption(self,xcs): 114 | subsumer = None 115 | for clRef in self.actionSet: 116 | classifier = self.popSet[clRef] 117 | if classifier.isSubsumer(xcs): 118 | if subsumer == None or classifier.isMoreGeneral(subsumer,xcs): 119 | subsumer = classifier 120 | 121 | if subsumer != None: 122 | i = 0 123 | while i < len(self.actionSet): 124 | ref = self.actionSet[i] 125 | if subsumer.isMoreGeneral(self.popSet[ref],xcs): 126 | xcs.trackingObj.subsumptionCount += 1 127 | subsumer.updateNumerosity(self.popSet[ref].numerosity) 128 | self.removeMacroClassifier(ref) 129 | self.deleteFromMatchSet(ref) 130 | self.deleteFromActionSet(ref) 131 | i -= 1 132 | i+=1 133 | 134 | def removeMacroClassifier(self, ref): 135 | del self.popSet[ref] 136 | 137 | def deleteFromMatchSet(self, deleteRef): 138 | if deleteRef in self.matchSet: 139 | self.matchSet.remove(deleteRef) 140 | 141 | for j in range(len(self.matchSet)): 142 | ref = self.matchSet[j] 143 | if ref > deleteRef: 144 | self.matchSet[j] -= 1 145 | 146 | def deleteFromActionSet(self, deleteRef): 147 | if deleteRef in self.actionSet: 148 | self.actionSet.remove(deleteRef) 149 | 150 | for j in range(len(self.actionSet)): 151 | ref = self.actionSet[j] 152 | if ref > deleteRef: 153 | self.actionSet[j] -= 1 154 | 155 | ####GA#### 156 | def runGA(self,state,xcs): 157 | #GA Run Requirement 158 | if (xcs.iterationCount - self.getIterStampAverage()) < xcs.theta_GA: 159 | return 160 | 161 | xcs.timer.startTimeGA() 162 | self.setIterStamps(xcs.iterationCount) 163 | parentClassifiers = self.selectTwoParentViaTournament(xcs) 164 | parentClassifier1 = parentClassifiers[0] 165 | parentClassifier2 = parentClassifiers[1] 166 | 167 | childClassifier1 = Classifier(xcs) 168 | childClassifier1.initializeWithParentClassifier(parentClassifier1) 169 | childClassifier2 = Classifier(xcs) 170 | childClassifier2.initializeWithParentClassifier(parentClassifier2) 171 | 172 | changedByCrossover = False 173 | if not childClassifier1.equals(childClassifier2) and random.random() < xcs.p_crossover: 174 | changedByCrossover = childClassifier1.uniformCrossover(childClassifier2,xcs) 175 | 176 | if changedByCrossover: 177 | childClassifier1.prediction = (childClassifier1.prediction + childClassifier2.prediction)/2 178 | childClassifier2.predictionError = xcs.prediction_error_reduction*(childClassifier1.predictionError + childClassifier2.predictionError)/2 179 | childClassifier1.fitness = xcs.fitness_reduction*(childClassifier1.fitness+childClassifier2.fitness)/2 180 | childClassifier2.prediction = childClassifier1.prediction 181 | childClassifier2.predictionError = childClassifier1.predictionError 182 | childClassifier2.fitness = childClassifier1.fitness 183 | else: 184 | childClassifier1.fitness = xcs.fitness_reduction * childClassifier1.fitness 185 | childClassifier2.fitness = xcs.fitness_reduction * childClassifier2.fitness 186 | 187 | changedByMutation1 = childClassifier1.mutation(state,xcs) 188 | changedByMutation2 = childClassifier2.mutation(state,xcs) 189 | xcs.timer.stopTimeGA() 190 | 191 | if changedByMutation1 or changedByMutation2 or changedByCrossover: 192 | if changedByMutation1 or changedByMutation2: 193 | xcs.trackingObj.mutationCount += 1 194 | if changedByCrossover: 195 | xcs.trackingObj.crossOverCount += 1 196 | self.insertDiscoveredClassifiers(childClassifier1,childClassifier2,parentClassifier1,parentClassifier2,xcs) 197 | 198 | def insertDiscoveredClassifiers(self,child1,child2,parent1,parent2,xcs): 199 | if xcs.do_GA_subsumption: 200 | xcs.timer.startTimeSubsumption() 201 | self.subsumeClassifier(child1,parent1,parent2,xcs) 202 | self.subsumeClassifier(child2,parent1,parent2,xcs) 203 | xcs.timer.stopTimeSubsumption() 204 | else: 205 | if len(child1.specifiedAttList) > 0: 206 | self.addClassifierToPopulation(xcs, child1, False) 207 | if len(child2.specifiedAttList) > 0: 208 | self.addClassifierToPopulation(xcs, child2, False) 209 | 210 | def subsumeClassifier(self,child,parent1,parent2,xcs): 211 | if parent1.subsumes(child,xcs): 212 | self.microPopSize += 1 213 | parent1.updateNumerosity(1) 214 | xcs.trackingObj.subsumptionCount += 1 215 | elif parent2.subsumes(child,xcs): 216 | self.microPopSize += 1 217 | parent2.updateNumerosity(1) 218 | xcs.trackingObj.subsumptionCount += 1 219 | else: #No additional [A] subsumption w/ offspring rules 220 | if len(child.specifiedAttList) > 0: 221 | self.addClassifierToPopulation(xcs, child, False) 222 | 223 | def getIterStampAverage(self): #Average GA Timestamp 224 | sumCl = 0 225 | numSum = 0 226 | for ref in self.actionSet: 227 | sumCl += self.popSet[ref].timestampGA * self.popSet[ref].numerosity 228 | numSum += self.popSet[ref].numerosity 229 | if numSum != 0: 230 | return sumCl/float(numSum) 231 | else: 232 | return 0 233 | 234 | def getInitStampAverage(self): #Average Init Timestamp 235 | sumCl = 0 236 | numSum = 0 237 | for ref in self.actionSet: 238 | sumCl += self.popSet[ref].initTimeStamp * self.popSet[ref].numerosity 239 | numSum += self.popSet[ref].numerosity 240 | if numSum != 0: 241 | return sumCl/float(numSum) 242 | else: 243 | return 0 244 | 245 | def setIterStamps(self,currentIteration): 246 | for ref in self.actionSet: 247 | self.popSet[ref].updateTimestamp(currentIteration) 248 | 249 | def selectTwoParentViaTournament(self,xcs): 250 | selectList = [None,None] 251 | setList = self.actionSet 252 | 253 | for i in range(2): 254 | tSize = int(len(setList) * xcs.theta_select) 255 | possibleClassifiers = random.sample(setList, tSize) 256 | 257 | bestFitness = 0 258 | bestClassifier = self.actionSet[0] 259 | for j in possibleClassifiers: 260 | if self.popSet[j].fitness > bestFitness: 261 | bestFitness = self.popSet[j].fitness 262 | bestClassifier = j 263 | selectList[i] = self.popSet[bestClassifier] 264 | return selectList 265 | 266 | ####Deletion#### 267 | def deletion(self,xcs): 268 | xcs.timer.startTimeDeletion() 269 | while (self.microPopSize > xcs.N): 270 | self.deleteFromPopulation(xcs) 271 | xcs.timer.stopTimeDeletion() 272 | 273 | def deleteFromPopulation(self,xcs): 274 | meanFitness = self.getFitnessSum()/self.microPopSize 275 | deletionProbSum = 0 276 | voteList = [] 277 | for classifier in self.popSet: 278 | vote = classifier.getDelProp(meanFitness,xcs) 279 | deletionProbSum += vote 280 | voteList.append(vote) 281 | i = 0 282 | for classifier in self.popSet: 283 | classifier.deletionProb = voteList[i]/deletionProbSum 284 | i+=1 285 | 286 | choicePoint = deletionProbSum * random.random() 287 | newSum = 0 288 | for i in range(len(voteList)): 289 | classifier = self.popSet[i] 290 | newSum = newSum + voteList[i] 291 | if newSum > choicePoint: 292 | classifier.updateNumerosity(-1) 293 | self.microPopSize -= 1 294 | if classifier.numerosity < 1: 295 | self.removeMacroClassifier(i) 296 | self.deleteFromMatchSet(i) 297 | self.deleteFromActionSet(i) 298 | xcs.trackingObj.deletionCount += 1 299 | return 300 | return 301 | 302 | def getFitnessSum(self): 303 | sum = 0 304 | for classifier in self.popSet: 305 | sum += classifier.fitness 306 | return sum 307 | 308 | ####Clear Sets#### 309 | def clearSets(self): 310 | """ Clears out references in the match and correct sets for the next learning iteration. """ 311 | self.matchSet = [] 312 | self.actionSet = [] 313 | 314 | ####Evaluation#### 315 | def makeEvaluationMatchSet(self,state,xcs): 316 | for i in range(len(self.popSet)): 317 | classifier = self.popSet[i] 318 | if classifier.match(state,xcs): 319 | self.matchSet.append(i) 320 | 321 | def getAveGenerality(self,xcs): 322 | generalitySum = 0 323 | for classifier in self.popSet: 324 | generalitySum += (xcs.env.formatData.numAttributes - len(classifier.condition))/xcs.env.formatData.numAttributes*classifier.numerosity 325 | if self.microPopSize == 0: 326 | aveGenerality = 0 327 | else: 328 | aveGenerality = generalitySum/self.microPopSize 329 | 330 | return aveGenerality 331 | 332 | def getAttributeSpecificityList(self,xcs): #To be changed for XCS 333 | attributeSpecList = [] 334 | for i in range(xcs.env.formatData.numAttributes): 335 | attributeSpecList.append(0) 336 | for cl in self.popSet: 337 | for ref in cl.specifiedAttList: 338 | attributeSpecList[ref] += cl.numerosity 339 | return attributeSpecList 340 | 341 | def getAttributeAccuracyList(self,xcs): #To be changed for XCS 342 | attributeAccList = [] 343 | for i in range(xcs.env.formatData.numAttributes): 344 | attributeAccList.append(0.0) 345 | for cl in self.popSet: 346 | for ref in cl.specifiedAttList: 347 | attributeAccList[ref] += cl.numerosity * cl.getAccuracy(xcs) 348 | return attributeAccList 349 | 350 | -------------------------------------------------------------------------------- /skXCS/Classifier.py: -------------------------------------------------------------------------------- 1 | import random 2 | import copy 3 | 4 | class Classifier: 5 | def __init__(self,xcs): 6 | self.specifiedAttList = [] 7 | self.condition = [] 8 | self.action = None 9 | 10 | self.prediction = xcs.init_prediction 11 | self.fitness = xcs.init_fitness 12 | self.predictionError = xcs.init_e 13 | 14 | self.numerosity = 1 15 | self.experience = 0 #aka action set count 16 | self.matchCount = 0 17 | 18 | self.actionSetSize = None 19 | self.timestampGA = xcs.iterationCount 20 | self.initTimeStamp = xcs.iterationCount 21 | self.deletionProb = None 22 | 23 | pass 24 | 25 | def initializeWithParentClassifier(self,classifier): 26 | self.specifiedAttList = copy.deepcopy(classifier.specifiedAttList) 27 | self.condition = copy.deepcopy(classifier.condition) 28 | self.action = copy.deepcopy(classifier.action) 29 | 30 | self.actionSetSize = classifier.actionSetSize 31 | self.prediction = classifier.prediction 32 | self.predictionError = classifier.predictionError 33 | self.fitness = classifier.fitness/classifier.numerosity 34 | 35 | def match(self,state,xcs): 36 | for i in range(len(self.condition)): 37 | specifiedIndex = self.specifiedAttList[i] 38 | attributeInfoType = xcs.env.formatData.attributeInfoType[specifiedIndex] 39 | instanceValue = state[specifiedIndex] 40 | 41 | #Continuous 42 | if attributeInfoType: 43 | if instanceValue == None: 44 | return False 45 | elif self.condition[i][0] < instanceValue < self.condition[i][1]: 46 | pass 47 | else: 48 | return False 49 | else: 50 | if instanceValue == self.condition[i]: 51 | pass 52 | elif instanceValue == None: 53 | return False 54 | else: 55 | return False 56 | return True 57 | 58 | def initializeWithMatchingStateAndGivenAction(self,setSize,state,action,xcs): 59 | self.action = action 60 | self.actionSetSize = setSize 61 | 62 | while len(self.specifiedAttList) < 1: 63 | for attRef in range(len(state)): 64 | if random.random() > xcs.p_general and not(state[attRef] == None): 65 | self.specifiedAttList.append(attRef) 66 | self.createMatchingAttribute(xcs,attRef,state) 67 | 68 | 69 | def createMatchingAttribute(self,xcs,attRef,state): 70 | attributeInfoType = xcs.env.formatData.attributeInfoType[attRef] 71 | if attributeInfoType: 72 | attributeInfoValue = xcs.env.formatData.attributeInfoContinuous[attRef] 73 | 74 | # Continuous attribute 75 | if attributeInfoType: 76 | attRange = attributeInfoValue[1] - attributeInfoValue[0] 77 | rangeRadius = random.randint(25, 75) * 0.01 * attRange / 2.0 # Continuous initialization domain radius. 78 | ar = state[attRef] 79 | Low = ar - rangeRadius 80 | High = ar + rangeRadius 81 | condList = [Low, High] 82 | self.condition.append(condList) 83 | 84 | # Discrete attribute 85 | else: 86 | condList = state[attRef] 87 | self.condition.append(condList) 88 | 89 | def equals(self,classifier): 90 | if classifier.action == self.action and len(classifier.specifiedAttList) == len(self.specifiedAttList): 91 | clRefs = sorted(classifier.specifiedAttList) 92 | selfRefs = sorted(self.specifiedAttList) 93 | if clRefs == selfRefs: 94 | for i in range(len(classifier.specifiedAttList)): 95 | tempIndex = self.specifiedAttList.index(classifier.specifiedAttList[i]) 96 | if not (classifier.condition[i] == self.condition[tempIndex]): 97 | return False 98 | return True 99 | return False 100 | 101 | def updateNumerosity(self,num): 102 | self.numerosity += num 103 | 104 | def increaseExperience(self): 105 | self.experience += 1 106 | 107 | def updatePredictionError(self,P,xcs): 108 | if self.experience < 1.0/xcs.beta: 109 | self.predictionError = self.predictionError + (abs(P - self.prediction) - self.predictionError) / float(self.experience) 110 | else: 111 | self.predictionError = self.predictionError + xcs.beta * (abs(P - self.prediction) - self.predictionError) 112 | 113 | def updatePrediction(self,P,xcs): 114 | if self.experience < 1.0 / xcs.beta: 115 | self.prediction = self.prediction + (P-self.prediction) / float(self.experience) 116 | else: 117 | self.prediction = self.prediction + xcs.beta * (P - self.prediction) 118 | 119 | def updateActionSetSize(self,numerositySum,xcs): 120 | if self.experience < 1.0/xcs.beta: 121 | self.actionSetSize = self.actionSetSize + (numerositySum - self.actionSetSize) / float(self.experience) 122 | else: 123 | self.actionSetSize = self.actionSetSize + xcs.beta * (numerositySum - self.actionSetSize) 124 | 125 | def getAccuracy(self,xcs): 126 | """ Returns the accuracy of the classifier. 127 | The accuracy is determined from the prediction error of the classifier using Wilson's 128 | power function as published in 'Get Real! XCS with continuous-valued inputs' (1999) """ 129 | 130 | if self.predictionError <= xcs.e_0: 131 | accuracy = 1.0 132 | else: 133 | accuracy = xcs.alpha * ((self.predictionError / xcs.e_0) ** (-xcs.nu)) 134 | 135 | return accuracy 136 | 137 | def updateFitness(self, accSum, accuracy,xcs): 138 | """ Updates the fitness of the classifier according to the relative accuracy. 139 | @param accSum The sum of all the accuracies in the action set 140 | @param accuracy The accuracy of the classifier. """ 141 | 142 | self.fitness = self.fitness + xcs.beta * ((accuracy * self.numerosity) / float(accSum) - self.fitness) 143 | 144 | def isSubsumer(self,xcs): 145 | """ Returns if the classifier is a possible subsumer. It is affirmed if the classifier 146 | has a sufficient experience and if its reward prediction error is sufficiently low. """ 147 | 148 | if self.experience > xcs.theta_sub and self.predictionError < xcs.e_0: 149 | return True 150 | return False 151 | 152 | def isMoreGeneral(self,classifier,xcs): 153 | if len(self.specifiedAttList) >= len(classifier.specifiedAttList): 154 | return False 155 | for i in range(len(self.specifiedAttList)): 156 | if self.specifiedAttList[i] not in classifier.specifiedAttList: 157 | return False 158 | 159 | attributeInfoType = xcs.env.formatData.attributeInfoType[self.specifiedAttList[i]] 160 | if attributeInfoType: 161 | otherRef = classifier.specifiedAttList.index(self.specifiedAttList[i]) 162 | if self.condition[i][0] < classifier.condition[otherRef][0]: 163 | return False 164 | if self.condition[i][1] > classifier.condition[otherRef][1]: 165 | return False 166 | return True 167 | 168 | def subsumes(self,classifier,xcs): 169 | return self.action == classifier.action and self.isSubsumer(xcs) and self.isMoreGeneral(classifier,xcs) 170 | 171 | def updateTimestamp(self,timestamp): 172 | self.timestampGA = timestamp 173 | 174 | def uniformCrossover(self,classifier,xcs): 175 | p_self_specifiedAttList = copy.deepcopy(self.specifiedAttList) 176 | p_cl_specifiedAttList = copy.deepcopy(classifier.specifiedAttList) 177 | 178 | # Make list of attribute references appearing in at least one of the parents.----------------------------- 179 | comboAttList = [] 180 | for i in p_self_specifiedAttList: 181 | comboAttList.append(i) 182 | for i in p_cl_specifiedAttList: 183 | if i not in comboAttList: 184 | comboAttList.append(i) 185 | elif not xcs.env.formatData.attributeInfoType[i]: 186 | comboAttList.remove(i) 187 | comboAttList.sort() 188 | 189 | changed = False 190 | for attRef in comboAttList: 191 | attributeInfoType = xcs.env.formatData.attributeInfoType[attRef] 192 | probability = 0.5 193 | ref = 0 194 | if attRef in p_self_specifiedAttList: 195 | ref += 1 196 | if attRef in p_cl_specifiedAttList: 197 | ref += 1 198 | 199 | if ref == 0: 200 | pass 201 | elif ref == 1: 202 | if attRef in p_self_specifiedAttList and random.random() > probability: 203 | i = self.specifiedAttList.index(attRef) 204 | classifier.condition.append(self.condition.pop(i)) 205 | 206 | classifier.specifiedAttList.append(attRef) 207 | self.specifiedAttList.remove(attRef) 208 | changed = True 209 | 210 | if attRef in p_cl_specifiedAttList and random.random() < probability: 211 | i = classifier.specifiedAttList.index(attRef) 212 | self.condition.append(classifier.condition.pop(i)) 213 | 214 | self.specifiedAttList.append(attRef) 215 | classifier.specifiedAttList.remove(attRef) 216 | changed = True 217 | else: 218 | # Continuous Attribute 219 | if attributeInfoType: 220 | i_cl1 = self.specifiedAttList.index(attRef) 221 | i_cl2 = classifier.specifiedAttList.index(attRef) 222 | tempKey = random.randint(0, 3) 223 | if tempKey == 0: 224 | temp = self.condition[i_cl1][0] 225 | self.condition[i_cl1][0] = classifier.condition[i_cl2][0] 226 | classifier.condition[i_cl2][0] = temp 227 | elif tempKey == 1: 228 | temp = self.condition[i_cl1][1] 229 | self.condition[i_cl1][1] = classifier.condition[i_cl2][1] 230 | classifier.condition[i_cl2][1] = temp 231 | else: 232 | allList = self.condition[i_cl1] + classifier.condition[i_cl2] 233 | newMin = min(allList) 234 | newMax = max(allList) 235 | if tempKey == 2: 236 | self.condition[i_cl1] = [newMin, newMax] 237 | classifier.condition.pop(i_cl2) 238 | 239 | classifier.specifiedAttList.remove(attRef) 240 | else: 241 | classifier.condition[i_cl2] = [newMin, newMax] 242 | self.condition.pop(i_cl1) 243 | 244 | self.specifiedAttList.remove(attRef) 245 | 246 | # Discrete Attribute 247 | else: 248 | pass 249 | 250 | tempList1 = copy.deepcopy(p_self_specifiedAttList) 251 | tempList2 = copy.deepcopy(classifier.specifiedAttList) 252 | tempList1.sort() 253 | tempList2.sort() 254 | 255 | if changed and len(set(tempList1) & set(tempList2)) == len(tempList2): 256 | changed = False 257 | 258 | return changed 259 | 260 | def mutation(self,state,xcs): 261 | changedByConditionMutation = self.mutateCondition(state,xcs) 262 | changedByActionMutation = self.mutateAction(xcs) 263 | return changedByConditionMutation or changedByActionMutation 264 | 265 | def mutateCondition(self,state,xcs): 266 | changed = False 267 | for attRef in range(xcs.env.formatData.numAttributes): 268 | attributeInfoType = xcs.env.formatData.attributeInfoType[attRef] 269 | if attributeInfoType: 270 | attributeInfoValue = xcs.env.formatData.attributeInfoContinuous[attRef] 271 | 272 | if random.random() < xcs.p_mutation and not(state[attRef] == None): 273 | if not (attRef in self.specifiedAttList): 274 | self.specifiedAttList.append(attRef) 275 | self.createMatchingAttribute(xcs,attRef,state) 276 | changed = True 277 | elif attRef in self.specifiedAttList: 278 | i = self.specifiedAttList.index(attRef) 279 | 280 | if not attributeInfoType or random.random() > 0.5: 281 | del self.specifiedAttList[i] 282 | del self.condition[i] 283 | changed = True 284 | else: 285 | attRange = float(attributeInfoValue[1]) - float(attributeInfoValue[0]) 286 | mutateRange = random.random() * 0.5 * attRange 287 | if random.random() > 0.5: 288 | if random.random() > 0.5: 289 | self.condition[i][0] += mutateRange 290 | else: 291 | self.condition[i][0] -= mutateRange 292 | else: 293 | if random.random() > 0.5: 294 | self.condition[i][1] += mutateRange 295 | else: 296 | self.condition[i][1] -= mutateRange 297 | self.condition[i] = sorted(self.condition[i]) 298 | changed = True 299 | else: 300 | pass 301 | return changed 302 | 303 | def mutateAction(self,xcs): 304 | changed = False 305 | if random.random() < xcs.p_mutation: 306 | action = random.choice(xcs.env.formatData.phenotypeList) 307 | while action == self.action: 308 | action = random.choice(xcs.env.formatData.phenotypeList) 309 | self.action = action 310 | changed = True 311 | return changed 312 | 313 | def getDelProp(self,meanFitness,xcs): 314 | if self.fitness / self.numerosity >= xcs.delta * meanFitness or self.experience < xcs.theta_del: 315 | deletionVote = self.actionSetSize * self.numerosity 316 | 317 | elif self.fitness == 0.0: 318 | deletionVote = self.actionSetSize * self.numerosity * meanFitness / (xcs.init_fit / self.numerosity) 319 | else: 320 | deletionVote = self.actionSetSize * self.numerosity * meanFitness / (self.fitness / self.numerosity) 321 | return deletionVote -------------------------------------------------------------------------------- /test/test_XCS.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import numpy as np 3 | from skXCS.XCS import XCS 4 | from skXCS.StringEnumerator import StringEnumerator 5 | from sklearn.model_selection import cross_val_score 6 | import os 7 | 8 | THIS_DIR = os.path.dirname(os.path.abspath("test_eLCS.py")) 9 | if THIS_DIR[-4:] == 'test': #Patch that ensures testing from Scikit not test directory 10 | THIS_DIR = THIS_DIR[:-5] 11 | 12 | class test_XCS(unittest.TestCase): 13 | #learning_iterations (nonnegative integer) 14 | def testParamLearningIterationsNonnumeric(self): 15 | with self.assertRaises(Exception) as context: 16 | clf = XCS(learning_iterations="hello") 17 | self.assertTrue("learning_iterations param must be nonnegative integer" in str(context.exception)) 18 | 19 | def testParamLearningIterationsInvalidNumeric(self): 20 | with self.assertRaises(Exception) as context: 21 | clf = XCS(learning_iterations=3.3) 22 | self.assertTrue("learning_iterations param must be nonnegative integer" in str(context.exception)) 23 | 24 | def testParamLearningIterationsInvalidNumeric2(self): 25 | with self.assertRaises(Exception) as context: 26 | clf = XCS(learning_iterations=-2) 27 | self.assertTrue("learning_iterations param must be nonnegative integer" in str(context.exception)) 28 | 29 | def testParamLearningIterations(self): 30 | clf = XCS(learning_iterations=2000) 31 | self.assertEqual(clf.learning_iterations,2000) 32 | 33 | #N (nonnegative integer) 34 | def testParamNNonnumeric(self): 35 | with self.assertRaises(Exception) as context: 36 | clf = XCS(N="hello") 37 | self.assertTrue("N param must be nonnegative integer" in str(context.exception)) 38 | 39 | def testParamNInvalidNumeric(self): 40 | with self.assertRaises(Exception) as context: 41 | clf = XCS(N=3.3) 42 | self.assertTrue("N param must be nonnegative integer" in str(context.exception)) 43 | 44 | def testParamNInvalidNumeric2(self): 45 | with self.assertRaises(Exception) as context: 46 | clf = XCS(N=-2) 47 | self.assertTrue("N param must be nonnegative integer" in str(context.exception)) 48 | 49 | def testParamN(self): 50 | clf = XCS(N=2000) 51 | self.assertEqual(clf.N,2000) 52 | 53 | #p_general (float 0-1) 54 | def testParamP_GeneralInv1(self): 55 | with self.assertRaises(Exception) as context: 56 | clf = XCS(p_general="hello") 57 | self.assertTrue("p_general param must be float from 0 - 1" in str(context.exception)) 58 | 59 | def testParamP_GeneralInv2(self): 60 | with self.assertRaises(Exception) as context: 61 | clf = XCS(p_general=3) 62 | self.assertTrue("p_general param must be float from 0 - 1" in str(context.exception)) 63 | 64 | def testParamP_GeneralInv3(self): 65 | with self.assertRaises(Exception) as context: 66 | clf = XCS(p_general=-1.2) 67 | self.assertTrue("p_general param must be float from 0 - 1" in str(context.exception)) 68 | 69 | def testParamP_General1(self): 70 | clf = XCS(p_general=0) 71 | self.assertEqual(clf.p_general,0) 72 | 73 | def testParamP_General2(self): 74 | clf = XCS(p_general=0.3) 75 | self.assertEqual(clf.p_general,0.3) 76 | 77 | def testParamP_General3(self): 78 | clf = XCS(p_general=1) 79 | self.assertEqual(clf.p_general,1) 80 | 81 | #beta (float) 82 | def testBetaInv1(self): 83 | with self.assertRaises(Exception) as context: 84 | clf = XCS(beta="hi") 85 | self.assertTrue("beta param must be float" in str(context.exception)) 86 | 87 | def testBeta1(self): 88 | clf = XCS(beta = -1) 89 | self.assertEqual(clf.beta,-1) 90 | 91 | def testBeta2(self): 92 | clf = XCS(beta = 3) 93 | self.assertEqual(clf.beta,3) 94 | 95 | def testBeta3(self): 96 | clf = XCS(beta = 1.2) 97 | self.assertEqual(clf.beta,1.2) 98 | 99 | #alpha (float) 100 | def testAlphaInv1(self): 101 | with self.assertRaises(Exception) as context: 102 | clf = XCS(alpha="hi") 103 | self.assertTrue("alpha param must be float" in str(context.exception)) 104 | 105 | def testAlpha1(self): 106 | clf = XCS(alpha = -1) 107 | self.assertEqual(clf.alpha,-1) 108 | 109 | def testAlpha2(self): 110 | clf = XCS(alpha = 3) 111 | self.assertEqual(clf.alpha,3) 112 | 113 | def testAlpha3(self): 114 | clf = XCS(alpha = 1.2) 115 | self.assertEqual(clf.alpha,1.2) 116 | 117 | #e_0 (float) 118 | def testE0Inv1(self): 119 | with self.assertRaises(Exception) as context: 120 | clf = XCS(e_0="hi") 121 | self.assertTrue("e_0 param must be float" in str(context.exception)) 122 | 123 | def testE01(self): 124 | clf = XCS(e_0 = -1) 125 | self.assertEqual(clf.e_0,-1) 126 | 127 | def testE02(self): 128 | clf = XCS(e_0 = 3) 129 | self.assertEqual(clf.e_0,3) 130 | 131 | def testE03(self): 132 | clf = XCS(e_0 = 1.2) 133 | self.assertEqual(clf.e_0,1.2) 134 | 135 | #nu (float) 136 | def testNuInv1(self): 137 | with self.assertRaises(Exception) as context: 138 | clf = XCS(nu="hi") 139 | self.assertTrue("nu param must be float" in str(context.exception)) 140 | 141 | def testNu1(self): 142 | clf = XCS(nu = -1) 143 | self.assertEqual(clf.nu,-1) 144 | 145 | def testNu2(self): 146 | clf = XCS(nu = 3) 147 | self.assertEqual(clf.nu,3) 148 | 149 | def testNu3(self): 150 | clf = XCS(nu = 1.2) 151 | self.assertEqual(clf.nu,1.2) 152 | 153 | #theta_GA (nonnegative float) 154 | def testParamThetaGAInv1(self): 155 | with self.assertRaises(Exception) as context: 156 | clf = XCS(theta_GA="hello") 157 | self.assertTrue("theta_GA param must be nonnegative float" in str(context.exception)) 158 | 159 | def testParamThetaGAInv3(self): 160 | with self.assertRaises(Exception) as context: 161 | clf = XCS(theta_GA=-1.2) 162 | self.assertTrue("theta_GA param must be nonnegative float" in str(context.exception)) 163 | 164 | def testParamThetaGA1(self): 165 | clf = XCS(theta_GA=0) 166 | self.assertEqual(clf.theta_GA,0) 167 | 168 | def testParamThetaGA2(self): 169 | clf = XCS(theta_GA=1) 170 | self.assertEqual(clf.theta_GA,1) 171 | 172 | def testParamThetaGA3(self): 173 | clf = XCS(theta_GA=4.3) 174 | self.assertEqual(clf.theta_GA,4.3) 175 | 176 | #p_crossover (float 0-1) 177 | def testParamP_CrossoverInv1(self): 178 | with self.assertRaises(Exception) as context: 179 | clf = XCS(p_crossover="hello") 180 | self.assertTrue("p_crossover param must be float from 0 - 1" in str(context.exception)) 181 | 182 | def testParamP_CrossoverInv2(self): 183 | with self.assertRaises(Exception) as context: 184 | clf = XCS(p_crossover=3) 185 | self.assertTrue("p_crossover param must be float from 0 - 1" in str(context.exception)) 186 | 187 | def testParamP_CrossoverInv3(self): 188 | with self.assertRaises(Exception) as context: 189 | clf = XCS(p_crossover=-1.2) 190 | self.assertTrue("p_crossover param must be float from 0 - 1" in str(context.exception)) 191 | 192 | def testParamP_Crossover1(self): 193 | clf = XCS(p_crossover=0) 194 | self.assertEqual(clf.p_crossover,0) 195 | 196 | def testParamP_Crossover2(self): 197 | clf = XCS(p_crossover=0.3) 198 | self.assertEqual(clf.p_crossover,0.3) 199 | 200 | def testParamP_Crossover3(self): 201 | clf = XCS(p_crossover=1) 202 | self.assertEqual(clf.p_crossover,1) 203 | 204 | #p_mutation (float 0-1) 205 | def testParamP_MutationInv1(self): 206 | with self.assertRaises(Exception) as context: 207 | clf = XCS(p_mutation="hello") 208 | self.assertTrue("p_mutation param must be float from 0 - 1" in str(context.exception)) 209 | 210 | def testParamP_MutationInv2(self): 211 | with self.assertRaises(Exception) as context: 212 | clf = XCS(p_mutation=3) 213 | self.assertTrue("p_mutation param must be float from 0 - 1" in str(context.exception)) 214 | 215 | def testParamP_MutationInv3(self): 216 | with self.assertRaises(Exception) as context: 217 | clf = XCS(p_mutation=-1.2) 218 | self.assertTrue("p_mutation param must be float from 0 - 1" in str(context.exception)) 219 | 220 | def testParamP_Mutation1(self): 221 | clf = XCS(p_mutation=0) 222 | self.assertEqual(clf.p_mutation,0) 223 | 224 | def testParamP_Mutation2(self): 225 | clf = XCS(p_mutation=0.3) 226 | self.assertEqual(clf.p_mutation,0.3) 227 | 228 | def testParamP_Mutation3(self): 229 | clf = XCS(p_mutation=1) 230 | self.assertEqual(clf.p_mutation,1) 231 | 232 | #theta_del (nonnegative integer) 233 | def testParamThetaDelInv1(self): 234 | with self.assertRaises(Exception) as context: 235 | clf = XCS(theta_del="hello") 236 | self.assertTrue("theta_del param must be nonnegative integer" in str(context.exception)) 237 | 238 | def testParamThetaDelInv2(self): 239 | with self.assertRaises(Exception) as context: 240 | clf = XCS(theta_del=2.3) 241 | self.assertTrue("theta_del param must be nonnegative integer" in str(context.exception)) 242 | 243 | def testParamThetaDelInv3(self): 244 | with self.assertRaises(Exception) as context: 245 | clf = XCS(theta_del=-1.2) 246 | self.assertTrue("theta_del param must be nonnegative integer" in str(context.exception)) 247 | 248 | def testParamThetaDelInv4(self): 249 | with self.assertRaises(Exception) as context: 250 | clf = XCS(theta_del=-5) 251 | self.assertTrue("theta_del param must be nonnegative integer" in str(context.exception)) 252 | 253 | def testParamThetaDel1(self): 254 | clf = XCS(theta_del=0) 255 | self.assertEqual(clf.theta_del,0) 256 | 257 | def testParamThetaDel2(self): 258 | clf = XCS(theta_del=5) 259 | self.assertEqual(clf.theta_del,5) 260 | 261 | #delta (float) 262 | def testDeltaInv1(self): 263 | with self.assertRaises(Exception) as context: 264 | clf = XCS(delta="hi") 265 | self.assertTrue("delta param must be float" in str(context.exception)) 266 | 267 | def testDelta1(self): 268 | clf = XCS(delta = -1) 269 | self.assertEqual(clf.delta,-1) 270 | 271 | def testDelta2(self): 272 | clf = XCS(delta = 3) 273 | self.assertEqual(clf.delta,3) 274 | 275 | def testDelta3(self): 276 | clf = XCS(delta = 1.2) 277 | self.assertEqual(clf.delta,1.2) 278 | 279 | #init_predication (float) 280 | def testInitPredictionInv1(self): 281 | with self.assertRaises(Exception) as context: 282 | clf = XCS(init_prediction="hi") 283 | self.assertTrue("init_prediction param must be float" in str(context.exception)) 284 | 285 | def testInitPrediction1(self): 286 | clf = XCS(init_prediction = -1) 287 | self.assertEqual(clf.init_prediction,-1) 288 | 289 | def testInitPrediction2(self): 290 | clf = XCS(init_prediction = 3) 291 | self.assertEqual(clf.init_prediction,3) 292 | 293 | def testInitPrediction3(self): 294 | clf = XCS(init_prediction = 1.2) 295 | self.assertEqual(clf.init_prediction,1.2) 296 | 297 | #init_e (float) 298 | def testInitEInv1(self): 299 | with self.assertRaises(Exception) as context: 300 | clf = XCS(init_e="hi") 301 | self.assertTrue("init_e param must be float" in str(context.exception)) 302 | 303 | def testInitE1(self): 304 | clf = XCS(init_e = -1) 305 | self.assertEqual(clf.init_e,-1) 306 | 307 | def testInitE2(self): 308 | clf = XCS(init_e = 3) 309 | self.assertEqual(clf.init_e,3) 310 | 311 | def testInitE3(self): 312 | clf = XCS(init_e = 1.2) 313 | self.assertEqual(clf.init_e,1.2) 314 | 315 | #init_fitness (float) 316 | def testInitFitnessInv1(self): 317 | with self.assertRaises(Exception) as context: 318 | clf = XCS(init_fitness="hi") 319 | self.assertTrue("init_fitness param must be float" in str(context.exception)) 320 | 321 | def testInitFitness1(self): 322 | clf = XCS(init_fitness = -1) 323 | self.assertEqual(clf.init_fitness,-1) 324 | 325 | def testInitFitness2(self): 326 | clf = XCS(init_fitness = 3) 327 | self.assertEqual(clf.init_fitness,3) 328 | 329 | def testInitFitness3(self): 330 | clf = XCS(init_fitness = 1.2) 331 | self.assertEqual(clf.init_fitness,1.2) 332 | 333 | #p_explore (float 0-1) 334 | def testParamP_ExploreInv1(self): 335 | with self.assertRaises(Exception) as context: 336 | clf = XCS(p_explore="hello") 337 | self.assertTrue("p_explore param must be float from 0 - 1" in str(context.exception)) 338 | 339 | def testParamP_ExploreInv2(self): 340 | with self.assertRaises(Exception) as context: 341 | clf = XCS(p_explore=3) 342 | self.assertTrue("p_explore param must be float from 0 - 1" in str(context.exception)) 343 | 344 | def testParamP_ExploreInv3(self): 345 | with self.assertRaises(Exception) as context: 346 | clf = XCS(p_explore=-1.2) 347 | self.assertTrue("p_explore param must be float from 0 - 1" in str(context.exception)) 348 | 349 | def testParamP_Explore1(self): 350 | clf = XCS(p_explore=0) 351 | self.assertEqual(clf.p_explore,0) 352 | 353 | def testParamP_Explore2(self): 354 | clf = XCS(p_explore=0.3) 355 | self.assertEqual(clf.p_explore,0.3) 356 | 357 | def testParamP_Explore3(self): 358 | clf = XCS(p_explore=1) 359 | self.assertEqual(clf.p_explore,1) 360 | 361 | #theta_matching (nonnegative integer) 362 | def testParamThetaMatchingInv1(self): 363 | with self.assertRaises(Exception) as context: 364 | clf = XCS(theta_matching="hello") 365 | self.assertTrue("theta_matching param must be nonnegative integer" in str(context.exception)) 366 | 367 | def testParamThetaMatchingInv2(self): 368 | with self.assertRaises(Exception) as context: 369 | clf = XCS(theta_matching=2.3) 370 | self.assertTrue("theta_matching param must be nonnegative integer" in str(context.exception)) 371 | 372 | def testParamThetaMatchingInv3(self): 373 | with self.assertRaises(Exception) as context: 374 | clf = XCS(theta_matching=-1.2) 375 | self.assertTrue("theta_matching param must be nonnegative integer" in str(context.exception)) 376 | 377 | def testParamThetaMatchingInv4(self): 378 | with self.assertRaises(Exception) as context: 379 | clf = XCS(theta_matching=-5) 380 | self.assertTrue("theta_matching param must be nonnegative integer" in str(context.exception)) 381 | 382 | def testParamThetaMatching1(self): 383 | clf = XCS(theta_matching=0) 384 | self.assertEqual(clf.theta_matching,0) 385 | 386 | def testParamThetaMatching2(self): 387 | clf = XCS(theta_matching=5) 388 | self.assertEqual(clf.theta_matching,5) 389 | 390 | #do_GA_subsumption (boolean) 391 | def testDoSub2Invalid(self): 392 | with self.assertRaises(Exception) as context: 393 | clf = XCS(do_GA_subsumption=2) 394 | self.assertTrue("do_GA_subsumption param must be boolean" in str(context.exception)) 395 | 396 | def testDoSub2(self): 397 | clf = XCS(do_GA_subsumption=True) 398 | self.assertEqual(clf.do_GA_subsumption,True) 399 | 400 | #do_action_set_subsumption (boolean) 401 | def testDoSubInvalid(self): 402 | with self.assertRaises(Exception) as context: 403 | clf = XCS(do_action_set_subsumption=2) 404 | self.assertTrue("do_action_set_subsumption param must be boolean" in str(context.exception)) 405 | 406 | def testDoSub(self): 407 | clf = XCS(do_action_set_subsumption=True) 408 | self.assertEqual(clf.do_action_set_subsumption,True) 409 | 410 | #max_payoff (float) 411 | def testMaxPayoffInv1(self): 412 | with self.assertRaises(Exception) as context: 413 | clf = XCS(max_payoff="hi") 414 | self.assertTrue("max_payoff param must be float" in str(context.exception)) 415 | 416 | def testMaxPayoff1(self): 417 | clf = XCS(max_payoff = -1) 418 | self.assertEqual(clf.max_payoff,-1) 419 | 420 | def testMaxPayoff2(self): 421 | clf = XCS(max_payoff = 3) 422 | self.assertEqual(clf.max_payoff,3) 423 | 424 | def testMaxPayoff3(self): 425 | clf = XCS(max_payoff = 1.2) 426 | self.assertEqual(clf.max_payoff,1.2) 427 | 428 | #theta_sub (nonnegative integer) 429 | def testParamThetaSubInv1(self): 430 | with self.assertRaises(Exception) as context: 431 | clf = XCS(theta_sub="hello") 432 | self.assertTrue("theta_sub param must be nonnegative integer" in str(context.exception)) 433 | 434 | def testParamThetaSubInv2(self): 435 | with self.assertRaises(Exception) as context: 436 | clf = XCS(theta_sub=2.3) 437 | self.assertTrue("theta_sub param must be nonnegative integer" in str(context.exception)) 438 | 439 | def testParamThetaSubInv3(self): 440 | with self.assertRaises(Exception) as context: 441 | clf = XCS(theta_sub=-1.2) 442 | self.assertTrue("theta_sub param must be nonnegative integer" in str(context.exception)) 443 | 444 | def testParamThetaSubInv4(self): 445 | with self.assertRaises(Exception) as context: 446 | clf = XCS(theta_sub=-5) 447 | self.assertTrue("theta_sub param must be nonnegative integer" in str(context.exception)) 448 | 449 | def testParamThetaSub1(self): 450 | clf = XCS(theta_sub=0) 451 | self.assertEqual(clf.theta_sub,0) 452 | 453 | def testParamThetaSub2(self): 454 | clf = XCS(theta_sub=5) 455 | self.assertEqual(clf.theta_sub,5) 456 | 457 | #theta_select (float 0-1) 458 | def testParamThetaSelInv1(self): 459 | with self.assertRaises(Exception) as context: 460 | clf = XCS(theta_select="hello") 461 | self.assertTrue("theta_select param must be float from 0 - 1" in str(context.exception)) 462 | 463 | def testParamThetaSelInv2(self): 464 | with self.assertRaises(Exception) as context: 465 | clf = XCS(theta_select=3) 466 | self.assertTrue("theta_select param must be float from 0 - 1" in str(context.exception)) 467 | 468 | def testParamThetaSelInv3(self): 469 | with self.assertRaises(Exception) as context: 470 | clf = XCS(theta_select=-1.2) 471 | self.assertTrue("theta_select param must be float from 0 - 1" in str(context.exception)) 472 | 473 | def testParamThetaSel1(self): 474 | clf = XCS(theta_select=0) 475 | self.assertEqual(clf.theta_select, 0) 476 | 477 | def testParamThetaSel2(self): 478 | clf = XCS(theta_select=0.3) 479 | self.assertEqual(clf.theta_select, 0.3) 480 | 481 | def testParamThetaSel3(self): 482 | clf = XCS(theta_select=1) 483 | self.assertEqual(clf.theta_select, 1) 484 | 485 | #discrete_attribute_limit (nonnegative integer or 'c/d' 486 | def testDiscreteAttributeLimitInv1(self): 487 | with self.assertRaises(Exception) as context: 488 | clf = XCS(discrete_attribute_limit="h") 489 | self.assertTrue("discrete_attribute_limit param must be nonnegative integer or 'c' or 'd'" in str(context.exception)) 490 | 491 | def testDiscreteAttributeLimitInv2(self): 492 | with self.assertRaises(Exception) as context: 493 | clf = XCS(discrete_attribute_limit=-10) 494 | self.assertTrue("discrete_attribute_limit param must be nonnegative integer or 'c' or 'd'" in str(context.exception)) 495 | 496 | def testDiscreteAttributeLimitInv3(self): 497 | with self.assertRaises(Exception) as context: 498 | clf = XCS(discrete_attribute_limit=1.2) 499 | self.assertTrue("discrete_attribute_limit param must be nonnegative integer or 'c' or 'd'" in str(context.exception)) 500 | 501 | def testDiscreteAttributeLimit1(self): 502 | clf = XCS(discrete_attribute_limit=10) 503 | self.assertEqual(clf.discrete_attribute_limit,10) 504 | 505 | def testDiscreteAttributeLimit2(self): 506 | clf = XCS(discrete_attribute_limit="c") 507 | self.assertEqual(clf.discrete_attribute_limit,"c") 508 | 509 | def testDiscreteAttributeLimit3(self): 510 | clf = XCS(discrete_attribute_limit="d") 511 | self.assertEqual(clf.discrete_attribute_limit,"d") 512 | 513 | #specified_attributes (ndarray of nonnegative integer attributes 514 | def testParamSpecAttrNonarray(self): 515 | with self.assertRaises(Exception) as context: 516 | clf = XCS(specified_attributes=2) 517 | self.assertTrue("specified_attributes param must be ndarray" in str(context.exception)) 518 | 519 | def testParamSpecAttrNonnumeric(self): 520 | with self.assertRaises(Exception) as context: 521 | clf = XCS(specified_attributes=np.array([2,100,"hi",200])) 522 | self.assertTrue("All specified_attributes elements param must be nonnegative integers" in str(context.exception)) 523 | 524 | def testParamSpecAttrInvalidNumeric(self): 525 | with self.assertRaises(Exception) as context: 526 | clf = XCS(specified_attributes=np.array([2,100,200.2,200])) 527 | self.assertTrue("All specified_attributes elements param must be nonnegative integers" in str(context.exception)) 528 | 529 | def testParamSpecAttrInvalidNumeric2(self): 530 | with self.assertRaises(Exception) as context: 531 | clf = XCS(specified_attributes=np.array([2,100,-200,200])) 532 | self.assertTrue("All specified_attributes elements param must be nonnegative integers" in str(context.exception)) 533 | 534 | def testParamSpecAttr(self): 535 | clf = XCS(specified_attributes=np.array([2, 100, 200, 300])) 536 | self.assertTrue(np.array_equal(clf.specified_attributes,np.array([2, 100, 200, 300]))) 537 | 538 | #random_state (integer or "none") 539 | def testRandomSeedInv1(self): 540 | with self.assertRaises(Exception) as context: 541 | clf = XCS(random_state="hello") 542 | self.assertTrue("random_state param must be integer or None" in str(context.exception)) 543 | 544 | def testRandomSeedInv2(self): 545 | with self.assertRaises(Exception) as context: 546 | clf = XCS(random_state=1.2) 547 | self.assertTrue("random_state param must be integer or None" in str(context.exception)) 548 | 549 | def testRandomSeed2(self): 550 | clf = XCS(random_state=200) 551 | self.assertEqual(clf.random_state,200) 552 | 553 | def testRandomSeed3(self): 554 | clf = XCS(random_state=None) 555 | self.assertEqual(clf.random_state,None) 556 | 557 | #prediction_error_reduction (float) 558 | def testPredReductionInv1(self): 559 | with self.assertRaises(Exception) as context: 560 | clf = XCS(prediction_error_reduction="hi") 561 | self.assertTrue("prediction_error_reduction param must be float" in str(context.exception)) 562 | 563 | def testPredReduction1(self): 564 | clf = XCS(prediction_error_reduction = -1) 565 | self.assertEqual(clf.prediction_error_reduction,-1) 566 | 567 | def testPredReduction2(self): 568 | clf = XCS(prediction_error_reduction = 3) 569 | self.assertEqual(clf.prediction_error_reduction,3) 570 | 571 | def testPredReduction3(self): 572 | clf = XCS(prediction_error_reduction = 1.2) 573 | self.assertEqual(clf.prediction_error_reduction,1.2) 574 | 575 | #fitness_reduction (float) 576 | def testFitnessReductionInv1(self): 577 | with self.assertRaises(Exception) as context: 578 | clf = XCS(fitness_reduction="hi") 579 | self.assertTrue("fitness_reduction param must be float" in str(context.exception)) 580 | 581 | def testFitnessReduction1(self): 582 | clf = XCS(fitness_reduction = -1) 583 | self.assertEqual(clf.fitness_reduction,-1) 584 | 585 | def testFitnessReduction2(self): 586 | clf = XCS(fitness_reduction = 3) 587 | self.assertEqual(clf.fitness_reduction,3) 588 | 589 | def testFitnessReduction3(self): 590 | clf = XCS(fitness_reduction = 1.2) 591 | self.assertEqual(clf.fitness_reduction,1.2) 592 | 593 | #reboot_filename (None or String) 594 | def testRebootFilenameInv1(self): 595 | with self.assertRaises(Exception) as context: 596 | clf = XCS(reboot_filename=2) 597 | self.assertTrue("reboot_filename param must be None or String from pickle" in str(context.exception)) 598 | 599 | def testRebootFilenameInv2(self): 600 | with self.assertRaises(Exception) as context: 601 | clf = XCS(reboot_filename=True) 602 | self.assertTrue("reboot_filename param must be None or String from pickle" in str(context.exception)) 603 | 604 | def testRebootFilename1(self): 605 | clf = XCS() 606 | self.assertEqual(clf.reboot_filename,None) 607 | 608 | def testRebootFilename2(self): 609 | clf = XCS(reboot_filename=None) 610 | self.assertEqual(clf.reboot_filename,None) 611 | 612 | #Performance Tests 613 | #6B MP 1000 iter training 614 | def test6BitMP1000Iterations(self): 615 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Real/Multiplexer6Modified.csv") 616 | converter = StringEnumerator(dataPath,"Class") 617 | headers, classLabel, dataFeatures, dataPhenotypes = converter.get_params() 618 | clf = XCS(learning_iterations=1000,N=500,nu=10) 619 | clf.fit(dataFeatures,dataPhenotypes) 620 | answer = 0.894 621 | #print("6 Bit 1000 Iter: "+str(clf.get_final_training_accuracy())) 622 | self.assertTrue(self.approxEqualOrBetter(0.2,clf.get_final_training_accuracy(),answer,True)) 623 | 624 | # 6B MP 5000 iter training 625 | def test6BitMP5000Iterations(self): 626 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Real/Multiplexer6Modified.csv") 627 | converter = StringEnumerator(dataPath, "Class") 628 | headers, classLabel, dataFeatures, dataPhenotypes = converter.get_params() 629 | clf = XCS(learning_iterations=5000, N=500, nu=10) 630 | clf.fit(dataFeatures, dataPhenotypes) 631 | answer = 1 632 | #print("6 Bit 5000 Iter: "+str(clf.get_final_training_accuracy())) 633 | self.assertTrue(self.approxEqualOrBetter(0.2, clf.get_final_training_accuracy(), answer, True)) 634 | 635 | #11B MP 5000 iter training 636 | def test11BitMP5000Iterations(self): 637 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Real/Multiplexer11Modified.csv") 638 | converter = StringEnumerator(dataPath,"Class") 639 | headers, classLabel, dataFeatures, dataPhenotypes = converter.get_params() 640 | clf = XCS(learning_iterations=5000,N=1000,nu=10) 641 | clf.fit(dataFeatures,dataPhenotypes) 642 | answer = 0.9514 643 | #print("11 Bit 5000 Iter: "+str(clf.get_final_training_accuracy())) 644 | self.assertTrue(self.approxEqualOrBetter(0.2,clf.get_final_training_accuracy(),answer,True)) 645 | 646 | #20B MP 5000 iter training 647 | def test20BitMP5000Iterations(self): 648 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Real/Multiplexer20Modified.csv") 649 | converter = StringEnumerator(dataPath,"Class") 650 | headers, classLabel, dataFeatures, dataPhenotypes = converter.get_params() 651 | clf = XCS(learning_iterations=5000,N=2000,nu=10) 652 | clf.fit(dataFeatures,dataPhenotypes) 653 | answer = 0.6634 654 | #print("20 Bit 5000 Iter: "+str(clf.get_final_training_accuracy())) 655 | self.assertTrue(self.approxEqualOrBetter(0.2,clf.get_final_training_accuracy(),answer,True)) 656 | 657 | #Continuous Valued 5000 iter training 658 | def testContValues5000Iterations(self): 659 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Real/ContinuousAndNonBinaryDiscreteAttributes.csv") 660 | converter = StringEnumerator(dataPath,"Class") 661 | headers, classLabel, dataFeatures, dataPhenotypes = converter.get_params() 662 | clf = XCS(learning_iterations=5000) 663 | clf.fit(dataFeatures,dataPhenotypes) 664 | answer = 0.64 665 | #print("Continuous Attributes 5000 Iter: "+str(clf.get_final_training_accuracy())) 666 | self.assertTrue(self.approxEqualOrBetter(0.2,clf.get_final_training_accuracy(),answer,True)) 667 | 668 | #3-fold testing 6B MP 1000 iter 669 | def test6BitMPTesting1000Iterations(self): 670 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Real/Multiplexer6Modified.csv") 671 | converter = StringEnumerator(dataPath,"Class") 672 | headers, classLabel, dataFeatures, dataPhenotypes = converter.get_params() 673 | formatted = np.insert(dataFeatures, dataFeatures.shape[1], dataPhenotypes, 1) 674 | np.random.shuffle(formatted) 675 | dataFeatures = np.delete(formatted, -1, axis=1) 676 | dataPhenotypes = formatted[:, -1] 677 | 678 | clf = XCS(learning_iterations=1000,N=500,nu=10) 679 | score = np.mean(cross_val_score(clf, dataFeatures, dataPhenotypes, cv=3)) 680 | 681 | answer = 0.9 682 | #print("6 Bit Testing 1000 Iter: "+str(score)) 683 | self.assertTrue(self.approxEqualOrBetter(0.2,score,answer,True)) 684 | 685 | #3-fold testing Continuous Valued + Missing 5000 iter 686 | def testContValuesAndMissingTesting5000Iterations(self): 687 | dataPath = os.path.join(THIS_DIR, "test/DataSets/Real/ContinuousAndNonBinaryDiscreteAttributesMissing.csv") 688 | converter = StringEnumerator(dataPath, "Class") 689 | headers, classLabel, dataFeatures, dataPhenotypes = converter.get_params() 690 | formatted = np.insert(dataFeatures, dataFeatures.shape[1], dataPhenotypes, 1) 691 | np.random.shuffle(formatted) 692 | dataFeatures = np.delete(formatted, -1, axis=1) 693 | dataPhenotypes = formatted[:, -1] 694 | 695 | clf = XCS(learning_iterations=5000) 696 | score = np.mean(cross_val_score(clf, dataFeatures, dataPhenotypes, cv=3)) 697 | 698 | answer = 0.5 699 | #print("Cont & Missing Testing 5000 Iter: " + str(score)) 700 | self.assertTrue(self.approxEqualOrBetter(0.2, score, answer, True)) 701 | 702 | #Random Seed Testing - Done 703 | 704 | #Reboot Pop Testing - 705 | 706 | ###Util Functions### 707 | def approxEqual(self, threshold, comp, right): # threshold is % tolerance 708 | return abs(abs(comp - right) / right) < threshold 709 | 710 | def approxEqualOrBetter(self, threshold, comp, right, 711 | better): # better is False when better is less, True when better is greater 712 | if not better: 713 | if self.approxEqual(threshold, comp, right) or comp < right: 714 | return True 715 | return False 716 | else: 717 | if self.approxEqual(threshold, comp, right) or comp > right: 718 | return True 719 | return False 720 | -------------------------------------------------------------------------------- /skXCS/XCS.py: -------------------------------------------------------------------------------- 1 | 2 | from sklearn.base import BaseEstimator, ClassifierMixin 3 | from sklearn.metrics import balanced_accuracy_score 4 | from skXCS.Environment import Environment 5 | from skXCS.Timer import Timer 6 | from skXCS.ClassifierSet import ClassifierSet 7 | from skXCS.PredictionArray import PredictionArray 8 | from skXCS.IterationRecord import IterationRecord 9 | 10 | import random 11 | import numpy as np 12 | import csv 13 | import copy 14 | import pickle 15 | import time 16 | 17 | class XCS(BaseEstimator,ClassifierMixin): 18 | def __init__(self,learning_iterations=10000,N=1000,p_general=0.5,beta=0.2,alpha=0.1,e_0=10,nu=5,theta_GA=25,p_crossover=0.8,p_mutation=0.04, 19 | theta_del=20,delta=0.1,init_prediction=10,init_e=0,init_fitness=0.01,p_explore=0.5,theta_matching=None,do_GA_subsumption=True, 20 | do_action_set_subsumption=False,max_payoff=1000,theta_sub=20,theta_select=0.5,discrete_attribute_limit=10,specified_attributes=np.array([]), 21 | random_state=None,prediction_error_reduction=0.25,fitness_reduction=0.1,reboot_filename=None): 22 | 23 | ''' 24 | :param learning_iterations: Must be nonnegative integer. The number of explore or exploit learning iterations to run 25 | :param N: Must be nonnegative integer. Maximum micropopulation size 26 | :param p_general: Must be float from 0 - 1. Probability of generalizing an allele during covering 27 | :param beta: Must be float. Learning Rate for updating statistics 28 | :param alpha: Must be float. The fall of rate in the fitness evaluation 29 | :param e_0: Must be float. The error threshold under which accuracy of a classifier can be set to 1 30 | :param nu: Must be float. Power parameter for fitness evaluation 31 | :param theta_GA: Must be nonnegative float. The threshold for the GA application in an action set 32 | :param p_crossover: Must be float from 0 - 1. The probability of applying crossover in an offspring classifier 33 | :param p_mutation: Must be float from 0 - 1. The probability of mutating one allele and the action in an offspring classifier 34 | :param theta_del: Must be nonnegative integer. Specified the threshold over which the fitness of a classifier may be considered in its deletion probability 35 | :param delta: Must be float. The fraction of the mean fitness of the population below which the fitness of a classifier may be considered in its vote for deletion 36 | :param init_prediction: Must be float. The initial prediction value when generating a new classifier (e.g in covering) 37 | :param init_e: Must be float. The initial prediction error value when generating a new classifier (e.g in covering) 38 | :param init_fitness: Must be float. The initial prediction value when generating a new classifier (e.g in covering) 39 | :param p_explore: Must be float from 0 - 1. Probability of doing an explore cycle instead of an exploit cycle 40 | :param theta_matching: Must be nonnegative integer. Number of unique actions that must be represented in the match set (otherwise, covering) 41 | :param do_GA_subsumption: Must be boolean. Do subsumption in GA 42 | :param do_action_set_subsumption: Must be boolean. Do subsumption in [A] 43 | :param max_payoff: Must be float. For single step problems, what the maximum reward for correctness 44 | :param theta_sub: Must be nonnegative integer. The experience of a classifier required to be a subsumer 45 | :param theta_select: Must be float from 0 - 1. The fraction of the action set to be included in tournament selection 46 | :param discrete_attribute_limit: Must be nonnegative integer OR "c" OR "d". Multipurpose param. If it is a nonnegative integer, discrete_attribute_limit determines the threshold that determines 47 | if an attribute will be treated as a continuous or discrete attribute. For example, if discrete_attribute_limit == 10, if an attribute has more than 10 unique 48 | values in the dataset, the attribute will be continuous. If the attribute has 10 or less unique values, it will be discrete. Alternatively, 49 | discrete_attribute_limit can take the value of "c" or "d". See next param for this 50 | :param specified_attributes: Must be an ndarray type of nonnegative integer attributeIndices (zero indexed). 51 | If "c", attributes specified by index in this param will be continuous and the rest will be discrete. If "d", attributes specified by index in this 52 | param will be discrete and the rest will be continuous. 53 | :param random_state: Must be an integer or None. Set a constant random seed value to some integer (in order to obtain reproducible results). Put None if none (for pseudo-random algorithm runs) 54 | :param prediction_error_reduction: Must be float. The reduction of the prediction error when generating an offspring classifier 55 | :param fitness_reduction: Must be float. The reduction of the fitness when generating an offspring classifier 56 | :param reboot_filename: Must be String or None. Filename of model to be rebooted 57 | ''' 58 | 59 | #learning_iterations 60 | if not self.checkIsInt(learning_iterations): 61 | raise Exception("learning_iterations param must be nonnegative integer") 62 | 63 | if learning_iterations < 0: 64 | raise Exception("learning_iterations param must be nonnegative integer") 65 | 66 | #N 67 | if not self.checkIsInt(N): 68 | raise Exception("N param must be nonnegative integer") 69 | 70 | if N < 0: 71 | raise Exception("N param must be nonnegative integer") 72 | 73 | #p_general 74 | if not self.checkIsFloat(p_general): 75 | raise Exception("p_general param must be float from 0 - 1") 76 | 77 | if p_general < 0 or p_general > 1: 78 | raise Exception("p_general param must be float from 0 - 1") 79 | 80 | #beta 81 | if not self.checkIsFloat(beta): 82 | raise Exception("beta param must be float") 83 | 84 | #alpha 85 | if not self.checkIsFloat(alpha): 86 | raise Exception("alpha param must be float") 87 | 88 | #e_0 89 | if not self.checkIsFloat(e_0): 90 | raise Exception("e_0 param must be float") 91 | 92 | #nu 93 | if not self.checkIsFloat(nu): 94 | raise Exception("nu param must be float") 95 | 96 | #theta_GA 97 | if not self.checkIsFloat(theta_GA): 98 | raise Exception("theta_GA param must be nonnegative float") 99 | 100 | if theta_GA < 0: 101 | raise Exception("theta_GA param must be nonnegative float") 102 | 103 | #p_crossover 104 | if not self.checkIsFloat(p_crossover): 105 | raise Exception("p_crossover param must be float from 0 - 1") 106 | 107 | if p_crossover < 0 or p_crossover > 1: 108 | raise Exception("p_crossover param must be float from 0 - 1") 109 | 110 | #p_mutation 111 | if not self.checkIsFloat(p_mutation): 112 | raise Exception("p_mutation param must be float from 0 - 1") 113 | 114 | if p_mutation < 0 or p_mutation > 1: 115 | raise Exception("p_mutation param must be float from 0 - 1") 116 | 117 | #theta_del 118 | if not self.checkIsInt(theta_del): 119 | raise Exception("theta_del param must be nonnegative integer") 120 | 121 | if theta_del < 0: 122 | raise Exception("theta_del param must be nonnegative integer") 123 | 124 | #delta 125 | if not self.checkIsFloat(delta): 126 | raise Exception("delta param must be float") 127 | 128 | #init_prediction 129 | if not self.checkIsFloat(init_prediction): 130 | raise Exception("init_prediction param must be float") 131 | 132 | #init_e 133 | if not self.checkIsFloat(init_e): 134 | raise Exception("init_e param must be float") 135 | 136 | #init_fitness 137 | if not self.checkIsFloat(init_fitness): 138 | raise Exception("init_fitness param must be float") 139 | 140 | #p_explore 141 | if not self.checkIsFloat(p_explore): 142 | raise Exception("p_explore param must be float from 0 - 1") 143 | 144 | if p_explore < 0 or p_explore > 1: 145 | raise Exception("p_explore param must be float from 0 - 1") 146 | 147 | #theta_matching 148 | if not self.checkIsInt(theta_matching) and theta_matching != None: 149 | raise Exception("theta_matching param must be nonnegative integer") 150 | 151 | if theta_matching != None and theta_matching < 0: 152 | raise Exception("theta_matching param must be nonnegative integer") 153 | 154 | #do_GA_subsumption 155 | if not (isinstance(do_GA_subsumption, bool)): 156 | raise Exception("do_GA_subsumption param must be boolean") 157 | 158 | #do_action_set_subsumption 159 | if not (isinstance(do_action_set_subsumption, bool)): 160 | raise Exception("do_action_set_subsumption param must be boolean") 161 | 162 | #max_payoff 163 | if not self.checkIsFloat(max_payoff): 164 | raise Exception("max_payoff param must be float") 165 | 166 | #theta_sub 167 | if not self.checkIsInt(theta_sub): 168 | raise Exception("theta_sub param must be nonnegative integer") 169 | 170 | if theta_sub < 0: 171 | raise Exception("theta_sub param must be nonnegative integer") 172 | 173 | #theta_select 174 | if not self.checkIsFloat(theta_select): 175 | raise Exception("theta_select param must be float from 0 - 1") 176 | 177 | if theta_select < 0 or theta_select > 1: 178 | raise Exception("theta_select param must be float from 0 - 1") 179 | 180 | #discrete_attribute_limit 181 | if discrete_attribute_limit != "c" and discrete_attribute_limit != "d": 182 | try: 183 | dpl = int(discrete_attribute_limit) 184 | if not self.checkIsInt(discrete_attribute_limit): 185 | raise Exception("discrete_attribute_limit param must be nonnegative integer or 'c' or 'd'") 186 | if dpl < 0: 187 | raise Exception("discrete_attribute_limit param must be nonnegative integer or 'c' or 'd'") 188 | except: 189 | raise Exception("discrete_attribute_limit param must be nonnegative integer or 'c' or 'd'") 190 | 191 | #specified_attributes 192 | if not (isinstance(specified_attributes, np.ndarray)): 193 | raise Exception("specified_attributes param must be ndarray") 194 | 195 | for spAttr in specified_attributes: 196 | if not self.checkIsInt(spAttr): 197 | raise Exception("All specified_attributes elements param must be nonnegative integers") 198 | if int(spAttr) < 0: 199 | raise Exception("All specified_attributes elements param must be nonnegative integers") 200 | 201 | #prediction_error_reduction 202 | if not self.checkIsFloat(prediction_error_reduction): 203 | raise Exception("prediction_error_reduction param must be float") 204 | 205 | #fitness_reduction 206 | if not self.checkIsFloat(fitness_reduction): 207 | raise Exception("fitness_reduction param must be float") 208 | 209 | #rebootPopulationFilename 210 | if reboot_filename != None and not isinstance(reboot_filename,str): 211 | raise Exception("reboot_filename param must be None or String from pickle") 212 | 213 | # random_state 214 | if random_state != None: 215 | try: 216 | if not self.checkIsInt(random_state): 217 | raise Exception("random_state param must be integer or None") 218 | except: 219 | raise Exception("random_state param must be integer or None") 220 | 221 | self.learning_iterations = learning_iterations 222 | self.N = N 223 | self.p_general = p_general 224 | self.beta = beta 225 | self.alpha = alpha 226 | self.e_0 = e_0 227 | self.nu = nu 228 | self.theta_GA = theta_GA 229 | self.p_crossover = p_crossover 230 | self.p_mutation = p_mutation 231 | self.theta_del = theta_del 232 | self.delta = delta 233 | self.init_prediction = init_prediction 234 | self.init_e = init_e 235 | self.init_fitness = init_fitness 236 | self.p_explore = p_explore 237 | self.theta_matching = theta_matching 238 | self.do_GA_subsumption = do_GA_subsumption 239 | self.do_action_set_subsumption = do_action_set_subsumption 240 | self.max_payoff = max_payoff 241 | self.theta_sub = theta_sub 242 | self.theta_select = theta_select 243 | self.discrete_attribute_limit = discrete_attribute_limit 244 | self.specified_attributes = specified_attributes 245 | self.random_state = random_state 246 | self.prediction_error_reduction = prediction_error_reduction 247 | self.fitness_reduction = fitness_reduction 248 | 249 | self.hasTrained = False 250 | self.trackingObj = TempTrackingObj() 251 | self.record = IterationRecord() 252 | self.reboot_filename = reboot_filename 253 | 254 | #Reboot Population 255 | if self.reboot_filename != None: 256 | self.rebootPopulation() 257 | self.hasTrained = True 258 | else: 259 | self.iterationCount = 0 260 | self.population = ClassifierSet() 261 | 262 | def checkIsInt(self, num): 263 | try: 264 | n = float(num) 265 | if num - int(num) == 0: 266 | return True 267 | else: 268 | return False 269 | except: 270 | return False 271 | 272 | def checkIsFloat(self,num): 273 | try: 274 | n = float(num) 275 | return True 276 | except: 277 | return False 278 | 279 | ##*************** Fit **************** 280 | def fit(self,X,y): 281 | """Scikit-learn required: Supervised training of XCS 282 | Parameters 283 | X: array-like {n_samples, n_features} Training instances. ALL INSTANCE ATTRIBUTES MUST BE NUMERIC or NAN 284 | y: array-like {n_samples} Training labels. ALL INSTANCE PHENOTYPES MUST BE NUMERIC NOT NAN OR OTHER TYPE 285 | Returns self 286 | """ 287 | 288 | # Check if X and Y are numeric 289 | try: 290 | for instance in X: 291 | for value in instance: 292 | if not (np.isnan(value)): 293 | float(value) 294 | for value in y: 295 | float(value) 296 | 297 | except: 298 | raise Exception("X and y must be fully numeric") 299 | 300 | # Handle repeated fit calls 301 | if self.learning_iterations == self.iterationCount and self.reboot_filename != None: 302 | raise Exception("You cannot call fit(X,y) a second time with a rebooted population.") 303 | 304 | if self.random_state != None: 305 | random.seed(int(self.random_state)) 306 | np.random.seed(int(self.random_state)) 307 | 308 | if self.reboot_filename == None: 309 | self.timer = Timer() 310 | else: 311 | self.rebootTimer() 312 | 313 | self.env = Environment(X,y,self) 314 | 315 | if self.theta_matching == None: 316 | self.theta_matching = self.env.formatData.numberOfActions 317 | if self.theta_matching > self.env.formatData.numberOfActions: 318 | raise Exception("theta_matching param cannot be greater than the number of actions") 319 | 320 | self.trackedAccuracy = [] 321 | self.movingAvgCount = 50 322 | aveGenerality = 0 323 | aveGeneralityFreq = min(self.env.formatData.numTrainInstances,1000) 324 | 325 | while self.iterationCount < self.learning_iterations: 326 | state = self.env.getTrainState() 327 | self.runIteration(state) 328 | 329 | #Basic Evaluation 330 | self.timer.updateGlobalTimer() 331 | self.timer.startTimeEvaluation() 332 | if self.iterationCount%aveGeneralityFreq == (aveGeneralityFreq-1): 333 | aveGenerality = self.population.getAveGenerality(self) 334 | 335 | if len(self.trackedAccuracy) != 0: 336 | accuracy = sum(self.trackedAccuracy)/len(self.trackedAccuracy) 337 | else: 338 | accuracy = 0 339 | self.record.addToTracking(self.iterationCount,accuracy,aveGenerality, 340 | self.trackingObj.macroPopSize,self.trackingObj.microPopSize, 341 | self.trackingObj.matchSetSize, self.trackingObj.actionSetSize, 342 | self.trackingObj.avgIterAge, self.trackingObj.subsumptionCount, 343 | self.trackingObj.crossOverCount, self.trackingObj.mutationCount, 344 | self.trackingObj.coveringCount, self.trackingObj.deletionCount, 345 | self.timer.globalTime, self.timer.globalMatching, 346 | self.timer.globalDeletion, self.timer.globalSubsumption, 347 | self.timer.globalGA, self.timer.globalEvaluation) 348 | self.timer.stopTimeEvaluation() 349 | ### 350 | 351 | self.iterationCount += 1 352 | self.env.newInstance() 353 | self.saveFinalMetrics() 354 | self.hasTrained = True 355 | return self 356 | 357 | def runIteration(self,state): 358 | self.trackingObj.resetAll() 359 | shouldExplore = random.random() < self.p_explore 360 | if shouldExplore: 361 | self.population.createMatchSet(state,self) 362 | predictionArray = PredictionArray(self.population,self) 363 | actionWinner = predictionArray.randomActionWinner() 364 | self.population.createActionSet(actionWinner) 365 | reward = self.env.executeAction(actionWinner) 366 | self.population.updateActionSet(reward,self) 367 | self.population.runGA(state,self) 368 | self.population.deletion(self) 369 | else: 370 | self.population.createMatchSet(state, self) 371 | predictionArray = PredictionArray(self.population, self) 372 | actionWinner = predictionArray.bestActionWinner() 373 | self.population.createActionSet(actionWinner) 374 | reward = self.env.executeAction(actionWinner) 375 | self.population.updateActionSet(reward, self) 376 | self.population.deletion(self) 377 | 378 | if reward == self.max_payoff: 379 | if len(self.trackedAccuracy) == self.movingAvgCount: 380 | del self.trackedAccuracy[0] 381 | self.trackedAccuracy.append(1) 382 | else: 383 | if len(self.trackedAccuracy) == self.movingAvgCount: 384 | del self.trackedAccuracy[0] 385 | self.trackedAccuracy.append(0) 386 | 387 | self.trackingObj.avgIterAge = self.iterationCount - self.population.getInitStampAverage() 388 | self.trackingObj.macroPopSize = len(self.population.popSet) 389 | self.trackingObj.microPopSize = self.population.microPopSize 390 | self.trackingObj.matchSetSize = len(self.population.matchSet) 391 | self.trackingObj.actionSetSize = len(self.population.actionSet) 392 | self.population.clearSets() 393 | 394 | ##*************** Population Reboot **************** 395 | def saveFinalMetrics(self): 396 | self.finalMetrics = [self.learning_iterations,self.timer.globalTime, self.timer.globalMatching, 397 | self.timer.globalDeletion, self.timer.globalSubsumption, self.timer.globalGA, 398 | self.timer.globalEvaluation,copy.deepcopy(self.env),copy.deepcopy(self.population.popSet)] 399 | 400 | def pickle_model(self,filename=None): 401 | if self.hasTrained: 402 | if filename == None: 403 | filename = 'pickled'+str(int(time.time())) 404 | outfile = open(filename,'wb') 405 | pickle.dump(self.finalMetrics,outfile) 406 | outfile.close() 407 | else: 408 | raise Exception("There is model to pickle, as the XCS model has not been trained") 409 | 410 | def rebootPopulation(self): 411 | #Sets popSet and microPopSize of self.population, as well as trackingMetrics, 412 | file = open(self.reboot_filename,'rb') 413 | rawData = pickle.load(file) 414 | file.close() 415 | 416 | popSet = rawData[8] 417 | microPopSize = 0 418 | for rule in popSet: 419 | microPopSize += rule.numerosity 420 | set = ClassifierSet() 421 | set.popSet = popSet 422 | set.microPopSize = microPopSize 423 | self.population = set 424 | 425 | self.learning_iterations += rawData[0] 426 | self.iterationCount = rawData[0] 427 | self.env = rawData[7] 428 | 429 | def rebootTimer(self): 430 | file = open(self.reboot_filename, 'rb') 431 | rawData = pickle.load(file) 432 | file.close() 433 | 434 | self.timer = Timer() 435 | self.timer.globalAdd = rawData[1] 436 | self.timer.globalMatching = rawData[2] 437 | self.timer.globalDeletion = rawData[3] 438 | self.timer.globalSubsumption = rawData[4] 439 | self.timer.globalGA = rawData[5] 440 | self.timer.globalEvaluation = rawData[6] 441 | 442 | 443 | ##*************** Predict and Score **************** 444 | def predict(self,X): 445 | """Scikit-learn required: Test Accuracy of XCS 446 | Parameters 447 | X: array-like {n_samples, n_features} Test instances to classify. ALL INSTANCE ATTRIBUTES MUST BE NUMERIC 448 | Returns 449 | y: array-like {n_samples} Classifications. 450 | """ 451 | try: 452 | for instance in X: 453 | for value in instance: 454 | if not (np.isnan(value)): 455 | float(value) 456 | except: 457 | raise Exception("X must be fully numeric") 458 | 459 | numInstances = X.shape[0] 460 | predictionList = [] 461 | for instance in range(numInstances): 462 | state = X[instance] 463 | self.population.makeEvaluationMatchSet(state,self) 464 | predictionArray = PredictionArray(self.population, self) 465 | actionWinner = predictionArray.bestActionWinner() 466 | predictionList.append(actionWinner) 467 | self.population.clearSets() 468 | return np.array(predictionList) 469 | 470 | def predict_proba(self,X): 471 | """Scikit-learn required: Test Accuracy of XCS 472 | Parameters 473 | X: array-like {n_samples, n_features} Test instances to classify. ALL INSTANCE ATTRIBUTES MUST BE NUMERIC 474 | Returns 475 | y: array-like {n_samples} Classifications. 476 | """ 477 | try: 478 | for instance in X: 479 | for value in instance: 480 | if not (np.isnan(value)): 481 | float(value) 482 | except: 483 | raise Exception("X must be fully numeric") 484 | 485 | numInstances = X.shape[0] 486 | predictionList = [] 487 | for instance in range(numInstances): 488 | state = X[instance] 489 | self.population.makeEvaluationMatchSet(state, self) 490 | predictionArray = PredictionArray(self.population, self) 491 | probabilities = predictionArray.getProbabilities() 492 | predictionList.append(probabilities) 493 | self.population.clearSets() 494 | return np.array(predictionList) 495 | 496 | def score(self,X,y): 497 | predictionList = self.predict(X) 498 | return balanced_accuracy_score(y,predictionList) 499 | 500 | ##*************** Export and Evaluation **************** 501 | def export_iteration_tracking_data(self,filename='iterationData.csv'): 502 | if self.hasTrained: 503 | self.record.exportTrackingToCSV(filename) 504 | else: 505 | raise Exception("There is no tracking data to export, as the XCS model has not been trained") 506 | 507 | def export_final_rule_population(self,filename='rulePopulation.csv',headerNames=np.array([]),className="Action"): 508 | if self.hasTrained: 509 | numAttributes = self.env.formatData.numAttributes 510 | headerNames = headerNames.tolist() # Convert to Python List 511 | 512 | # Default headerNames if none provided 513 | if len(headerNames) == 0: 514 | for i in range(numAttributes): 515 | headerNames.append("N" + str(i)) 516 | 517 | if len(headerNames) != numAttributes: 518 | raise Exception("# of Header Names provided does not match the number of attributes in dataset instances.") 519 | 520 | with open(filename, mode='w') as file: 521 | writer = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) 522 | 523 | writer.writerow(headerNames + [className] + ["Fitness","Prediction","Prediction Error","Accuracy", "Numerosity", "Avg Action Set Size", 524 | "TimeStamp GA", "Iteration Initialized", "Specificity", 525 | "Deletion Probability", "Experience", "Match Count"]) 526 | 527 | classifiers = copy.deepcopy(self.population.popSet) 528 | for classifier in classifiers: 529 | a = [] 530 | for attributeIndex in range(numAttributes): 531 | if attributeIndex in classifier.specifiedAttList: 532 | specifiedLocation = classifier.specifiedAttList.index(attributeIndex) 533 | if not isinstance(classifier.condition[specifiedLocation], list): # if discrete 534 | a.append(classifier.condition[specifiedLocation]) 535 | else: # if continuous 536 | conditionCont = classifier.condition[specifiedLocation] # cont array [min,max] 537 | s = str(conditionCont[0]) + "," + str(conditionCont[1]) 538 | a.append(s) 539 | else: 540 | a.append("#") 541 | 542 | a.append(classifier.action) 543 | a.append(classifier.fitness) 544 | a.append(classifier.prediction) 545 | a.append(classifier.predictionError) 546 | a.append(classifier.getAccuracy(self)) 547 | a.append(classifier.numerosity) 548 | a.append(classifier.actionSetSize) 549 | a.append(classifier.timestampGA) 550 | a.append(classifier.initTimeStamp) 551 | a.append(len(classifier.specifiedAttList) / numAttributes) 552 | a.append(classifier.deletionProb) 553 | a.append(classifier.experience) 554 | a.append(classifier.matchCount) 555 | writer.writerow(a) 556 | file.close() 557 | else: 558 | raise Exception("There is no rule population to export, as the XCS model has not been trained") 559 | 560 | def export_final_rule_population_DCAL(self,filename='rulePopulationDCAL.csv',headerNames=np.array([]),className="Action"): 561 | if self.hasTrained: 562 | numAttributes = self.env.formatData.numAttributes 563 | 564 | headerNames = headerNames.tolist() # Convert to Python List 565 | 566 | # Default headerNames if none provided 567 | if len(headerNames) == 0: 568 | for i in range(numAttributes): 569 | headerNames.append("N" + str(i)) 570 | 571 | if len(headerNames) != numAttributes: 572 | raise Exception( 573 | "# of Header Names provided does not match the number of attributes in dataset instances.") 574 | 575 | with open(filename, mode='w') as file: 576 | writer = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) 577 | 578 | writer.writerow( 579 | ["Specified Values", "Specified Attribute Names"] + [className] + ["Fitness","Prediction", 580 | "Prediction Error","Accuracy", 581 | "Numerosity", "Avg Action Set Size", 582 | "TimeStamp GA", "Iteration Initialized", 583 | "Specificity", "Deletion Probability", 584 | "Experience", "Match Count"]) 585 | 586 | classifiers = copy.deepcopy(self.population.popSet) 587 | for classifier in classifiers: 588 | a = [] 589 | 590 | # Add attribute information 591 | headerString = "" 592 | valueString = "" 593 | for attributeIndex in range(numAttributes): 594 | if attributeIndex in classifier.specifiedAttList: 595 | specifiedLocation = classifier.specifiedAttList.index(attributeIndex) 596 | headerString += str(headerNames[attributeIndex]) + ", " 597 | if not isinstance(classifier.condition[specifiedLocation], list): # if discrete 598 | valueString += str(classifier.condition[specifiedLocation]) + ", " 599 | else: # if continuous 600 | conditionCont = classifier.condition[specifiedLocation] # cont array [min,max] 601 | s = "[" + str(conditionCont[0]) + "," + str(conditionCont[1]) + "]" 602 | valueString += s + ", " 603 | 604 | a.append(valueString[:-2]) 605 | a.append(headerString[:-2]) 606 | 607 | # Add statistics 608 | a.append(classifier.action) 609 | a.append(classifier.fitness) 610 | a.append(classifier.prediction) 611 | a.append(classifier.predictionError) 612 | a.append(classifier.getAccuracy(self)) 613 | a.append(classifier.numerosity) 614 | a.append(classifier.actionSetSize) 615 | a.append(classifier.timestampGA) 616 | a.append(classifier.initTimeStamp) 617 | a.append(len(classifier.specifiedAttList) / numAttributes) 618 | a.append(classifier.deletionProb) 619 | a.append(classifier.experience) 620 | a.append(classifier.matchCount) 621 | writer.writerow(a) 622 | file.close() 623 | else: 624 | raise Exception("There is no rule population to export, as the XCS model has not been trained") 625 | 626 | def get_final_training_accuracy(self): 627 | if self.hasTrained: 628 | originalTrainingData = self.env.formatData.savedRawTrainingData 629 | return self.score(originalTrainingData[0],originalTrainingData[1]) 630 | else: 631 | raise Exception("There is no final training accuracy to return, as the XCS model has not been trained") 632 | 633 | def get_final_instance_coverage(self): 634 | if self.hasTrained: 635 | numCovered = 0 636 | originalTrainingData = self.env.formatData.savedRawTrainingData 637 | for state in originalTrainingData[0]: 638 | self.population.makeEvaluationMatchSet(state, self) 639 | predictionArray = PredictionArray(self.population, self) 640 | if predictionArray.hasMatch: 641 | numCovered += 1 642 | self.population.clearSets() 643 | return numCovered/len(originalTrainingData[0]) 644 | else: 645 | raise Exception("There is no final instance coverage to return, as the XCS model has not been trained") 646 | 647 | def get_final_attribute_specificity_list(self): 648 | if self.hasTrained: 649 | return self.population.getAttributeSpecificityList(self) 650 | else: 651 | raise Exception("There is no final attribute specificity list to return, as the XCS model has not been trained") 652 | 653 | def get_final_attribute_accuracy_list(self): 654 | if self.hasTrained: 655 | return self.population.getAttributeAccuracyList(self) 656 | else: 657 | raise Exception("There is no final attribute accuracy list to return, as the XCS model has not been trained") 658 | 659 | class TempTrackingObj(): 660 | #Tracks stats of every iteration (except accuracy, avg generality, and times) 661 | def __init__(self): 662 | self.macroPopSize = 0 663 | self.microPopSize = 0 664 | self.matchSetSize = 0 665 | self.correctSetSize = 0 666 | self.avgIterAge = 0 667 | self.subsumptionCount = 0 668 | self.crossOverCount = 0 669 | self.mutationCount = 0 670 | self.coveringCount = 0 671 | self.deletionCount = 0 672 | 673 | def resetAll(self): 674 | self.macroPopSize = 0 675 | self.microPopSize = 0 676 | self.matchSetSize = 0 677 | self.correctSetSize = 0 678 | self.avgIterAge = 0 679 | self.subsumptionCount = 0 680 | self.crossOverCount = 0 681 | self.mutationCount = 0 682 | self.coveringCount = 0 683 | self.deletionCount = 0 -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------