def generation(env, old_population, new_population, p_mutation, p_crossover): for i in range(0, len(old_population) - 1, 2): print('generating',i) # Selection # parent1 = roulette_wheel_selection(old_population) # parent2 = roulette_wheel_selection(old_population) parent1, parent2 = ranking_selection(old_population) # Crossover child1 = copy.deepcopy(parent1) child2 = copy.deepcopy(parent2) child1.weights_biases, child2.weights_biases = crossover(parent1.weights_biases, parent2.weights_biases, p_crossover) # Mutation child1.weights_biases = mutation(child1.weights_biases, p_mutation) child2.weights_biases = mutation(child2.weights_biases, p_mutation) # Update model weights and biases child1.update_model() child2.update_model() child1.calculate_fitness(env) child2.calculate_fitness(env) # If children fitness is greater thant parents update population if child1.fitness + child2.fitness > parent1.fitness + parent2.fitness: new_population[i] = child1 new_population[i + 1] = child2 else: new_population[i] = parent1 new_population[i + 1] = parent2
def generation(env, old_population: list, new_population: list, p_mutation: float, p_crossover: float, p_inversion: float = 0.0): for i in range(0, len(old_population) - 1, 2): # Selection parent1, parent2 = ranking_selection(old_population) # Crossover child1 = copy.deepcopy(parent1) child2 = copy.deepcopy(parent2) child1.weights_biases, child2.weights_biases = crossover( parent1.weights_biases, parent2.weights_biases, p_crossover) # Mutation child1.weights_biases = mutation(child1.weights_biases, p_mutation) child2.weights_biases = mutation(child2.weights_biases, p_mutation) # Update model weights and biases child1.update_model() child2.update_model() child1.calculate_fitness(env) child2.calculate_fitness(env) # If children fitness is greater thant parents update population if child1.fitness + child2.fitness > parent1.fitness + parent2.fitness: new_population[i] = child1 new_population[i + 1] = child2 else: new_population[i] = parent1 new_population[i + 1] = parent2