def calculate_standard_deviation(self, graph, population): import math fitness_list = self.evaluate_fitness(graph, population) avg_score = np.mean( [goalFunction(graph.applyMask(i)) for i in population]) variance = np.mean([math.pow(i - avg_score, 2) for i in fitness_list]) deviation = math.sqrt(variance) return deviation, avg_score
def run(self, graph, population, params, num_parents, debug): start = time.time() population = [ self.generateRandomMask(graph) for i in range(params['population']) ] t_condition, avg_score, deviation = self.ga.termination_method( graph, population) while (t_condition): # Measuring the fitness of each chromosome in the population. And Updating the population fitness_list, population = self.ga.succesion_method( population, graph) # Selecting best mates(Parents) and add them to population parents = self.ga.selection(population, fitness_list, num_parents) # Generate crossover if (params['cross_prob'] > random.random()): children = self.ga.cross_method(population, parents) if (params['mutation_prob'] > random.random()): # Generate Mutations children_mutations = self.ga.mutation(population, children) # Update Population and mesuare new fitness fitness_list = self.ga.evaluate_fitness(graph, population) # Update t_condition t_condition, avg_score, deviation = self.ga.termination_method( graph, population) #Update score graph_indx = np.argmin(fitness_list) mask = population[graph_indx] score = goalFunction(graph.applyMask(mask)) if (score < self.score): self.history.append(score) self.bestGraph = copy.deepcopy(graph.applyMask(mask)) self.score = goalFunction(self.bestGraph) # Debug if (debug): self.debug.show_iterations(avg_score, deviation) #self.debug.show_parent_children(parents, children, children_mutations, graph) end = time.time() self.time = end - start
def roulete(self, fitness_list, population, graph): summation = np.sum( [goalFunction(graph.applyMask(i)) for i in population]) u = random.random() if (u < 0.3): u = 0.3 cur_population = len(population) new_population = int(cur_population * u) #print("cur: {} new: {} u: {}".format(cur_population, new_population, u)) while (len(population) > new_population and len(fitness_list) > new_population and new_population > 4): del population[np.argmax(fitness_list)] del fitness_list[np.argmax(fitness_list)] return fitness_list, population #endregion
def evaluate_fitness(self, graph, population): return [goalFunction(graph.applyMask(i)) for i in population]
def show_parent_children(self, generations, parents, children, children_mutations, graph): child = goalFunction(graph.applyMask(children[0])) print("Generation: {} Parent1: {} parent2: {} Children: {}".format( generations, parents[0][0], parents[1][0], child))