def test_mutate(self): c1 = create_chromosome(6) c2 = create_chromosome(7) c3 = create_chromosome(8) assert mutate(copy.deepcopy(c1)) != c1 assert mutate(copy.deepcopy(c2)) != c2
def evolve(self): # create a new population new_population = Population(self.helper, pop=self.POPULATION_SIZE, tour=self.TOURNAMENT_SIZE, cross=self.CROSSOVER_RATE, mut=self.MUTATION_INVERSION_RATE) # the best fitting solution go to the next population automatically (ELITISM) best_fit = ga.get_best_fitness(self.chromosomes, self.helper) elit_chromosome = Chromosome() elit_chromosome.path = list(best_fit.path) elit_chromosome.trucks_used = list(best_fit.trucks_used) new_population.chromosomes.append(elit_chromosome) elit_unchanged = Chromosome() elit_unchanged.path = list(best_fit.path) elit_unchanged.trucks_used = list(best_fit.trucks_used) # crossover for _ in range((self.POPULATION_SIZE - 2) / 2): #print 'generating child ' + str(i) # must select parent 1 using TOURNAMENT SELECTION parent_1 = ga.tournament_selection(self.chromosomes, self.helper, self.TOURNAMENT_SIZE) # must select parent 2 using TOURNAMENT SELECTION parent_2 = ga.tournament_selection(self.chromosomes, self.helper, self.TOURNAMENT_SIZE) # crossover these chomosomes child = ga.crossover(parent_1, parent_2, self.helper, self.CROSSOVER_RATE) child.fitness = None # reset the fitness (it was calculated in the tournament and yet can mutate) child.deposit_distance = None new_population.chromosomes.append(child) child2 = ga.crossover(parent_2, parent_1, self.helper, self.CROSSOVER_RATE) child2.fitness = None # reset the fitness (it was calculated in the tournament and yet can mutate) child2.deposit_distance = None new_population.chromosomes.append(child2) # mutate ga.mutate(new_population.chromosomes, self.helper, self.MUTATION_INVERSION_RATE) # insert one unchanged elit (to keep the best if its the case) new_population.chromosomes.append(elit_unchanged) if len(new_population.chromosomes) != self.POPULATION_SIZE: print 'POPULATION WITH DFF SIZE' return new_population
def generate(population, fitness): mutation = 0.1 new_population = [] sort_population = sortPopulation(population,total_clashes,n_queens) new_population = [x[0] for x in sort_population[:5000]] for i in range(len(new_population)): child = crossover(random.choice(new_population[:5000]),random.choice(new_population[:5000])) if random.random() < mutation: child = mutate(child) new_population.append(child) if fitness(child,total_clashes) == total_clashes: break new_population = sortPopulation(new_population,total_clashes,n_queens) return [x[0] for x in new_population]
# Compute stats avg_targets.append(sum(targets) / float(len(targets))) best_targets.append(min(targets)) print("Best\t", best_targets[-1]) print("Worst\t", max(targets)) print("Mean\t", avg_targets[-1]) print("Variance", np.var(targets)) print() # Compute next generation parents = ga.select_mating_pool(population, targets, N_PARENTS) offspring = ga.crossover( parents, offspring_size=(population.shape[0] - parents.shape[0], population.shape[1])) offspring = ga.mutate(offspring, MUTATION_RATE) population[:N_PARENTS] = parents population[N_PARENTS:] = offspring # Put back into matrix form population = [ann.vec_to_mat(**ann_params, vec=vec) for vec in population] time_passed = time.time() - start print('Generation took {0:.4f} seconds.'.format(time_passed)) # Save population to disk with open("ga_population.csv", mode='w') as file: writer = csv.writer(file, delimiter=',') for i in population: writer.writerow([i]) # Plot average target values
f"Generation: {gen}, Avg Fitness: {avg_fitness}, Avg Games Won: {avg_games}, Max Fitness: {population[0].fitness}, Max Games Won: {max_games_won}" ) # Alter mutation intensity based on closeness to maximum solution (i.e. big mutations at start, small when nearing solution) current_mutation_delta = mutation_delta * (1 - (max_games_won / max_games)) #current_mutation_delta = mutation_delta * (1 - (gen / generations)) parents = ga.select_mating_pool(population, len(population) // 2) children = ga.crossover(parents, population_size - len(parents), 10, ga.intermediate_crossover, crossover_rate=0.5, extra_range=0.25) children = ga.mutate(children, mutation_rate, current_mutation_delta) population = np.append(parents, children) try: with open("500-smartgreedy.csv", 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=csv_header) writer.writeheader() for data in dict_data: writer.writerow(data) except IOError: print("I/O error") population = sorted(population, key=lambda player: player.fitness, reverse=True)