def optimize(n, d, fitness_function, search_space, max_iter): population = Population(n, d, search_space) best_particle_position = population.particles[0].position best_particle_score = fitness_function(best_particle_position) for i in population.getParticles(): if fitness_function(i.position) < best_particle_score: best_particle_position = i.position best_particle_score = fitness_function(i.position) for __ in xrange(max_iter): best_particle_position_sofar = [] best_particle_score_sofar = float('inf') for i in population.getParticles(): i.velocity = 0.8 * i.velocity + np.random.rand() * ( i.best_position - i.position) * 0.5 + np.random.rand() * ( best_particle_position - i.position) * 0.5 i.position += i.velocity new_score = fitness_function(i.position) if new_score < best_particle_score_sofar: best_particle_position_sofar = i.position best_particle_score_sofar = fitness_function(i.position) if new_score < i.best_score: i.best_score = new_score i.best_position = i.position best_particle_position = best_particle_position_sofar best_particle_score = best_particle_score_sofar counter = 0 for i in population.particles: if (i.position[0] > 5 or i.position[0] < -5) or (i.position[1] > 5 or i.position[1] < -5): counter += 1 print counter return best_particle_score, best_particle_position
def run_instance(fileDir, env): #run a simulation instance #initialisation POP = Population(const.POP_SIZE) performance = np.empty(shape = (int(const.GENERATIONS/env.numGensPerEnvironment),4), dtype='float64') #main for gener in range(const.GENERATIONS): # print progress (%) if (float(gener)/const.GENERATIONS*100) % 2 == 0: print("%.2f"% (float(gener)/const.GENERATIONS*100) + "%") # change environment env.generate_environment(gener) # next generation POP.next_gen(envCues=env.get_cues(), target=env.get_target()) # store performance evaluation if gener % env.numGensPerEnvironment == 0: performance[int(gener / env.numGensPerEnvironment),:] = np.array([POP.get_top_fitness(), POP.get_mean_fitness(), POP.get_top_training_performance(env), POP.get_mean_training_performance(env)]) #save data #generate directory path = os.path.abspath(fileDir) + '/' print(path) ensure_dir(path) #store simulation specifications - global variables save_global_vars(path) #store simulation specifications - global variables - txt file save_global_vars_txt(path) #store population #save_object(POP, path + 'population.p') #store and show figures plot_performance(performance,filePath=path,saveData = True, showFig = False, saveFig = True) POP.get_best_individual().plot_reaction_norm(env, filePath=path, showFig = False, saveFig = True) ind = POP.get_best_individual().get_weights() print(ind)
def carnitas(gen, minGen, limit, choice, degree, acpErr): plt.style.use('seaborn') if int(choice) == 0: df = pd.read_csv('data/anual.csv') function = 'anual' elif int(choice) == 1: df = pd.read_csv('data/semanal.csv') function = 'semanal' else: Tk().withdraw() selectedFile = askopenfilename() df = pd.read_csv(selectedFile) function = selectedFile[43:].replace('.csv', '') lookupTable = {} for i, record in df.iterrows(): key = record['X'] lookupTable[key] = record[function] generations = int(gen) degrees = int(degree) min_generations = int(minGen) min_error = int(acpErr) limit = int(limit) PATH = "C:/Users/Paredon/Desktop/tesis" # Pendiente con esto polynomials = Population(degrees, 1) polynomials.evaluate(lookupTable) polynomials.sort() for g in range(generations): if (g > limit): if ((g > min_generations and polynomials.best[-1].fitness == polynomials.best[-limit].fitness) or polynomials.best[-1].fitness < min_error): break polynomials.enhance(lookupTable) polynomials.plot2D(df['X'], df[function], g, PATH, generations) polynomials.plotBar(df['X'], df[function], g, PATH, generations) create_gif("scatter") create_gif("bar") for g in range(generations): if Path(str(g) + 'scatter.png').is_file(): os.remove(str(g) + 'scatter.png') os.remove(str(g) + 'bar.png') polynomials.best[-1].roundCoefficients() poly = polynomials.best[-1].display() p = np.poly1d(poly) preres = [] yresult = [] if int(choice) == 0: xpred = [0.2, 0.6, 1.2, 2.4] markers = ['1 mes: ', '3 meses: ', '6 meses: ', '1 año: '] for r in xpred: preres.append(round(p(r), 5)) yresult = [x * 10000 for x in preres] create_csv('Yearly', yresult, markers) else: markers = ['1 día: ', '3 días: ', '6 días: ', '1 semana: '] xpred = [2.029, 2.086, 2.143, 2.2] for r in xpred: preres.append(round(p(r), 4)) yresult = [x * 100 for x in preres] create_csv('Weekly', yresult, markers) generate_report(markers, yresult, PATH) return yresult
frac_elites = 0.2 frac_parents = 0.6 mutation_prob = 0.2 mutationMethod = "Guided" # Read the Mona Lisa image monaLisaImage = cv2.imread("mona_lisa.jpg") generationNumber = 0 totalFitnessList = [] # EVOLUTIONARY ALGORITHM # Initialize population with num_inds individuals each having num_genes genes pop = Population(num_inds=num_inds, num_genes=num_genes, tm_size=tm_size, frac_elites=frac_elites, frac_parents=frac_parents, mutation_prob=mutation_prob, mutationMethod="Guided") # While not all generations (num_generations) are computed: while generationNumber <= num_generations: # Sort all chromosomes before evaluating pop.sortAllChromosomes() # Evaluate all the individuals pop.evaluatePopulation(monaLisaImage=monaLisaImage) # Find best individual and save total fitness bestInd = pop.bestIndividual() totalFit = pop.totalFitness() totalFitnessList.append(totalFit) print(bestInd.fitness, generationNumber)
bayes_opt(Population.multi_run_hist, const_args, vary_args, n_iter=3) exit() ######### For grad desc method ### these settings worked pretty great: Population.multi_run_hist(N_evo_runs=10, agent_class=LogicAgentNand.LogicAgentNand, N_pop=16, atom_add_chance=0.5, weight_add_chance=0.8, weight_remove_chance=0.1, weight_change_chance=0.0, complex_atom_add_chance=0.0, NN_output_type='logic', best_N_frac=0.4, grad_desc=True, N_gen=80, N_train_steps=300, N_eval_steps=30, N_trials_per_agent=1, reward_stop_goal=-0.05, max_runtime=90) exit() ######### For grad free method Population.multi_run_hist(40, fname='noGD_nand',
TARGET = pygame.math.Vector2(WIN_WIDTH / 2, 75) LIFESPAN = 225 FRAMECOUNT = 0 def clamp(n, minn, maxn): return max(min(maxn, n), minn) # Barrier rx = 250 ry = 275 rw = 300 rh = 10 rocket_pop = Population(WIN) clock = pygame.time.Clock() font = pygame.font.Font('freesansbold.ttf', 11) generation = 1 running = True while running: clock.tick(50) for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: # Will change this once population is implemented fully. rocket_pop.rockets.append(Rocket(WIN, False))
from sys import argv import numpy as npy import time from random import seed # Local imports from classes import Agent, Population # Input data from arguments gmax = int(argv[1]) n_population = int(argv[2]) n_agent = int(argv[3]) upper_bound = float(argv[4]) lower_bound = float(argv[5]) num_funcion = int(argv[6]) P = Population([Agent(0, [0] * n_agent)] * n_population) P.initialize(upper_bound, lower_bound) P.print_population() P.evaluate(num_funcion) for t in range(1, 30 + 1): print(f'Iteracion {t}') b = P.get_best() b.print_agent() r1 = 2 - (2 * t / gmax) Q = P.create_new_population(b, upper_bound, lower_bound, r1) Q.evaluate(num_funcion) P = P.update_population(Q) P.agents.sort(key=lambda agent: agent.f) P.agents = P.agents[0:n_population]
def genetic_algorithm(goal=[2,4,6,8,10,3], pop_size=20, mut_chance=0.05): # Get user input for the goal of the Genetic Algorithm ''' goal = input("Enter 5 integers (0-10 inclusive) that you wish to converge to, separated by a space: ") goal = goal.split() goal = list(map(int, goal)) ''' # Define the basic parameters ''' pop_size = 20 mut_chance = 0.05 ''' current_gen = 1 # Generate the initial population generation = Population(pop_size) generation.create_pop(len(goal)) # Compute fitness of initial population generation.pop_fitness(goal) # Begin the 'evolution' process while (generation.get_fittest().fitness > 0): # Sort generation in order of fittest to least fittest generation.sort_fittest() # Print out best of current generation if __name__ == "__main__": print("Best Chromosome: %s \nFitness: %d \nCurrent Generation: %d" % (generation.get_fittest().combination, generation.get_fittest().fitness, current_gen)) # Create new generation for population generation.new_generation(mut_chance) # Compute fitness of children generation.pop_fitness(goal) # Increment the generation counter current_gen += 1 if __name__ == "__main__": print("Goal of %s reached" %goal) return current_gen