Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. def evolutivo(ngen, pop):
  2. hof = []
  3. p_cruce = 1
  4. p_mutacion = 1
  5. for g in range(ngen):
  6. offspring = toolbox.select(pop, len(pop)) # Siguiente generaciĆ³n
  7. offspring = map(toolbox.clone, offspring) # Clonamos
  8. offspring = list(offspring)
  9.  
  10. # Aplicamos los cruces
  11. for child1, child2 in zip(offspring[::2], offspring[1::2]):
  12. if random.randint(0, 10) < p_cruce:
  13. toolbox.mate(child1, child2)
  14. del child1.fitness.values
  15. del child2.fitness.values
  16.  
  17. # Apply mutation on the offspring
  18. for mutant in offspring:
  19. if random.randint(0, 10) < p_mutacion:
  20. toolbox.mutate(mutant)
  21. del mutant.fitness.values
  22.  
  23. # Evaluate the individuals with an invalid fitness
  24. invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
  25. fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)
  26.  
  27. for ind, fit in zip(invalid_ind, fitnesses):
  28. ind.fitness.values = fit
  29.  
  30. # The population is entirely replaced by the offspring
  31. padres_hijos = pop + offspring
  32. padres_hijos_sort = sorted(padres_hijos, key = lambda x: x.fitness.values, reverse = True)
  33. rep_set = list()
  34. for individual_position in range(len(padres_hijos_sort)):
  35. if set(padres_hijos_sort[individual_position]) in rep_set:
  36. padres_hijos_sort[individual_position] = 0
  37. else:
  38. rep_set.append(set(padres_hijos_sort[individual_position]))
  39.  
  40. new_pop = []
  41. for individual in padres_hijos_sort:
  42. if individual != 0:
  43. new_pop.append(individual)
  44.  
  45. if len(hof) == 0:
  46. hof = new_pop[1:100]
  47. else:
  48. for i in new_pop:
  49. if i.fitness.values > hof[-1].fitness.values and i not in hof:
  50. hof[-1] = i
  51. hof = sorted(hof, key = lambda x: x.fitness.values, reverse = True)
  52.  
  53. pop[:] = offspring
  54. return pop, hof
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement