a "generic" problem

Sean Ross frobozz_electric at hotmail.com
Wed Feb 12 21:15:39 EST 2003


Hi.
I've reimplemented my classes as per your suggestions, however, there is a
problem. First, what the relevant code looks like:

class Chromosome:
    alphabet = "01"
    length = 40
    def __init__(self, gene=None):
        if gene == None:
            gene = self.randomgene()
        self.gene = gene
        self.fit = self.fitness()

    def fitness(self, target=None):
        "override this method to evaluate chromosome fitness"
        pass

    [snip]

    def onepoint(self, mate):
        "creates offspring via one-point xover between mates"
        klass = self.__class__
        pivot = random.randrange(self.length)
        c1 = klass(self.gene[:pivot] + mate.gene[pivot:])
        c2 = klass(mate.gene[:pivot] + self.gene[pivot:])
        return c1, c2

    [snip]

class GeneticAlgorithm:
    def __init__(self, chromosome_class, population=100,
                 crossover=0.85, mutate=0.01, max_epoch=0,
                 elitism = 0.0, target=None):
        self.chromosome_class = chromosome_class
        self.population = population
        self.pool = self.generatepool()
        ...
    [snip]

    def generatepool(self):
        return [self.chromosome_class() \
                      for chromo in xrange(self.population)]

    def fitness(self, target=None):
        "sets fitness for each chromosome in pool"
        for chromo in self.pool:
            chromo.fitness(self.target)

     [snip]

class OneMax(Chromosome):
    length = 30
    def fitness(self, target=None):
        self.fit = utils.sum([int(allele) for allele in self.gene])
    [snip]

if __name__ == "__main__":
    TARGET = '1'*30
    species = OneMaxGA(OneMax, target=TARGET,
                       mutate=0.05, max_epoch=200)
    [snip]


And, now, the problem:
When I run my algorithm and call species.fitness(), it calls the OneMax
fitness() for each chromosome in the pool, and a print statement in that
method showed that the value for self.fit was being set correctly.
However, when I inspect the species.pool, all of the OneMax instances have
self.fit=None.

e.g., here's a result from inside one of the xover methods to check
which class 'klass' represented; print before making c1, a print inside the
OneMax fitness function(which appears to be called as c1 is made)
and a print of c1 after it has been made.


klass: __main__.OneMax
making c1
self.fit 16
c1: <OneMax gene="011010001010111101011011100100" fitness=None>

I don't understand why c1's self.fit=16 inside it's self.fitness() call,
but afterward it equals None. It looks like the Chromosome fitness() method
is being called rather than the OneMax fitness() method.

Thanks for your help,
Sean

P.S. Once again, if you require more code to see what's going on, let me
know.






More information about the Python-list mailing list