Reputation: 2920
I'm working on an implementation of the genetic algorithm to solve an advanced Traveling Salesman Problem (with edges depending on daytime to simulate traffic hours). It's working out quite well so far.
I've got some classes Inhabitant
which has a GeneticString
, a Population
and some others classes.
In each iteration, where the generation of the simulation advances there is a chance of mutation, so to be safe I want to save the best of all my Inhabitants (Solutions/Tours) in case this one mutates and I'll never find a better one.
So Population
has a best
property and after each iteration I call determineBest()
to see if the best inhabitant of my current population (I keep the population sorted, so the inhabitant with key 0 is the best) is better than the one I remembered with best
class Population:
def __init__(self,p,simulation):
self.inhabitants = []
self.generation = 0
self.simulation = simulation
self.map = self.simulation.map
for i in range(0,p):
self.addRandomInhabitant()
self.best = self.inhabitants[0]
...
def setBest(self,b):
self.best = Inhabitant(b.locations(),self)
def determineBest(self):
if (self.inhabitants[0].fitness() < self.best.fitness()):
# WHY!?
print "overwriting " + str(self.best.fitness()) + " with "+ str(self.inhabitants[0].fitness())
self.setBest(self.inhabitants[0])
"This can't be so hard" but I'm doing something wrong. The best Inhabitant is never saved.
The output of the debug print is (for the last generations):
overwriting 3.57107095019 with 3.55664843948
overwriting 3.63240015308 with 3.55664843948
overwriting 3.57107095019 with 3.55664843948
Since my implementation depends on the current time and the fitness value of a Tour changes with the given starting time, I've already checked on this. For each fitness value calculation the same starting time is used.
If you need access to the full code, I could host it on a git-hoster.
Upvotes: 0
Views: 92
Reputation: 26
My best guess is that mutating the inhabitant actually mutates some attribute that is shared with the copy, probably the object returned by Inhabitant.locations(). In this case, mutating the original inhabitant will also mutate the copy. You would need to create a copy of the object returned by locations() or (to be on the safe side) change the locations() method itself to return a copy.
Upvotes: 1
Reputation: 1
(self.inhabitants[0].fitness() < self.best.fitness())
Hi,
If you want to maximize fitness, should you not change the "<" to ">"?
Upvotes: 0