def evolutionary_algorithm(fitness_fn, objective_fn, logger, pop_size=100, cx_prob=0.8, mut_prob=0.05, mut_flip_prob=0.1, generations=100): pop = create_population(pop_size) for G in range(generations): fit_obj = list( map(lambda pair: utils.FitObjPair(pair[0], pair[1]), zip(map(fitness_fn, pop), map(objective_fn, pop)))) evals = G * pop_size logger.add_gen(fit_obj, evals) # log.append((G, max(fits), sum(fits)/100, G*POP_SIZE)) #print(G, sum(fits), max(fits)) # prints fitness to console mating_pool = selection(pop, [f.fitness for f in fit_obj]) offspring = operators(mating_pool, mut_prob, mut_flip_prob, cx_prob) #pop = offspring[:-1]+[max(pop, key=fitness)] #SGA + elitism pop = offspring[:] #SGA logger.write_files() return pop # for i in range(): # random.seed(i) # pop,log = evolutionary_algorithm(fitness) # logs.append(log) # fits = list(map(fitness, pop)) # # pprint.pprint(list(zip(fits, pop))) # # print(sum(fits), max(fits)) # # pprint.pprint(log) # # # extract fitness evaluations and best fitnesses from logs # evals = [] # best_fit = [] # for log in logs: # evals.append([l[3] for l in log]) # best_fit.append([l[1] for l in log]) # # evals = np.array(evals) # best_fit = np.array(best_fit) # # # plot the converegence graph and quartiles # import matplotlib.pyplot as plt # _, ax = plt.subplots() # # ax.plot(evals[0,:], np.median(best_fit, axis=0), label = "median") # ax.fill_between(evals[0,:], np.percentile(best_fit, q=25, axis=0), # np.percentile(best_fit, q=75, axis=0), alpha = 0.2, label = "Interquartile range") # # legend = ax.legend(loc="upper center", shadow = True, fontsize = 'large') # # # plt.show()
def fitness(ind, cities): # quickly check that ind is a permutation num_cities = len(cities) assert len(ind) == num_cities assert sum(ind) == num_cities*(num_cities - 1)//2 dist = 0 for a, b in zip(ind, ind[1:]): dist += distance(cities[a], cities[b]) dist += distance(cities[ind[-1]], cities[ind[0]]) return utils.FitObjPair(fitness=-dist, objective=dist)
def fitness(ind, weights): bw = bin_weights(weights, ind) return utils.FitObjPair(fitness=1 / (max(bw) - min(bw) + 1), objective=max(bw) - min(bw))
def fitness(ind, train_data, test_data): return utils.FitObjPair(fitness=accuracy(ind, train_data), objective=1 - accuracy(ind, test_data))
def fitness(ind, weights): bw = bin_weights(weights, ind) for i in range(len(bw)): return utils.FitObjPair(fitness=1 / (average(bw) - min(bw)), objective=(average(bw) - min(bw)))
def best_fitness(ind, weights): bw = bin_weights(weights, ind) M = sum(bw) / len(bw) S = sum(map(lambda w: abs(w - M), bw)) F = 0.99**S return utils.FitObjPair(fitness=F, objective=S)
def better_fitness(ind, weights): bw = bin_weights(weights, ind) M = sum(bw) / len(bw) S = sum(map(lambda w: (w - M)**2, bw))**(1 / len(bw)) return utils.FitObjPair(fitness=1 / (S + 1), objective=max(bw) - min(bw))