Created
March 13, 2011 06:53
-
-
Save topher200/867936 to your computer and use it in GitHub Desktop.
the main loop from my python example for my blog, source available: https://github.com/topher200/genetic-hello-world-python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def run(self): | |
# Create a random sample of chromos | |
sample = self.generate_random_chromosomes() | |
# Main loop: each generation select a subset of the sample and breed from | |
# them. | |
generation = -1 | |
while self.fitness(sample[0]) != 0: | |
generation += 1 | |
# Generate the selected group from sample- take the top 1% of samples | |
# and tourny select to generate the rest of selected. | |
ten_percent = int(len(sample)*.01) | |
selected = sample[:ten_percent] | |
while len(selected) < self.num_selected: | |
selected.append(self.tourny_select_chromo(sample)) | |
# Generate the solution group by breeding random chromos from selected | |
solution = [] | |
while len(solution) < self.num_samples: | |
solution.extend(self.breed(random.choice(selected), | |
random.choice(selected))) | |
# Apply a mutation to a subset of the solution set | |
for i, chromo in enumerate(solution[::self.mutation_factor]): | |
solution[i] = self.mutate(solution[i]) | |
sample = sorted(solution, key = self.fitness) | |
# Print useful stats about this generation | |
(min, median, max) = map(self.fitness, | |
[sample[0], sample[len(sample)//2], sample[-1]]) | |
print("{0} best string: {1}. fitness: best {2}, median {3}, worst {4}" \ | |
.format(generation, sample[0], min, median, max)) | |
return generation |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment