def ga_p(city_list): cfg = GACfg(gene_len=25, gene_size=25, pop_size=1000, elite_size=50, tournament_num=50, tournament_size=100, mutation_rate=0.03, repeatable=False) ga = GA(fitness_func, cfg) ga.prepare_kwargs(city_list=city_list) ga.init_population() progress = [] progress.append(1 / ga.cal_fitness()[0][1]) for _ in range(100): early_stop = ga.evolve() progress.append(1 / ga.cal_fitness()[0][1]) if early_stop: break print("Final distance: " + str(1 / ga.cal_fitness()[0][1])) plt.plot(progress) plt.ylabel('Distance') plt.xlabel('Generation') plt.show()
def f2(x1, x2): return (1. * (x2 - (5.1 / (4. * math.pi ** 2)) * x1 ** 2 + (5. / math.pi) * x1 - 6.) ** 2 + 10. * (1 - 1 / (8 * math.pi)) * math.cos(x1) + 10.) def f3() # TEST NUM. 1 -- f1(x) g = GA(10, 10, p_mut, p_xover, l_dna) b_gene = "" b_fitness = 999999 g.init_population() for _ in range(g.n_gen): decimals = [g.in_context(-2., 2., g.to_decimal(g.population[i]), l_dna) for i in range(g.n_pop)] scores = [f1(x) for x in decimals] for i, gene in enumerate(g.population): if scores[i] < b_fitness: b_fitness = scores[i] b_gene = gene children = []