Save strategy in pickle file

90 views
Skip to first unread message

Carlotta Porcelli

unread,
Jun 10, 2017, 10:30:40 AM6/10/17
to deap-users
Hello, 
I am running a cmaes algorithm but after running the first generation I can't figure out how to load the pickle file saved.
The error I get is: 
population = toolbox.generate()
AttributeError: 'Toolbox' object has no attribute 'generate'
It looks like it is not saving the generation even though the .pkl file is created
Can someone help ?
Thanks

This is the code:
  1. import datetime
  2. import pickle
  3. import random
  4. import sys
  5. import numpy as np
  6. from deap import base
  7. from deap import cma
  8. from deap import creator
  9. from deap import tools
  10. from evol_experimets_chem import EvolutionaryExperiment
  11. from petri_dish_coordinates import petridishes
  12. import os
  13. sys.path.append('../../api')
  14. sys.path.append('../../settings')
  15.  
  16. IND_SIZE = 2
  17. NGEN = 10  # number of generations for which the evolution runs
    number_children = 8  # number of individuals in each population - 8 individuals
    random.seed(30)
  18. creator.create("FitnessMax", base.Fitness, weights=(1.0,))
  19. creator.create("Individual", list, fitness=creator.FitnessMax)
  20. creator.create("Strategy", list)

    toolbox = base.Toolbox()
  21. toolbox.register("attribute", random.random)
  22. toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attribute, n=IND_SIZE)
  23. toolbox.register("population", tools.initRepeat, list, toolbox.individual)

  24. hall_of_fame = tools.HallOfFame(1)
  25. stats = tools.Statistics(lambda individual: individual.fitness.values)
  26. stats.register("avg", np.mean)
  27. stats.register("std", np.std)
  28. stats.register("min", np.min)
  29. stats.register("max", np.max)
  30. logbook = tools.Logbook()
  31. logbook.header = ['gen', 'nevals'] + (stats.fields if stats else [])
  32. experiment = EvolutionaryExperiment()
     
  33. def do_stuff_here(petri, individual):
  34.    """This function prepares the liquid mix with ph and molarity from the individual """
  35.    print "Preparing experiment"
  36.    os.system("say 'Preparing experiment'")
  37.    ph, molarity = experiment.prepare_experiment(individual, petri)
  38.    print "Experiment prepared, starting experiment"
  39.    os.system("say 'Experiment prepared, starting experiment'")
  40.     petri.clean_flag = False
  41.    fitness = experiment.perform_experiment(petri, ph, molarity)
  42.    print "Experiment has finished"
  43.    os.system("say 'Experiment has finished'")
  44.     print "Check that all the vessels have enough reagents!"
  45.    os.system("say 'Check that all the vessels have enough reagents!'")
  46.     return fitness
  47.  
  48. def eval_max(individual):
  49.    for p in petridishes:
           
    if p.is_clean():
  50.            petri = p
  51.            break
  52.    else: # We did not find any clean petri dish
  53.         repeat = True
  54.        while repeat:
  55.            print "There are no clean petri dishes"
  56.            os.system("say 'There are no clean petri dishes'")
  57.            print "Check that all the vessels have enough reagents and place clean petri dishes!"
  58.            os.system("say 'Check that all the vessels have enough reagents and place clean petri dishes!'")
  59.             print "Is everything OK? Type ""y"" to continue"
  60.            text = sys.stdin.readline()
  61.            if "y" in text:
  62.                repeat = False # Take the firs petri dish (all are clean now)
  63.        
    for petris in petridishes:
  64.            petris.clean_flag = True
  65.        petri = petridishes[0]
  66.     fitness = do_stuff_here(petri, individual)
  67.    return fitness
  68.  
  69. toolbox.register("evaluate", eval_max)
  70.  
  71. def check_individuals(individual):
  72.    """ This function checks if the individual's attributes are in the boundaries: if x or y < 0 -> 0 if x or y > 1
  73.   -> 1 """
  74.    x, y = individual[0], individual[1]
  75.    if x < 0.:
  76.        new_x = 0.
  77.        individual[0] = new_x
  78.    elif x > 1.:
  79.        new_x_1 = 1.
  80.        individual[0] = new_x_1
  81.    if y < 0.:
  82.        new_y = 0.
  83.        individual[1] = new_y
  84.    elif y > 1.:
  85.        new_y_1 = 1.
  86.        individual[1] = new_y_1
  87.     return individual
  88.  
  89. def main(population_file="population-g0.pkl"):
  90.    print "The evolutionary experiments start now!"
  91.    os.system("say 'Good afternoon Carlotta! Is everything ready ?'")
  92.    os.system("say 'The evolutionary experiments start now!'")
  93.    if not population_file:
  94.        strategy = cma.Strategy(centroid=[0.5] * IND_SIZE, sigma=0.15, lambda_=number_children)
  95.        toolbox.register("generate", strategy.generate, creator.Individual)
  96.        toolbox.register("update", strategy.update)
  97.        start_gen = 0
  98.    else:
  99.        cp = pickle.load(open(population_file, "r"))
  100.        population = cp["population"]
  101.        start_gen = cp["generation"]
  102.        random.setstate(cp["rndstate"])
  103.        fitnesses = cp["fitness"]
  104.        strategy = cp["strat"]
  105.        for ind, fit in zip(population, fitnesses):
  106.            ind.fitness.values = fit,
  107.         print("Start of evolution")
  108.     for gen in range(start_gen, NGEN):
  109.            print("-- Generation %i --" % gen)
  110.            os.system('say "Generation %i"' % gen)

  111.             population = toolbox.generate()
  112.            for ind in population:
  113.                check_individuals(ind)  # check the attributes of each individual

                fitnesses
    = toolbox.map(toolbox.evaluate, population)
  114.             print 'GENERATION: %d' % gen
  115.            print 'POPULATION: %s' % population
  116.            print 'FITNESSES: %s' % fitnesses
  117.             for ind, fit in zip(population, fitnesses):
  118.                ind.fitness.values = fit,
  119.                hall_of_fame.update(population)

               toolbox.update(population)
  120.             record = stats.compile(population) if stats is not None else {}
  121.            logbook.record(gen=gen, nevals=len(population), **record)
  122.            print logbook
  123.             import csv
  124.            my_list = zip(population, fitnesses)
  125.            print my_list
  126.            with open('/Users/capo/Documents/data_from_exp/logbook/generation_summary-{}.csv'.format(
  127.                    datetime.datetime.now().strftime("%Y-%m-%d %H.%M.%S")), 'wb') as f:
  128.                writer = csv.writer(f, delimiter=',')
  129.                writer.writerow(['generation %d ' % gen])
  130.                writer.writerows([
  131.                    my_list
  132.                ])
  133.             cp = dict(population=population, generation=gen, fitness=fitnesses, rndstate=random.getstate(), strat=strategy)
  134.            filename = "population-g" + str(gen) + ".pkl"
  135.            pickle.dump(cp, open(filename, "wb"))
  136.     print "-- End of (successful) evolution --"
  137.     best_ind = tools.selBest(population, 1)[0]
  138.    print "Best individual is %s, %s" % (best_ind, best_ind.fitness.values)
  139.  
  140. if __name__ == "__main__":
  141.    if len(sys.argv) > 1:
  142.        main(sys.argv[1])
  143.    else:
  144.        main()


François-Michel De Rainville

unread,
Jun 18, 2017, 6:46:27 AM6/18/17
to deap-users
You have te re-register your function within the toolbox when you are loading your pickle. Something like this

if not population_file:
    # Create and register strategy
else:
    cp = pickle.load(open(population_file, "r"))
    # ...
    strategy = cp["strat"]
    toolbox.register("generate", strategy.generate, creator.Individual)
    toolbox.register("update", strategy.update)

Cheers,


--
You received this message because you are subscribed to the Google Groups "deap-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to deap-users+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Carlotta Porcelli

unread,
Jun 27, 2017, 10:35:14 AM6/27/17
to deap-users
that helped, thanks you very much !
To unsubscribe from this group and stop receiving emails from it, send an email to deap-users+...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages