diff --git a/mloop/controllers.py b/mloop/controllers.py index ca2035a..3777c4d 100644 --- a/mloop/controllers.py +++ b/mloop/controllers.py @@ -18,32 +18,32 @@ class ControllerInterrupt(Exception): ''' - Exception that is raised when the controlled is ended with the end flag or event. + Exception that is raised when the controlled is ended with the end flag or event. ''' def __init__(self): super(ControllerInterrupt,self).__init__() - + def create_controller(interface, - controller_type='gaussian_process', + controller_type='gaussian_process', **controller_config_dict): ''' Start the controller with the options provided. - + Args: interface (interface): Interface with queues and events to be passed to controller - + Keyword Args: controller_type (Optional [str]): Defines the type of controller can be 'random', 'nelder' or 'gaussian_process'. Defaults to 'gaussian_process'. **controller_config_dict : Options to be passed to controller. - + Returns: Controller : threadible object which must be started with start() to get the controller running. - + Raises: ValueError : if controller_type is an unrecognized string ''' log = logging.getLogger(__name__) - + controller_type = str(controller_type) if controller_type=='gaussian_process': controller = GaussianProcessController(interface, **controller_config_dict) @@ -58,33 +58,33 @@ def create_controller(interface, else: log.error('Unknown controller type:' + repr(controller_type)) raise ValueError - + return controller class Controller(): ''' Abstract class for controllers. The controller controls the entire M-LOOP process. The controller for each algorithm all inherit from this class. The class stores a variety of data which all algorithms use and also all of the achiving and saving features. - + In order to implement your own controller class the minimum requirement is to add a learner to the learner variable. And implement the next_parameters method, where you provide the appropriate information to the learner and get the next parameters. - + See the RandomController for a simple implementation of a controller. - + Note the first three keywords are all possible halting conditions for the controller. If any of them are satisfied the controller will halt (meaning an and condition is used). - + Also creates an empty variable learner. The simplest way to make a working controller is to assign a learner of some kind to this variable, and add appropriate queues and events from it. - + Args: interface (interface): The interface process. Is run by learner. - + Keyword Args: max_num_runs (Optional [float]): The number of runs before the controller stops. If set to float('+inf') the controller will run forever. Default float('inf'), meaning the controller will run until another condition is met. target_cost (Optional [float]): The target cost for the run. If a run achieves a cost lower than the target, the controller is stopped. Default float('-inf'), meaning the controller will run until another condition is met. - max_num_runs_without_better_params (Otional [float]): Puts a limit on the number of runs are allowed before a new better set of parameters is found. Default float('inf'), meaning the controller will run until another condition is met. + max_num_runs_without_better_params (Otional [float]): Puts a limit on the number of runs are allowed before a new better set of parameters is found. Default float('inf'), meaning the controller will run until another condition is met. controller_archive_filename (Optional [string]): Filename for archive. Contains costs, parameter history and other details depending on the controller type. Default 'ControllerArchive.mat' controller_archive_file_type (Optional [string]): File type for archive. Can be either 'txt' a human readable text file, 'pkl' a python dill file, 'mat' a matlab file or None if there is no archive. Default 'mat'. archive_extra_dict (Optional [dict]): A dictionary with any extra variables that are to be saved to the archive. If None, nothing is added. Default None. start_datetime (Optional datetime): Datetime for when controller was started. - + Attributes: params_out_queue (queue): Queue for parameters to next be run by experiment. costs_in_queue (queue): Queue for costs (and other details) that have been returned by experiment. @@ -94,7 +94,7 @@ class Controller(): learner_costs_queue (queue): The costs queue for the learner end_learner (event): Event used to trigger the end of the learner num_in_costs (int): Counter for the number of costs received. - num_out_params (int): Counter for the number of parameters received. + num_out_params (int): Counter for the number of parameters received. out_params (list): List of all parameters sent out by controller. out_extras (list): Any extras associated with the output parameters. in_costs (list): List of costs received by controller. @@ -102,10 +102,10 @@ class Controller(): best_cost (float): The lowest, and best, cost received by the learner. best_uncer (float): The uncertainty associated with the best cost. best_params (array): The best parameters recieved by the learner. - best_index (float): The run number that produced the best cost. - + best_index (float): The run number that produced the best cost. + ''' - + def __init__(self, interface, max_num_runs = float('+inf'), target_cost = float('-inf'), @@ -115,11 +115,11 @@ def __init__(self, interface, archive_extra_dict = None, start_datetime = None, **kwargs): - + #Make logger self.remaining_kwargs = mlu._config_logger(**kwargs) self.log = logging.getLogger(__name__) - + #Variable that are included in archive self.num_in_costs = 0 self.num_out_params = 0 @@ -135,7 +135,7 @@ def __init__(self, interface, self.best_uncer = float('nan') self.best_index = float('nan') self.best_params = float('nan') - + #Variables that used internally self.last_out_params = None self.curr_params = None @@ -143,29 +143,29 @@ def __init__(self, interface, self.curr_uncer = None self.curr_bad = None self.curr_extras = None - + #Constants self.controller_wait = float(1) - + #Learner related variables self.learner_params_queue = None self.learner_costs_queue = None self.end_learner = None self.learner = None - + #Variables set by user - + #save interface and extract important variables if isinstance(interface, mli.Interface): self.interface = interface else: self.log.error('interface is not a Interface as defined in the MLOOP package.') raise TypeError - + self.params_out_queue = interface.params_out_queue self.costs_in_queue = interface.costs_in_queue self.end_interface = interface.end_event - + #Other options if start_datetime is None: self.start_datetime = datetime.datetime.now() @@ -180,7 +180,7 @@ def __init__(self, interface, if self.max_num_runs_without_better_params<=0: self.log.error('Max number of repeats must be greater than zero. max_num_runs:'+repr(max_num_runs_without_better_params)) raise ValueError - + if mlu.check_file_type_supported(controller_archive_file_type): self.controller_archive_file_type = controller_archive_file_type else: @@ -193,7 +193,7 @@ def __init__(self, interface, os.makedirs(mlu.archive_foldername) self.controller_archive_filename =str(controller_archive_filename) self.total_archive_filename = mlu.archive_foldername + self.controller_archive_filename + '_' + mlu.datetime_to_string(self.start_datetime) + '.' + self.controller_archive_file_type - + self.archive_dict = {'archive_type':'controller', 'num_out_params':self.num_out_params, 'out_params':self.out_params, @@ -205,21 +205,21 @@ def __init__(self, interface, 'in_extras':self.in_extras, 'max_num_runs':self.max_num_runs, 'start_datetime':mlu.datetime_to_string(self.start_datetime)} - + if archive_extra_dict is not None: self.archive_dict.update(archive_extra_dict) - + self.log.debug('Controller init completed.') - + def check_end_conditions(self): ''' Check whether either of the three end contions have been met: number_of_runs, target_cost or max_num_runs_without_better_params. - + Returns: - bool : True, if the controlled should continue, False if the controller should end. + bool : True, if the controlled should continue, False if the controller should end. ''' return (self.num_in_costs < self.max_num_runs) and (self.best_cost > self.target_cost) and (self.num_last_best_cost < self.max_num_runs_without_better_params) - + def _update_controller_with_learner_attributes(self): ''' Update the controller with properties from the learner. @@ -228,19 +228,19 @@ def _update_controller_with_learner_attributes(self): self.learner_costs_queue = self.learner.costs_in_queue self.end_learner = self.learner.end_event self.remaining_kwargs = self.learner.remaining_kwargs - + self.archive_dict.update({'num_params':self.learner.num_params, 'min_boundary':self.learner.min_boundary, 'max_boundary':self.learner.max_boundary}) - - + + def _put_params_and_out_dict(self, params, param_type=None, **kwargs): ''' - Send parameters to queue and whatever additional keywords. Saves sent variables in appropriate storage arrays. - + Send parameters to queue and whatever additional keywords. Saves sent variables in appropriate storage arrays. + Args: params (array) : array of values to be sent to file - + Keyword Args: **kwargs: any additional data to be attached to file sent to experiment ''' @@ -255,11 +255,11 @@ def _put_params_and_out_dict(self, params, param_type=None, **kwargs): self.out_type.append(param_type) self.log.info('params ' + str(params)) #self.log.debug('Put params num:' + repr(self.num_out_params )) - + def _get_cost_and_in_dict(self): ''' Get cost, uncertainty, parameters, bad and extra data from experiment. Stores in a list of history and also puts variables in their appropriate 'current' variables - + Note returns nothing, stores everything in the internal storage arrays and the curr_variables ''' while True: @@ -269,16 +269,16 @@ def _get_cost_and_in_dict(self): continue else: break - + self.num_in_costs += 1 self.num_last_best_cost += 1 - + if not ('cost' in in_dict) and (not ('bad' in in_dict) or not in_dict['bad']): self.log.error('You must provide at least the key cost or the key bad with True.') raise ValueError try: - self.curr_cost = float(in_dict.pop('cost',float('nan'))) - self.curr_uncer = float(in_dict.pop('uncer',0)) + self.curr_cost = float(in_dict.pop('cost',float('nan'))) + self.curr_uncer = float(in_dict.pop('uncer',0)) self.curr_bad = bool(in_dict.pop('bad',False)) self.curr_extras = in_dict except ValueError: @@ -286,7 +286,7 @@ def _get_cost_and_in_dict(self): raise if self.curr_bad and ('cost' in in_dict): self.log.warning('The cost provided with the bad run will be saved, but not used by the learners.') - + self.in_costs.append(self.curr_cost) self.in_uncers.append(self.curr_uncer) self.in_bads.append(self.curr_bad) @@ -303,7 +303,7 @@ def _get_cost_and_in_dict(self): else: self.log.info('cost ' + str(self.curr_cost) + ' +/- ' + str(self.curr_uncer)) #self.log.debug('Got cost num:' + repr(self.num_in_costs)) - + def save_archive(self): ''' Save the archive associated with the controller class. Only occurs if the filename for the archive is not None. Saves with the format previously set. @@ -322,15 +322,15 @@ def save_archive(self): raise else: self.log.debug('Did not save controller archive file.') - + def optimize(self): ''' Optimize the experiment. This code learner and interface processes/threads are launched and appropriately ended. - + Starts both threads and catches kill signals and shuts down appropriately. ''' log = logging.getLogger(__name__) - + try: log.info('Optimization started.') self._start_up() @@ -350,14 +350,14 @@ def optimize(self): self._shut_down() self.print_results() self.log.info('M-LOOP Done.') - + def _start_up(self): ''' Start the learner and interface threads/processes. ''' self.learner.start() self.interface.start() - + def _shut_down(self): ''' Shutdown and clean up resources of the controller. end the learners, queue_listener and make one last save of archive. @@ -373,8 +373,8 @@ def _shut_down(self): self.log.debug('Learner joined.') self.interface.join() self.log.debug('Interface joined.') - self.save_archive() - + self.save_archive() + def print_results(self): ''' Print results from optimization run to the logs @@ -393,7 +393,7 @@ def print_results(self): def _optimization_routine(self): ''' - Runs controller main loop. Gives parameters to experiment and saves costs returned. + Runs controller main loop. Gives parameters to experiment and saves costs returned. ''' self.log.debug('Start controller loop.') self.log.info('Run:' + str(self.num_in_costs +1)) @@ -411,61 +411,61 @@ def _optimization_routine(self): def _first_params(self): ''' - Checks queue to get first parameters. - + Checks queue to get first parameters. + Returns: Parameters for first experiment ''' return self.learner_params_queue.get() - + def _next_params(self): ''' Abstract method. - + When implemented should send appropriate information to learner and get next parameters. - + Returns: Parameters for next experiment. ''' pass - + class RandomController(Controller): ''' Controller that simply returns random variables for the next parameters. Costs are stored but do not influence future points picked. - + Args: params_out_queue (queue): Queue for parameters to next be run by experiment. costs_in_queue (queue): Queue for costs (and other details) that have been returned by experiment. **kwargs (Optional [dict]): Dictionary of options to be passed to Controller and Random Learner. - + ''' def __init__(self, interface,**kwargs): - + super(RandomController,self).__init__(interface, **kwargs) self.learner = mll.RandomLearner(start_datetime = self.start_datetime, learner_archive_filename=None, **self.remaining_kwargs) - + self._update_controller_with_learner_attributes() self.out_type.append('random') - - self.log.debug('Random controller init completed.') - + + self.log.debug('Random controller init completed.') + def _next_params(self): ''' Sends cost uncer and bad tuple to learner then gets next parameters. - + Returns: Parameters for next experiment. ''' self.learner_costs_queue.put(self.best_params) - return self.learner_params_queue.get() - + return self.learner_params_queue.get() + class NelderMeadController(Controller): ''' Controller for the Nelder-Mead solver. Suggests new parameters based on the Nelder-Mead algorithm. Can take no boundaries or hard boundaries. More details for the Nelder-Mead options are in the learners section. - + Args: params_out_queue (queue): Queue for parameters to next be run by experiment. costs_in_queue (queue): Queue for costs (and other details) that have been returned by experiment. @@ -473,14 +473,14 @@ class NelderMeadController(Controller): ''' def __init__(self, interface, **kwargs): - super(NelderMeadController,self).__init__(interface, **kwargs) - + super(NelderMeadController,self).__init__(interface, **kwargs) + self.learner = mll.NelderMeadLearner(start_datetime = self.start_datetime, **self.remaining_kwargs) - + self._update_controller_with_learner_attributes() self.out_type.append('nelder_mead') - + def _next_params(self): ''' Gets next parameters from Nelder-Mead learner. @@ -488,14 +488,14 @@ def _next_params(self): if self.curr_bad: cost = float('inf') else: - cost = self.curr_cost + cost = self.curr_cost self.learner_costs_queue.put(cost) return self.learner_params_queue.get() class DifferentialEvolutionController(Controller): ''' - Controller for the differential evolution learner. - + Controller for the differential evolution learner. + Args: params_out_queue (queue): Queue for parameters to next be run by experiment. costs_in_queue (queue): Queue for costs (and other details) that have been returned by experiment. @@ -503,14 +503,14 @@ class DifferentialEvolutionController(Controller): ''' def __init__(self, interface, **kwargs): - super(DifferentialEvolutionController,self).__init__(interface, **kwargs) - + super(DifferentialEvolutionController,self).__init__(interface, **kwargs) + self.learner = mll.DifferentialEvolutionLearner(start_datetime = self.start_datetime, **self.remaining_kwargs) - + self._update_controller_with_learner_attributes() self.out_type.append('differential_evolution') - + def _next_params(self): ''' Gets next parameters from differential evolution learner. @@ -518,15 +518,15 @@ def _next_params(self): if self.curr_bad: cost = float('inf') else: - cost = self.curr_cost + cost = self.curr_cost self.learner_costs_queue.put(cost) return self.learner_params_queue.get() class MachineLearnerController(Controller): ''' - Abstract Controller class for the machine learning based solvers. - + Abstract Controller class for the machine learning based solvers. + Args: interface (Interface): The interface to the experiment under optimization. **kwargs (Optional [dict]): Dictionary of options to be passed to Controller parent class, initial training learner and Gaussian Process learner. @@ -536,37 +536,37 @@ class MachineLearnerController(Controller): num_training_runs (Optional [int]): The number of training runs to before starting the learner. If None, will by ten or double the number of parameters, whatever is larger. no_delay (Optional [bool]): If True, there is never any delay between a returned cost and the next parameters to run for the experiment. In practice, this means if the gaussian process has not prepared the next parameters in time the learner defined by the initial training source is used instead. If false, the controller will wait for the gaussian process to predict the next parameters and there may be a delay between runs. ''' - - def __init__(self, interface, + + def __init__(self, interface, training_type='differential_evolution', num_training_runs=None, no_delay=True, num_params=None, min_boundary=None, max_boundary=None, - trust_region=None, + trust_region=None, learner_archive_filename = mll.default_learner_archive_filename, learner_archive_file_type = mll.default_learner_archive_file_type, **kwargs): - - super(MachineLearnerController,self).__init__(interface, **kwargs) - + + super(MachineLearnerController,self).__init__(interface, **kwargs) + self.last_training_cost = None self.last_training_bad = None self.last_training_run_flag = False - + if num_training_runs is None: if num_params is None: self.num_training_runs = 10 else: self.num_training_runs = max(10, 2*int(num_params)) else: - self.num_training_runs = int(num_training_runs) + self.num_training_runs = int(num_training_runs) if self.num_training_runs<=0: self.log.error('Number of training runs must be larger than zero:'+repr(self.num_training_runs)) raise ValueError self.no_delay = bool(no_delay) - + self.training_type = str(training_type) if self.training_type == 'random': self.learner = mll.RandomLearner(start_datetime=self.start_datetime, @@ -586,7 +586,7 @@ def __init__(self, interface, learner_archive_filename=None, learner_archive_file_type=learner_archive_file_type, **self.remaining_kwargs) - + elif self.training_type == 'differential_evolution': self.learner = mll.DifferentialEvolutionLearner(start_datetime=self.start_datetime, num_params=num_params, @@ -596,32 +596,32 @@ def __init__(self, interface, evolution_strategy='rand2', learner_archive_filename=None, learner_archive_file_type=learner_archive_file_type, - **self.remaining_kwargs) - + **self.remaining_kwargs) + else: self.log.error('Unknown training type provided to Gaussian process controller:' + repr(training_type)) self.archive_dict.update({'training_type':self.training_type}) self._update_controller_with_learner_attributes() - - + + def _update_controller_with_machine_learner_attributes(self): - + self.ml_learner_params_queue = self.ml_learner.params_out_queue self.ml_learner_costs_queue = self.ml_learner.costs_in_queue self.end_ml_learner = self.ml_learner.end_event self.new_params_event = self.ml_learner.new_params_event self.remaining_kwargs = self.ml_learner.remaining_kwargs self.generation_num = self.ml_learner.generation_num - - + + def _put_params_and_out_dict(self, params): ''' Override _put_params_and_out_dict function, used when the training learner creates parameters. Makes the defualt param_type the training type and sets last_training_run_flag. ''' super(MachineLearnerController,self)._put_params_and_out_dict(params, param_type=self.training_type) - self.last_training_run_flag = True - + self.last_training_run_flag = True + def _get_cost_and_in_dict(self): ''' Call _get_cost_and_in_dict() of parent Controller class. But also sends cost to Gaussian process learner and saves the cost if the parameters came from a trainer. @@ -636,7 +636,7 @@ def _get_cost_and_in_dict(self): self.curr_cost, self.curr_uncer, self.curr_bad)) - + def _next_params(self): ''' Gets next parameters from training learner. @@ -646,19 +646,19 @@ def _next_params(self): if self.last_training_bad: cost = float('inf') else: - cost = self.last_training_cost + cost = self.last_training_cost self.learner_costs_queue.put(cost) temp = self.learner_params_queue.get() - + elif self.training_type == 'random': #Copied from RandomController self.learner_costs_queue.put(self.best_params) - temp = self.learner_params_queue.get() - + temp = self.learner_params_queue.get() + else: self.log.error('Unknown training type called. THIS SHOULD NOT HAPPEN') return temp - + def _start_up(self): ''' Runs pararent method and also starts training_learner. @@ -684,7 +684,7 @@ def _optimization_routine(self): self._put_params_and_out_dict(next_params) self.save_archive() self._get_cost_and_in_dict() - + if self.check_end_conditions(): #Start last training run self.log.info('Run:' + str(self.num_in_costs +1)) @@ -696,10 +696,10 @@ def _optimization_routine(self): self.save_archive() self._get_cost_and_in_dict() self.log.debug('End training runs.') - + ml_consec = 0 - ml_count = 0 - + ml_count = 0 + while self.check_end_conditions(): self.log.info('Run:' + str(self.num_in_costs +1)) if ml_consec==self.generation_num or (self.no_delay and self.ml_learner_params_queue.empty()): @@ -750,16 +750,16 @@ def _shut_down(self): if self.ml_learner.predict_global_minima_at_end or self.ml_learner.predict_local_minima_at_end: self.log.info('Machine Learner did not provide best and/or all minima.') super(MachineLearnerController,self)._shut_down() - + def print_results(self): ''' - Adds some additional output to the results specific to controller. + Adds some additional output to the results specific to controller. ''' super(MachineLearnerController,self).print_results() try: self.log.info('Predicted best parameters:' + str(self.predicted_best_parameters)) self.log.info('Predicted best cost:' + str(self.predicted_best_cost) + ' +/- ' + str(self.predicted_best_uncertainty)) - + except AttributeError: pass try: @@ -769,34 +769,34 @@ def print_results(self): class GaussianProcessController(MachineLearnerController): ''' - Controller for the Gaussian Process solver. Primarily suggests new points from the Gaussian Process learner. However, during the initial few runs it must rely on a different optimization algorithm to get some points to seed the learner. - + Controller for the Gaussian Process solver. Primarily suggests new points from the Gaussian Process learner. However, during the initial few runs it must rely on a different optimization algorithm to get some points to seed the learner. + Args: interface (Interface): The interface to the experiment under optimization. **kwargs (Optional [dict]): Dictionary of options to be passed to Controller parent class, initial training learner and Gaussian Process learner. Keyword Args: - + ''' - - def __init__(self, interface, + + def __init__(self, interface, num_params=None, min_boundary=None, max_boundary=None, - trust_region=None, + trust_region=None, learner_archive_filename = mll.default_learner_archive_filename, learner_archive_file_type = mll.default_learner_archive_file_type, **kwargs): - + super(GaussianProcessController,self).__init__(interface, num_params=num_params, min_boundary=min_boundary, max_boundary=max_boundary, trust_region=trust_region, learner_archive_filename=learner_archive_filename, - learner_archive_file_type=learner_archive_file_type, - **kwargs) - + learner_archive_file_type=learner_archive_file_type, + **kwargs) + self.ml_learner = mll.GaussianProcessLearner(start_datetime=self.start_datetime, num_params=num_params, min_boundary=min_boundary, @@ -805,26 +805,26 @@ def __init__(self, interface, learner_archive_filename=learner_archive_filename, learner_archive_file_type=learner_archive_file_type, **self.remaining_kwargs) - + self._update_controller_with_machine_learner_attributes() class NeuralNetController(MachineLearnerController): ''' - Controller for the Neural Net solver. Primarily suggests new points from the Neural Net learner. However, during the initial few runs it must rely on a different optimization algorithm to get some points to seed the learner. - + Controller for the Neural Net solver. Primarily suggests new points from the Neural Net learner. However, during the initial few runs it must rely on a different optimization algorithm to get some points to seed the learner. + Args: interface (Interface): The interface to the experiment under optimization. **kwargs (Optional [dict]): Dictionary of options to be passed to Controller parent class, initial training learner and Gaussian Process learner. Keyword Args: - + ''' - - def __init__(self, interface, + + def __init__(self, interface, num_params=None, min_boundary=None, max_boundary=None, - trust_region=None, + trust_region=None, learner_archive_filename = mll.default_learner_archive_filename, learner_archive_file_type = mll.default_learner_archive_file_type, **kwargs): @@ -835,9 +835,9 @@ def __init__(self, interface, max_boundary=max_boundary, trust_region=trust_region, learner_archive_filename=learner_archive_filename, - learner_archive_file_type=learner_archive_file_type, - **kwargs) - + learner_archive_file_type=learner_archive_file_type, + **kwargs) + self.ml_learner = mll.NeuralNetLearner(start_datetime=self.start_datetime, num_params=num_params, min_boundary=min_boundary, @@ -846,8 +846,8 @@ def __init__(self, interface, learner_archive_filename=learner_archive_filename, learner_archive_file_type=learner_archive_file_type, **self.remaining_kwargs) - + self._update_controller_with_machine_learner_attributes() - \ No newline at end of file + diff --git a/mloop/learners.py b/mloop/learners.py index ed15093..a0f3572 100644 --- a/mloop/learners.py +++ b/mloop/learners.py @@ -1,5 +1,5 @@ ''' -Module of learners used to determine what parameters to try next given previous cost evaluations. +Module of learners used to determine what parameters to try next given previous cost evaluations. Each learner is created and controlled by a controller. ''' @@ -21,26 +21,26 @@ import multiprocessing as mp learner_thread_count = 0 -default_learner_archive_filename = 'learner_archive' +default_learner_archive_filename = 'learner_archive' default_learner_archive_file_type = 'txt' class LearnerInterrupt(Exception): ''' - Exception that is raised when the learner is ended with the end flag or event. + Exception that is raised when the learner is ended with the end flag or event. ''' def __init__(self): ''' Create LearnerInterrupt. ''' super(LearnerInterrupt,self).__init__() - + class Learner(): ''' Base class for all learners. Contains default boundaries and some useful functions that all learners use. - - The class that inherits from this class should also inherit from threading.Thread or multiprocessing.Process, depending if you need the learner to be a genuine parallel process or not. - + + The class that inherits from this class should also inherit from threading.Thread or multiprocessing.Process, depending if you need the learner to be a genuine parallel process or not. + Keyword Args: num_params (Optional [int]): The number of parameters to be optimized. If None defaults to 1. Default None. min_boundary (Optional [array]): Array with minimimum values allowed for each parameter. Note if certain values have no minimum value you can set them to -inf for example [-1, 2, float('-inf')] is a valid min_boundary. If None sets all the boundaries to '-1'. Default None. @@ -49,36 +49,36 @@ class Learner(): learner_archive_file_type (Optional [string]): File type for archive. Can be either 'txt' a human readable text file, 'pkl' a python dill file, 'mat' a matlab file or None if there is no archive. Default 'mat'. log_level (Optional [int]): Level for the learners logger. If None, set to warning. Default None. start_datetime (Optional [datetime]): Start date time, if None, is automatically generated. - + Attributes: params_out_queue (queue): Queue for parameters created by learner. costs_in_queue (queue): Queue for costs to be used by learner. end_event (event): Event to trigger end of learner. ''' - - def __init__(self, + + def __init__(self, num_params=None, - min_boundary=None, - max_boundary=None, + min_boundary=None, + max_boundary=None, learner_archive_filename=default_learner_archive_filename, learner_archive_file_type=default_learner_archive_file_type, start_datetime=None, **kwargs): super(Learner,self).__init__() - + global learner_thread_count - learner_thread_count += 1 + learner_thread_count += 1 self.log = logging.getLogger(__name__ + '.' + str(learner_thread_count)) - + self.learner_wait=float(1) - + self.remaining_kwargs = kwargs - + self.params_out_queue = mp.Queue() self.costs_in_queue = mp.Queue() self.end_event = mp.Event() - + if num_params is None: self.log.warning('num_params not provided, setting to default value of 1.') self.num_params = 1 @@ -121,42 +121,42 @@ def __init__(self, os.makedirs(mlu.archive_foldername) self.learner_archive_filename =str(learner_archive_filename) self.total_archive_filename = mlu.archive_foldername + self.learner_archive_filename + '_' + mlu.datetime_to_string(self.start_datetime) + '.' + self.learner_archive_file_type - + self.archive_dict = {'archive_type':'learner', 'num_params':self.num_params, 'min_boundary':self.min_boundary, 'max_boundary':self.max_boundary, 'start_datetime':mlu.datetime_to_string(self.start_datetime)} - - self.log.debug('Learner init completed.') - + + self.log.debug('Learner init completed.') + def check_num_params(self,param): ''' Check the number of parameters is right. ''' return param.shape == (self.num_params,) - + def check_in_boundary(self,param): ''' Check give parameters are within stored boundaries - + Args: param (array): array of parameters - + Returns: bool : True if the parameters are within boundaries, False otherwise. ''' param = np.array(param) testbool = np.all(param >= self.min_boundary) and np.all(param <= self.max_boundary) return testbool - + def check_in_diff_boundary(self,param): ''' Check given distances are less than the boundaries - + Args: param (array): array of distances - + Returns: bool : True if the distances are smaller or equal to boundaries, False otherwise. ''' @@ -166,11 +166,11 @@ def check_in_diff_boundary(self,param): def put_params_and_get_cost(self, params, **kwargs): ''' - Send parameters to queue and whatever additional keywords. Saves sent variables in appropriate storage arrays. - + Send parameters to queue and whatever additional keywords. Saves sent variables in appropriate storage arrays. + Args: params (array) : array of values to be sent to file - + Returns: cost from the cost queue ''' @@ -196,7 +196,7 @@ def put_params_and_get_cost(self, params, **kwargs): raise LearnerInterrupt #self.log.debug('Learner cost='+repr(cost)) return cost - + def save_archive(self): ''' Save the archive associated with the learner class. Only occurs if the filename for the archive is not None. Saves with the format previously set. @@ -204,19 +204,19 @@ def save_archive(self): self.update_archive() if self.learner_archive_filename is not None: mlu.save_dict_to_file(self.archive_dict, self.total_archive_filename, self.learner_archive_file_type) - + def update_archive(self): ''' Abstract method for update to the archive. To be implemented by child class. ''' pass - + def _set_trust_region(self,trust_region): ''' - Sets trust region properties for learner that have this. Common function for learners with trust regions. - + Sets trust region properties for learner that have this. Common function for learners with trust regions. + Args: - trust_region (float or array): Property defines the trust region. + trust_region (float or array): Property defines the trust region. ''' if trust_region is None: self.trust_region = float('nan') @@ -231,7 +231,7 @@ def _set_trust_region(self,trust_region): raise ValueError else: self.trust_region = np.array(trust_region, dtype=float) - + if self.has_trust_region: if not self.check_num_params(self.trust_region): self.log.error('Shape of the trust_region does not match the number of parameters:' + repr(self.trust_region)) @@ -242,7 +242,7 @@ def _set_trust_region(self,trust_region): if not self.check_in_diff_boundary(self.trust_region): self.log.error('The trust_region must be smaller than the range of the boundaries:' + repr(self.trust_region)) raise ValueError - + def _shut_down(self): ''' Shut down and perform one final save of learner. @@ -253,24 +253,24 @@ def _shut_down(self): class RandomLearner(Learner, threading.Thread): ''' Random learner. Simply generates new parameters randomly with a uniform distribution over the boundaries. Learner is perhaps a misnomer for this class. - + Args: - **kwargs (Optional dict): Other values to be passed to Learner. - + **kwargs (Optional dict): Other values to be passed to Learner. + Keyword Args: min_boundary (Optional [array]): If set to None, overrides default learner values and sets it to a set of value 0. Default None. max_boundary (Optional [array]): If set to None overides default learner values and sets it to an array of value 1. Default None. first_params (Optional [array]): The first parameters to test. If None will just randomly sample the initial condition. - trust_region (Optional [float or array]): The trust region defines the maximum distance the learner will travel from the current best set of parameters. If None, the learner will search everywhere. If a float, this number must be between 0 and 1 and defines maximum distance the learner will venture as a percentage of the boundaries. If it is an array, it must have the same size as the number of parameters and the numbers define the maximum absolute distance that can be moved along each direction. + trust_region (Optional [float or array]): The trust region defines the maximum distance the learner will travel from the current best set of parameters. If None, the learner will search everywhere. If a float, this number must be between 0 and 1 and defines maximum distance the learner will venture as a percentage of the boundaries. If it is an array, it must have the same size as the number of parameters and the numbers define the maximum absolute distance that can be moved along each direction. ''' - - def __init__(self, + + def __init__(self, trust_region=None, first_params=None, **kwargs): - + super(RandomLearner,self).__init__(**kwargs) - + if not np.all(self.diff_boundary>0.0): self.log.error('All elements of max_boundary are not larger than min_boundary') raise ValueError @@ -287,13 +287,13 @@ def __init__(self, if not self.check_in_boundary(self.first_params): self.log.error('first_params is not in the boundary:' + repr(self.first_params)) raise ValueError - + self._set_trust_region(trust_region) - + self.archive_dict.update({'archive_type':'random_learner'}) - + self.log.debug('Random learner init completed.') - + def run(self): ''' Puts the next parameters on the queue which are randomly picked from a uniform distribution between the minimum and maximum boundaries when a cost is added to the cost queue. @@ -303,7 +303,7 @@ def run(self): next_params = self.min_boundary + nr.rand(self.num_params) * self.diff_boundary else: next_params = self.first_params - while not self.end_event.is_set(): + while not self.end_event.is_set(): try: centre_params = self.put_params_and_get_cost(next_params) except LearnerInterrupt: @@ -315,46 +315,46 @@ def run(self): next_params = temp_min + nr.rand(self.num_params) * (temp_max - temp_min) else: next_params = self.min_boundary + nr.rand(self.num_params) * self.diff_boundary - + self._shut_down() self.log.debug('Ended Random Learner') - + class NelderMeadLearner(Learner, threading.Thread): ''' Nelder-Mead learner. Executes the Nelder-Mead learner algorithm and stores the needed simplex to estimate the next points. - + Args: params_out_queue (queue): Queue for parameters from controller. costs_in_queue (queue): Queue for costs for nelder learner. The queue should be populated with cost (float) corresponding to the last parameter sent from the Nelder-Mead Learner. Can be a float('inf') if it was a bad run. end_event (event): Event to trigger end of learner. - + Keyword Args: initial_simplex_corner (Optional [array]): Array for the initial set of parameters, which is the lowest corner of the initial simplex. If None the initial parameters are randomly sampled if the boundary conditions are provided, or all are set to 0 if boundary conditions are not provided. initial_simplex_displacements (Optional [array]): Array used to construct the initial simplex. Each array is the positive displacement of the parameters above the init_params. If None and there are no boundary conditions, all are set to 1. If None and there are boundary conditions assumes the initial conditions are scaled. Default None. - initial_simplex_scale (Optional [float]): Creates a simplex using a the boundary conditions and the scaling factor provided. If None uses the init_simplex if provided. If None and init_simplex is not provided, but boundary conditions are is set to 0.5. Default None. - + initial_simplex_scale (Optional [float]): Creates a simplex using a the boundary conditions and the scaling factor provided. If None uses the init_simplex if provided. If None and init_simplex is not provided, but boundary conditions are is set to 0.5. Default None. + Attributes: init_simplex_corner (array): Parameters for the corner of the initial simple used. - init_simplex_disp (array): Parameters for the displacements about the simplex corner used to create the initial simple. + init_simplex_disp (array): Parameters for the displacements about the simplex corner used to create the initial simple. simplex_params (array): Parameters of the current simplex simplex_costs (array): Costs associated with the parameters of the current simplex - + ''' - def __init__(self, - initial_simplex_corner=None, - initial_simplex_displacements=None, + def __init__(self, + initial_simplex_corner=None, + initial_simplex_displacements=None, initial_simplex_scale=None, **kwargs): - + super(NelderMeadLearner,self).__init__(**kwargs) - + self.num_boundary_hits = 0 self.rho = 1 self.chi = 2 self.psi = 0.5 self.sigma = 0.5 - + if initial_simplex_displacements is None and initial_simplex_scale is None: self.init_simplex_disp = self.diff_boundary * 0.6 self.init_simplex_disp[self.init_simplex_disp==float('inf')] = 1 @@ -368,7 +368,7 @@ def __init__(self, self.init_simplex_disp = np.array(initial_simplex_displacements, dtype=float) else: self.log.error('initial_simplex_displacements and initial_simplex_scale can not both be provided simultaneous.') - + if not self.check_num_params(self.init_simplex_disp): self.log.error('There is the wrong number of elements in the initial simplex displacement:' + repr(self.init_simplex_disp)) raise ValueError @@ -378,7 +378,7 @@ def __init__(self, if not self.check_in_diff_boundary(self.init_simplex_disp): self.log.error('Initial simplex displacements must be within boundaries. init_simplex_disp:'+ repr(self.init_simplex_disp) + '. diff_boundary:' +repr(self.diff_boundary)) raise ValueError - + if initial_simplex_corner is None: diff_roll = (self.diff_boundary - self.init_simplex_disp) * nr.rand(self.num_params) diff_roll[diff_roll==float('+inf')]= 0 @@ -387,42 +387,42 @@ def __init__(self, self.init_simplex_corner += diff_roll else: self.init_simplex_corner = np.array(initial_simplex_corner, dtype=float) - + if not self.check_num_params(self.init_simplex_corner): - self.log.error('There is the wrong number of elements in the initial simplex corner:' + repr(self.init_simplex_corner)) + self.log.error('There is the wrong number of elements in the initial simplex corner:' + repr(self.init_simplex_corner)) if not self.check_in_boundary(self.init_simplex_corner): self.log.error('Initial simplex corner outside of boundaries:' + repr(self.init_simplex_corner)) raise ValueError - + if not np.all(np.isfinite(self.init_simplex_corner + self.init_simplex_disp)): self.log.error('Initial simplex corner and simplex are not finite numbers. init_simplex_corner:'+ repr(self.init_simplex_corner) + '. init_simplex_disp:' +repr(self.init_simplex_disp)) raise ValueError if not self.check_in_boundary(self.init_simplex_corner + self.init_simplex_disp): self.log.error('Largest boundary of simplex not inside the boundaries:' + repr(self.init_simplex_corner + self.init_simplex_disp)) raise ValueError - + self.simplex_params = np.zeros((self.num_params + 1, self.num_params), dtype=float) self.simplex_costs = np.zeros((self.num_params + 1,), dtype=float) - + self.archive_dict.update({'archive_type':'nelder_mead_learner', 'initial_simplex_corner':self.init_simplex_corner, 'initial_simplex_displacements':self.init_simplex_disp}) - + self.log.debug('Nelder-Mead learner init completed.') - + def run(self): ''' - Runs Nelder-Mead algorithm to produce new parameters given costs, until end signal is given. + Runs Nelder-Mead algorithm to produce new parameters given costs, until end signal is given. ''' - + self.log.info('Starting Nelder Mead Learner') - + N = int(self.num_params) - + one2np1 = list(range(1, N + 1)) - + self.simplex_params[0] = self.init_simplex_corner - + try: self.simplex_costs[0] = self.put_params_and_get_cost(self.init_simplex_corner) except ValueError: @@ -431,7 +431,7 @@ def run(self): except LearnerInterrupt: self.log.info('Ended Nelder-Mead before end of simplex') return - + for k in range(0, N): y = np.array(self.init_simplex_corner, copy=True) y[k] = y[k] + self.init_simplex_disp[k] @@ -444,22 +444,22 @@ def run(self): except LearnerInterrupt: self.log.info('Ended Nelder-Mead before end of simplex') return - + self.simplex_costs[k + 1] = f - + ind = np.argsort(self.simplex_costs) self.simplex_costs = np.take(self.simplex_costs, ind, 0) # sort so sim[0,:] has the lowest function value self.simplex_params = np.take(self.simplex_params, ind, 0) - + while not self.end_event.is_set(): - + xbar = np.add.reduce(self.simplex_params[:-1], 0) / N xr = (1 +self.rho) * xbar -self.rho * self.simplex_params[-1] - + if self.check_in_boundary(xr): try: - fxr = self.put_params_and_get_cost(xr) + fxr = self.put_params_and_get_cost(xr) except ValueError: self.log.error('Outside of boundary on first reduce. THIS SHOULD NOT HAPPEN') raise @@ -470,12 +470,12 @@ def run(self): fxr = float('inf') self.num_boundary_hits+=1 self.log.debug('Hit boundary (reflect): '+str(self.num_boundary_hits)+' times.') - + doshrink = 0 - + if fxr < self.simplex_costs[0]: xe = (1 +self.rho *self.chi) * xbar -self.rho *self.chi * self.simplex_params[-1] - + if self.check_in_boundary(xe): try: fxe = self.put_params_and_get_cost(xe) @@ -486,10 +486,10 @@ def run(self): break else: #Hit boundary so set the cost above maximum this ensures the algorithm does a contracting reflection - fxe = fxr+1.0 + fxe = fxr+1.0 self.num_boundary_hits+=1 self.log.debug('Hit boundary (expand): '+str(self.num_boundary_hits)+' times.') - + if fxe < fxr: self.simplex_params[-1] = xe self.simplex_costs[-1] = fxe @@ -541,11 +541,11 @@ def run(self): raise except LearnerInterrupt: break - + ind = np.argsort(self.simplex_costs) self.simplex_params = np.take(self.simplex_params, ind, 0) self.simplex_costs = np.take(self.simplex_costs, ind, 0) - + self._shut_down() self.log.info('Ended Nelder-Mead') @@ -558,43 +558,43 @@ def update_archive(self): class DifferentialEvolutionLearner(Learner, threading.Thread): ''' - Adaption of the differential evolution algorithm in scipy. - + Adaption of the differential evolution algorithm in scipy. + Args: params_out_queue (queue): Queue for parameters sent to controller. costs_in_queue (queue): Queue for costs for gaussian process. This must be tuple end_event (event): Event to trigger end of learner. - + Keyword Args: first_params (Optional [array]): The first parameters to test. If None will just randomly sample the initial condition. Default None. - trust_region (Optional [float or array]): The trust region defines the maximum distance the learner will travel from the current best set of parameters. If None, the learner will search everywhere. If a float, this number must be between 0 and 1 and defines maximum distance the learner will venture as a percentage of the boundaries. If it is an array, it must have the same size as the number of parameters and the numbers define the maximum absolute distance that can be moved along each direction. + trust_region (Optional [float or array]): The trust region defines the maximum distance the learner will travel from the current best set of parameters. If None, the learner will search everywhere. If a float, this number must be between 0 and 1 and defines maximum distance the learner will venture as a percentage of the boundaries. If it is an array, it must have the same size as the number of parameters and the numbers define the maximum absolute distance that can be moved along each direction. evolution_strategy (Optional [string]): the differential evolution strategy to use, options are 'best1', 'best1', 'rand1' and 'rand2'. The default is 'best2'. population_size (Optional [int]): multiplier proportional to the number of parameters in a generation. The generation population is set to population_size * parameter_num. Default 15. mutation_scale (Optional [tuple]): The mutation scale when picking new points. Otherwise known as differential weight. When provided as a tuple (min,max) a mutation constant is picked randomly in the interval. Default (0.5,1.0). cross_over_probability (Optional [float]): The recombination constand or crossover probability, the probability a new points will be added to the population. restart_tolerance (Optional [float]): when the current population have a spread less than the initial tolerance, namely stdev(curr_pop) < restart_tolerance stdev(init_pop), it is likely the population is now in a minima, and so the search is started again. - + Attributes: has_trust_region (bool): Whether the learner has a trust region. - num_population_members (int): The number of parameters in a generation. + num_population_members (int): The number of parameters in a generation. params_generations (list): History of the parameters generations. A list of all the parameters in the population, for each generation created. costs_generations (list): History of the costs generations. A list of all the costs in the population, for each generation created. init_std (float): The initial standard deviation in costs of the population. Calucalted after sampling (or resampling) the initial population. curr_std (float): The current standard devation in costs of the population. Calculated after sampling each generation. ''' - def __init__(self, + def __init__(self, first_params = None, trust_region = None, - evolution_strategy='best1', + evolution_strategy='best1', population_size=15, - mutation_scale=(0.5, 1), - cross_over_probability=0.7, - restart_tolerance=0.01, + mutation_scale=(0.5, 1), + cross_over_probability=0.7, + restart_tolerance=0.01, **kwargs): - + super(DifferentialEvolutionLearner,self).__init__(**kwargs) - + if first_params is None: self.first_params = float('nan') else: @@ -605,9 +605,9 @@ def __init__(self, if not self.check_in_boundary(self.first_params): self.log.error('first_params is not in the boundary:' + repr(self.first_params)) raise ValueError - + self._set_trust_region(trust_region) - + if evolution_strategy == 'best1': self.mutation_func = self._best1 elif evolution_strategy == 'best2': @@ -619,7 +619,7 @@ def __init__(self, else: self.log.error('Please select a valid mutation strategy') raise ValueError - + self.evolution_strategy = evolution_strategy self.restart_tolerance = restart_tolerance @@ -628,29 +628,29 @@ def __init__(self, else: self.log.error('Mutation scale must be a tuple with (min,max) between 0 and 2. mutation_scale:' + repr(mutation_scale)) raise ValueError - + if cross_over_probability <= 1 and cross_over_probability >= 0: self.cross_over_probability = cross_over_probability else: self.log.error('Cross over probability must be between 0 and 1. cross_over_probability:' + repr(cross_over_probability)) - + if population_size >= 5: self.population_size = population_size else: self.log.error('Population size must be greater or equal to 5:' + repr(population_size)) - + self.num_population_members = self.population_size * self.num_params - + self.first_sample = True - + self.params_generations = [] self.costs_generations = [] self.generation_count = 0 - + self.min_index = 0 self.init_std = 0 self.curr_std = 0 - + self.archive_dict.update({'archive_type':'differential_evolution', 'evolution_strategy':self.evolution_strategy, 'mutation_scale':self.mutation_scale, @@ -661,26 +661,26 @@ def __init__(self, 'first_params':self.first_params, 'has_trust_region':self.has_trust_region, 'trust_region':self.trust_region}) - - + + def run(self): ''' Runs the Differential Evolution Learner. ''' try: - + self.generate_population() - + while not self.end_event.is_set(): - + self.next_generation() - + if self.curr_std < self.restart_tolerance * self.init_std: self.generate_population() - + except LearnerInterrupt: return - + def save_generation(self): ''' Save history of generations. @@ -688,29 +688,29 @@ def save_generation(self): self.params_generations.append(np.copy(self.population)) self.costs_generations.append(np.copy(self.population_costs)) self.generation_count += 1 - + def generate_population(self): ''' Sample a new random set of variables ''' - + self.population = [] self.population_costs = [] self.min_index = 0 - + if np.all(np.isfinite(self.first_params)) and self.first_sample: curr_params = self.first_params self.first_sample = False else: curr_params = self.min_boundary + nr.rand(self.num_params) * self.diff_boundary - + curr_cost = self.put_params_and_get_cost(curr_params) - + self.population.append(curr_params) self.population_costs.append(curr_cost) - + for index in range(1, self.num_population_members): - + if self.has_trust_region: temp_min = np.maximum(self.min_boundary,self.population[self.min_index] - self.trust_region) temp_max = np.minimum(self.max_boundary,self.population[self.min_index] + self.trust_region) @@ -719,76 +719,76 @@ def generate_population(self): curr_params = self.min_boundary + nr.rand(self.num_params) * self.diff_boundary curr_cost = self.put_params_and_get_cost(curr_params) - + self.population.append(curr_params) self.population_costs.append(curr_cost) - + if curr_cost < self.population_costs[self.min_index]: self.min_index = index - + self.population = np.array(self.population) self.population_costs = np.array(self.population_costs) - + self.init_std = np.std(self.population_costs) self.curr_std = self.init_std - + self.save_generation() - + def next_generation(self): ''' Evolve the population by a single generation ''' - + self.curr_scale = nr.uniform(self.mutation_scale[0], self.mutation_scale[1]) - + for index in range(self.num_population_members): - + curr_params = self.mutate(index) curr_cost = self.put_params_and_get_cost(curr_params) - + if curr_cost < self.population_costs[index]: self.population[index] = curr_params self.population_costs[index] = curr_cost - + if curr_cost < self.population_costs[self.min_index]: self.min_index = index - + self.curr_std = np.std(self.population_costs) - + self.save_generation() def mutate(self, index): ''' Mutate the parameters at index. - + Args: index (int): Index of the point to be mutated. ''' - + fill_point = nr.randint(0, self.num_params) candidate_params = self.mutation_func(index) crossovers = nr.rand(self.num_params) < self.cross_over_probability crossovers[fill_point] = True mutated_params = np.where(crossovers, candidate_params, self.population[index]) - + if self.has_trust_region: temp_min = np.maximum(self.min_boundary,self.population[self.min_index] - self.trust_region) temp_max = np.minimum(self.max_boundary,self.population[self.min_index] + self.trust_region) rand_params = temp_min + nr.rand(self.num_params) * (temp_max - temp_min) else: rand_params = self.min_boundary + nr.rand(self.num_params) * self.diff_boundary - + projected_params = np.where(np.logical_or(mutated_params < self.min_boundary, mutated_params > self.max_boundary), rand_params, mutated_params) - + return projected_params def _best1(self, index): ''' Use best parameters and two others to generate mutation. - + Args: - index (int): Index of member to mutate. + index (int): Index of member to mutate. ''' r0, r1 = self.random_index_sample(index, 2) return (self.population[self.min_index] + self.curr_scale *(self.population[r0] - self.population[r1])) @@ -796,9 +796,9 @@ def _best1(self, index): def _rand1(self, index): ''' Use three random parameters to generate mutation. - + Args: - index (int): Index of member to mutate. + index (int): Index of member to mutate. ''' r0, r1, r2 = self.random_index_sample(index, 3) return (self.population[r0] + self.curr_scale * (self.population[r1] - self.population[r2])) @@ -806,9 +806,9 @@ def _rand1(self, index): def _best2(self, index): ''' Use best parameters and four others to generate mutation. - + Args: - index (int): Index of member to mutate. + index (int): Index of member to mutate. ''' r0, r1, r2, r3 = self.random_index_sample(index, 4) return self.population[self.min_index] + self.curr_scale * (self.population[r0] + self.population[r1] - self.population[r2] - self.population[r3]) @@ -816,9 +816,9 @@ def _best2(self, index): def _rand2(self, index): ''' Use five random parameters to generate mutation. - + Args: - index (int): Index of member to mutate. + index (int): Index of member to mutate. ''' r0, r1, r2, r3, r4 = self.random_index_sample(index, 5) return self.population[r0] + self.curr_scale * (self.population[r1] + self.population[r2] - self.population[r3] - self.population[r4]) @@ -826,7 +826,7 @@ def _rand2(self, index): def random_index_sample(self, index, num_picks): ''' Randomly select a num_picks of indexes, without index. - + Args: index(int): The index that is not included num_picks(int): The number of picks. @@ -834,7 +834,7 @@ def random_index_sample(self, index, num_picks): rand_indexes = list(range(self.num_population_members)) rand_indexes.remove(index) return random.sample(rand_indexes, num_picks) - + def update_archive(self): ''' Update the archive. @@ -850,49 +850,49 @@ def update_archive(self): class GaussianProcessLearner(Learner, mp.Process): ''' - Gaussian process learner. Generats new parameters based on a gaussian process fitted to all previous data. - + Gaussian process learner. Generats new parameters based on a gaussian process fitted to all previous data. + Args: params_out_queue (queue): Queue for parameters sent to controller. costs_in_queue (queue): Queue for costs for gaussian process. This must be tuple end_event (event): Event to trigger end of learner. - + Keyword Args: length_scale (Optional [array]): The initial guess for length scale(s) of the gaussian process. The array can either of size one or the number of parameters or None. If it is size one, it is assumed all the correlation lengths are the same. If it is the number of the parameters then all the parameters have their own independent length scale. If it is None, it is assumed all the length scales should be independent and they are all given an initial value of 1. Default None. - cost_has_noise (Optional [bool]): If true the learner assumes there is common additive white noise that corrupts the costs provided. This noise is assumed to be on top of the uncertainty in the costs (if it is provided). If false, it is assumed that there is no noise in the cost (or if uncertainties are provided no extra noise beyond the uncertainty). Default True. + cost_has_noise (Optional [bool]): If true the learner assumes there is common additive white noise that corrupts the costs provided. This noise is assumed to be on top of the uncertainty in the costs (if it is provided). If false, it is assumed that there is no noise in the cost (or if uncertainties are provided no extra noise beyond the uncertainty). Default True. noise_level (Optional [float]): The initial guess for the noise level in the costs, is only used if cost_has_noise is true. Default 1.0. update_hyperparameters (Optional [bool]): Whether the length scales and noise estimate should be updated when new data is provided. Is set to true by default. - trust_region (Optional [float or array]): The trust region defines the maximum distance the learner will travel from the current best set of parameters. If None, the learner will search everywhere. If a float, this number must be between 0 and 1 and defines maximum distance the learner will venture as a percentage of the boundaries. If it is an array, it must have the same size as the number of parameters and the numbers define the maximum absolute distance that can be moved along each direction. + trust_region (Optional [float or array]): The trust region defines the maximum distance the learner will travel from the current best set of parameters. If None, the learner will search everywhere. If a float, this number must be between 0 and 1 and defines maximum distance the learner will venture as a percentage of the boundaries. If it is an array, it must have the same size as the number of parameters and the numbers define the maximum absolute distance that can be moved along each direction. default_bad_cost (Optional [float]): If a run is reported as bad and default_bad_cost is provided, the cost for the bad run is set to this default value. If default_bad_cost is None, then the worst cost received is set to all the bad runs. Default None. default_bad_uncertainty (Optional [float]): If a run is reported as bad and default_bad_uncertainty is provided, the uncertainty for the bad run is set to this default value. If default_bad_uncertainty is None, then the uncertainty is set to a tenth of the best to worst cost range. Default None. minimum_uncertainty (Optional [float]): The minimum uncertainty associated with provided costs. Must be above zero to avoid fitting errors. Default 1e-8. predict_global_minima_at_end (Optional [bool]): If True finds the global minima when the learner is ended. Does not if False. Default True. predict_local_minima_at_end (Optional [bool]): If True finds the all minima when the learner is ended. Does not if False. Default False. - + Attributes: all_params (array): Array containing all parameters sent to learner. all_costs (array): Array containing all costs sent to learner. all_uncers (array): Array containing all uncertainties sent to learner. - scaled_costs (array): Array contaning all the costs scaled to have zero mean and a standard deviation of 1. Needed for training the gaussian process. + scaled_costs (array): Array contaning all the costs scaled to have zero mean and a standard deviation of 1. Needed for training the gaussian process. bad_run_indexs (list): list of indexes to all runs that were marked as bad. best_cost (float): Minimum received cost, updated during execution. best_params (array): Parameters of best run. (reference to element in params array). - best_index (int): index of the best cost and params. + best_index (int): index of the best cost and params. worst_cost (float): Maximum received cost, updated during execution. worst_index (int): index to run with worst cost. cost_range (float): Difference between worst_cost and best_cost generation_num (int): Number of sets of parameters to generate each generation. Set to 5. length_scale_history (list): List of length scales found after each fit. - noise_level_history (list): List of noise levels found after each fit. + noise_level_history (list): List of noise levels found after each fit. fit_count (int): Counter for the number of times the gaussian process has been fit. cost_count (int): Counter for the number of costs, parameters and uncertainties added to learner. - params_count (int): Counter for the number of parameters asked to be evaluated by the learner. + params_count (int): Counter for the number of parameters asked to be evaluated by the learner. gaussian_process (GaussianProcessRegressor): Gaussian process that is fitted to data and used to make predictions - cost_scaler (StandardScaler): Scaler used to normalize the provided costs. - has_trust_region (bool): Whether the learner has a trust region. - ''' - - def __init__(self, + cost_scaler (StandardScaler): Scaler used to normalize the provided costs. + has_trust_region (bool): Whether the learner has a trust region. + ''' + + def __init__(self, length_scale = None, update_hyperparameters = True, cost_has_noise=True, @@ -906,40 +906,40 @@ def __init__(self, predict_global_minima_at_end = True, predict_local_minima_at_end = False, **kwargs): - + if gp_training_filename is not None: - + gp_training_filename = str(gp_training_filename) gp_training_file_type = str(gp_training_file_type) if not mlu.check_file_type_supported(gp_training_file_type): self.log.error('GP training file type not supported' + repr(gp_training_file_type)) - + self.training_dict = mlu.get_dict_from_file(gp_training_filename, gp_training_file_type) - + #Basic optimization settings num_params = int(self.training_dict['num_params']) min_boundary = np.squeeze(np.array(self.training_dict['min_boundary'], dtype=float)) max_boundary = np.squeeze(np.array(self.training_dict['max_boundary'], dtype=float)) - + #Configuration of the learner self.cost_has_noise = bool(self.training_dict['cost_has_noise']) self.length_scale = np.squeeze(np.array(self.training_dict['length_scale'])) self.length_scale_history = list(self.training_dict['length_scale_history']) self.noise_level = float(self.training_dict['noise_level']) self.noise_level_history = mlu.safe_cast_to_list(self.training_dict['noise_level_history']) - + #Counters self.costs_count = int(self.training_dict['costs_count']) self.fit_count = int(self.training_dict['fit_count']) self.params_count = int(self.training_dict['params_count']) - + #Data from previous experiment self.all_params = np.array(self.training_dict['all_params'], dtype=float) self.all_costs = np.squeeze(np.array(self.training_dict['all_costs'], dtype=float)) self.all_uncers = np.squeeze(np.array(self.training_dict['all_uncers'], dtype=float)) - - self.bad_run_indexs = mlu.safe_cast_to_list(self.training_dict['bad_run_indexs']) - + + self.bad_run_indexs = mlu.safe_cast_to_list(self.training_dict['bad_run_indexs']) + #Derived properties self.best_cost = float(self.training_dict['best_cost']) self.best_params = np.squeeze(np.array(self.training_dict['best_params'], dtype=float)) @@ -956,7 +956,7 @@ def __init__(self, self.has_global_minima = False try: self.local_minima_parameters = list(self.training_dict['local_minima_parameters']) - + if isinstance(self.training_dict['local_minima_costs'], np.ndarray): self.local_minima_costs = list(np.squeeze(self.training_dict['local_minima_costs'])) else: @@ -965,21 +965,21 @@ def __init__(self, self.local_minima_uncers = list(np.squeeze(self.training_dict['local_minima_uncers'])) else: self.local_minima_uncers = list(self.training_dict['local_minima_uncers']) - + self.has_local_minima = True except KeyError: self.has_local_minima = False - - + + super(GaussianProcessLearner,self).__init__(num_params=num_params, - min_boundary=min_boundary, - max_boundary=max_boundary, + min_boundary=min_boundary, + max_boundary=max_boundary, **kwargs) - + else: - + super(GaussianProcessLearner,self).__init__(**kwargs) - + #Storage variables, archived self.all_params = np.array([], dtype=float) self.all_costs = np.array([], dtype=float) @@ -993,14 +993,14 @@ def __init__(self, self.cost_range = float('inf') self.length_scale_history = [] self.noise_level_history = [] - + self.costs_count = 0 self.fit_count = 0 self.params_count = 0 - + self.has_local_minima = False self.has_global_minima = False - + #Optional user set variables if length_scale is None: self.length_scale = np.ones((self.num_params,)) @@ -1008,32 +1008,32 @@ def __init__(self, self.length_scale = np.array(length_scale, dtype=float) self.noise_level = float(noise_level) self.cost_has_noise = bool(cost_has_noise) - - + + #Multiprocessor controls self.new_params_event = mp.Event() - + #Storage variables and counters self.search_params = [] self.scaled_costs = None self.cost_bias = None self.uncer_bias = None - + #Internal variable for bias function self.bias_func_cycle = 4 - self.bias_func_cost_factor = [1.0,1.0,1.0,1.0] + self.bias_func_cost_factor = [1.0,1.0,1.0,1.0] self.bias_func_uncer_factor =[0.0,1.0,2.0,3.0] self.generation_num = self.bias_func_cycle if self.generation_num < 3: self.log.error('Number in generation must be larger than 2.') raise ValueError - + #Constants, limits and tolerances self.search_precision = 1.0e-6 self.parameter_searches = max(10,self.num_params) self.hyperparameter_searches = max(10,self.num_params) - self.bad_uncer_frac = 0.1 #Fraction of cost range to set a bad run uncertainty - + self.bad_uncer_frac = 0.1 #Fraction of cost range to set a bad run uncertainty + #Optional user set variables self.update_hyperparameters = bool(update_hyperparameters) self.predict_global_minima_at_end = bool(predict_global_minima_at_end) @@ -1048,7 +1048,7 @@ def __init__(self, self.default_bad_uncertainty = None self.minimum_uncertainty = float(minimum_uncertainty) self._set_trust_region(trust_region) - + #Checks of variables if self.length_scale.size == 1: self.length_scale = float(self.length_scale) @@ -1075,17 +1075,17 @@ def __init__(self, if self.minimum_uncertainty <= 0: self.log.error('Minimum uncertainty must be larger than zero for the learner.') raise ValueError - + self.create_gaussian_process() - + #Search bounds self.search_min = self.min_boundary self.search_max = self.max_boundary self.search_diff = self.search_max - self.search_min self.search_region = list(zip(self.search_min, self.search_max)) - + self.cost_scaler = skp.StandardScaler() - + self.archive_dict.update({'archive_type':'gaussian_process_learner', 'cost_has_noise':self.cost_has_noise, 'length_scale_history':self.length_scale_history, @@ -1103,11 +1103,11 @@ def __init__(self, 'has_trust_region':self.has_trust_region, 'predict_global_minima_at_end':self.predict_global_minima_at_end, 'predict_local_minima_at_end':self.predict_local_minima_at_end}) - + #Remove logger so gaussian process can be safely picked for multiprocessing on Windows self.log = None - - + + def create_gaussian_process(self): ''' Create the initial Gaussian process. @@ -1120,10 +1120,10 @@ def create_gaussian_process(self): self.gaussian_process = skg.GaussianProcessRegressor(kernel=gp_kernel,n_restarts_optimizer=self.hyperparameter_searches) else: self.gaussian_process = skg.GaussianProcessRegressor(kernel=gp_kernel,optimizer=None) - + def wait_for_new_params_event(self): ''' - Waits for a new parameters event and starts a new parameter generation cycle. Also checks end event and will break if it is triggered. + Waits for a new parameters event and starts a new parameter generation cycle. Also checks end event and will break if it is triggered. ''' while not self.end_event.is_set(): if self.new_params_event.wait(timeout=self.learner_wait): @@ -1134,26 +1134,26 @@ def wait_for_new_params_event(self): else: self.log.debug('GaussianProcessLearner end signal received. Ending') raise LearnerInterrupt - - + + def get_params_and_costs(self): ''' - Get the parameters and costs from the queue and place in their appropriate all_[type] arrays. Also updates bad costs, best parameters, and search boundaries given trust region. + Get the parameters and costs from the queue and place in their appropriate all_[type] arrays. Also updates bad costs, best parameters, and search boundaries given trust region. ''' if self.costs_in_queue.empty(): self.log.error('Gaussian process asked for new parameters but no new costs were provided.') raise ValueError - + new_params = [] new_costs = [] new_uncers = [] new_bads = [] update_bads_flag = False - + while not self.costs_in_queue.empty(): (param, cost, uncer, bad) = self.costs_in_queue.get_nowait() self.costs_count +=1 - + if bad: new_bads.append(self.costs_count-1) if self.bad_defaults_set: @@ -1162,7 +1162,7 @@ def get_params_and_costs(self): else: cost = self.worst_cost uncer = self.cost_range*self.bad_uncer_frac - + param = np.array(param, dtype=float) if not self.check_num_params(param): self.log.error('Incorrect number of parameters provided to Gaussian process learner:' + repr(param) + '. Number of parameters:' + str(self.num_params)) @@ -1173,7 +1173,7 @@ def get_params_and_costs(self): if uncer < 0: self.log.error('Provided uncertainty must be larger or equal to zero:' + repr(uncer)) uncer = max(float(uncer), self.minimum_uncertainty) - + cost_change_flag = False if cost > self.worst_cost: self.worst_cost = cost @@ -1188,12 +1188,12 @@ def get_params_and_costs(self): self.cost_range = self.worst_cost - self.best_cost if not self.bad_defaults_set: update_bads_flag = True - + new_params.append(param) new_costs.append(cost) new_uncers.append(uncer) - - + + if self.all_params.size==0: self.all_params = np.array(new_params, dtype=float) self.all_costs = np.array(new_costs, dtype=float) @@ -1202,21 +1202,21 @@ def get_params_and_costs(self): self.all_params = np.concatenate((self.all_params, np.array(new_params, dtype=float))) self.all_costs = np.concatenate((self.all_costs, np.array(new_costs, dtype=float))) self.all_uncers = np.concatenate((self.all_uncers, np.array(new_uncers, dtype=float))) - + self.bad_run_indexs.append(new_bads) - + if self.all_params.shape != (self.costs_count,self.num_params): self.log('Saved GP params are the wrong size. THIS SHOULD NOT HAPPEN:' + repr(self.all_params)) if self.all_costs.shape != (self.costs_count,): self.log('Saved GP costs are the wrong size. THIS SHOULD NOT HAPPEN:' + repr(self.all_costs)) if self.all_uncers.shape != (self.costs_count,): self.log('Saved GP uncertainties are the wrong size. THIS SHOULD NOT HAPPEN:' + repr(self.all_uncers)) - + if update_bads_flag: self.update_bads() - + self.update_search_region() - + def update_bads(self): ''' Best and/or worst costs have changed, update the values associated with bad runs accordingly. @@ -1224,7 +1224,7 @@ def update_bads(self): for index in self.bad_run_indexs: self.all_costs[index] = self.worst_cost self.all_uncers[index] = self.cost_range*self.bad_uncer_frac - + def update_search_region(self): ''' If trust boundaries is not none, updates the search boundaries based on the defined trust region. @@ -1234,7 +1234,7 @@ def update_search_region(self): self.search_max = np.minimum(self.best_params + self.trust_region, self.max_boundary) self.search_diff = self.search_max - self.search_min self.search_region = list(zip(self.search_min, self.search_max)) - + def update_search_params(self): ''' Update the list of parameters to use for the next search. @@ -1243,7 +1243,7 @@ def update_search_params(self): self.search_params.append(self.best_params) for _ in range(self.parameter_searches): self.search_params.append(self.search_min + nr.uniform(size=self.num_params) * self.search_diff) - + def update_archive(self): ''' Update the archive. @@ -1262,10 +1262,10 @@ def update_archive(self): 'params_count':self.params_count, 'update_hyperparameters':self.update_hyperparameters, 'length_scale':self.length_scale, - 'noise_level':self.noise_level}) - + 'noise_level':self.noise_level}) + + - def fit_gaussian_process(self): ''' Fit the Gaussian process to the current data @@ -1278,14 +1278,14 @@ def fit_gaussian_process(self): self.scaled_uncers = self.all_uncers * self.cost_scaler.scale_ self.gaussian_process.alpha_ = self.scaled_uncers self.gaussian_process.fit(self.all_params,self.scaled_costs) - + if self.update_hyperparameters: - + self.fit_count += 1 self.gaussian_process.kernel = self.gaussian_process.kernel_ - + last_hyperparameters = self.gaussian_process.kernel.get_params() - + if self.cost_has_noise: self.length_scale = last_hyperparameters['k1__length_scale'] if isinstance(self.length_scale, float): @@ -1296,30 +1296,30 @@ def fit_gaussian_process(self): else: self.length_scale = last_hyperparameters['length_scale'] self.length_scale_history.append(self.length_scale) - - + + def update_bias_function(self): ''' Set the constants for the cost bias function. ''' self.cost_bias = self.bias_func_cost_factor[self.params_count%self.bias_func_cycle] self.uncer_bias = self.bias_func_uncer_factor[self.params_count%self.bias_func_cycle] - + def predict_biased_cost(self,params): ''' Predicts the biased cost at the given parameters. The bias function is: biased_cost = cost_bias*pred_cost - uncer_bias*pred_uncer - + Returns: pred_bias_cost (float): Biased cost predicted at the given parameters ''' (pred_cost, pred_uncer) = self.gaussian_process.predict(params[np.newaxis,:], return_std=True) return self.cost_bias*pred_cost - self.uncer_bias*pred_uncer - + def find_next_parameters(self): ''' Returns next parameters to find. Increments counters and bias function appropriately. - + Return: next_params (array): Returns next parameters from biased cost search. ''' @@ -1334,7 +1334,7 @@ def find_next_parameters(self): next_params = result.x next_cost = result.fun return next_params - + def run(self): ''' Starts running the Gaussian process learner. When the new parameters event is triggered, reads the cost information provided and updates the Gaussian process with the information. Then searches the Gaussian process for new optimal parameters to test based on the biased cost. Parameters to test next are put on the output parameters queue. @@ -1342,7 +1342,7 @@ def run(self): #logging to the main log file from a process (as apposed to a thread) in cpython is currently buggy on windows and/or python 2.7 #current solution is to only log to the console for warning and above from a process self.log = mp.log_to_stderr(logging.WARNING) - + try: while not self.end_event.is_set(): #self.log.debug('Learner waiting for new params event') @@ -1376,36 +1376,36 @@ def run(self): self.params_out_queue.put(end_dict) self._shut_down() self.log.debug('Ended Gaussian Process Learner') - + def predict_cost(self,params): ''' - Produces a prediction of cost from the gaussian process at params. - + Produces a prediction of cost from the gaussian process at params. + Returns: float : Predicted cost at paramters ''' return self.gaussian_process.predict(params[np.newaxis,:]) - + def find_global_minima(self): ''' Performs a quick search for the predicted global minima from the learner. Does not return any values, but creates the following attributes. - + Attributes: predicted_best_parameters (array): the parameters for the predicted global minima predicted_best_cost (float): the cost at the predicted global minima predicted_best_uncertainty (float): the uncertainty of the predicted global minima ''' self.log.debug('Started search for predicted global minima.') - + self.predicted_best_parameters = None self.predicted_best_scaled_cost = float('inf') self.predicted_best_scaled_uncertainty = None - + search_params = [] search_params.append(self.best_params) for _ in range(self.parameter_searches): search_params.append(self.min_boundary + nr.uniform(size=self.num_params) * self.diff_boundary) - + search_bounds = list(zip(self.min_boundary, self.max_boundary)) for start_params in search_params: result = so.minimize(self.predict_cost, start_params, bounds = search_bounds, tol=self.search_precision) @@ -1415,55 +1415,55 @@ def find_global_minima(self): self.predicted_best_parameters = curr_best_params self.predicted_best_scaled_cost = curr_best_cost self.predicted_best_scaled_uncertainty = curr_best_uncer - + self.predicted_best_cost = self.cost_scaler.inverse_transform(self.predicted_best_scaled_cost) self.predicted_best_uncertainty = self.predicted_best_scaled_uncertainty / self.cost_scaler.scale_ - + self.archive_dict.update({'predicted_best_parameters':self.predicted_best_parameters, 'predicted_best_scaled_cost':self.predicted_best_scaled_cost, 'predicted_best_scaled_uncertainty':self.predicted_best_scaled_uncertainty, 'predicted_best_cost':self.predicted_best_cost, 'predicted_best_uncertainty':self.predicted_best_uncertainty}) - + self.has_global_minima = True - self.log.debug('Predicted global minima found.') - + self.log.debug('Predicted global minima found.') + def find_local_minima(self): ''' - Performs a comprehensive search of the learner for all predicted local minima (and hence the global as well) in the landscape. Note, this can take a very long time. - + Performs a comprehensive search of the learner for all predicted local minima (and hence the global as well) in the landscape. Note, this can take a very long time. + Attributes: local_minima_parameters (list): list of all the parameters for local minima. local_minima_costs (list): list of all the costs at local minima. local_minima_uncers (list): list of all the uncertainties at local minima. - + ''' self.log.info('Searching for all minima.') - + self.minima_tolerance = 10*self.search_precision - + self.number_of_local_minima = 0 self.local_minima_parameters = [] self.local_minima_costs = [] self.local_minima_uncers = [] - + search_bounds = list(zip(self.min_boundary, self.max_boundary)) for start_params in self.all_params: result = so.minimize(self.predict_cost, start_params, bounds = search_bounds, tol=self.search_precision) curr_minima_params = result.x (curr_minima_cost,curr_minima_uncer) = self.gaussian_process.predict(curr_minima_params[np.newaxis,:],return_std=True) - if all( not np.all( np.abs(params - curr_minima_params) < self.minima_tolerance ) for params in self.local_minima_parameters): + if all( not np.all( np.abs(params - curr_minima_params) < self.minima_tolerance ) for params in self.local_minima_parameters): #Non duplicate point so add to the list self.number_of_local_minima += 1 self.local_minima_parameters.append(curr_minima_params) self.local_minima_costs.append(curr_minima_cost) self.local_minima_uncers.append(curr_minima_uncer) - + self.archive_dict.update({'number_of_local_minima':self.number_of_local_minima, 'local_minima_parameters':self.local_minima_parameters, 'local_minima_costs':self.local_minima_costs, 'local_minima_uncers':self.local_minima_uncers}) - + self.has_local_minima = True self.log.info('Search completed') @@ -1471,45 +1471,45 @@ def find_local_minima(self): class NeuralNetLearner(Learner, mp.Process): ''' Shell of Neural Net Learner. - + Args: params_out_queue (queue): Queue for parameters sent to controller. costs_in_queue (queue): Queue for costs for gaussian process. This must be tuple end_event (event): Event to trigger end of learner. - + Keyword Args: length_scale (Optional [array]): The initial guess for length scale(s) of the gaussian process. The array can either of size one or the number of parameters or None. If it is size one, it is assumed all the correlation lengths are the same. If it is the number of the parameters then all the parameters have their own independent length scale. If it is None, it is assumed all the length scales should be independent and they are all given an initial value of 1. Default None. - trust_region (Optional [float or array]): The trust region defines the maximum distance the learner will travel from the current best set of parameters. If None, the learner will search everywhere. If a float, this number must be between 0 and 1 and defines maximum distance the learner will venture as a percentage of the boundaries. If it is an array, it must have the same size as the number of parameters and the numbers define the maximum absolute distance that can be moved along each direction. + trust_region (Optional [float or array]): The trust region defines the maximum distance the learner will travel from the current best set of parameters. If None, the learner will search everywhere. If a float, this number must be between 0 and 1 and defines maximum distance the learner will venture as a percentage of the boundaries. If it is an array, it must have the same size as the number of parameters and the numbers define the maximum absolute distance that can be moved along each direction. default_bad_cost (Optional [float]): If a run is reported as bad and default_bad_cost is provided, the cost for the bad run is set to this default value. If default_bad_cost is None, then the worst cost received is set to all the bad runs. Default None. default_bad_uncertainty (Optional [float]): If a run is reported as bad and default_bad_uncertainty is provided, the uncertainty for the bad run is set to this default value. If default_bad_uncertainty is None, then the uncertainty is set to a tenth of the best to worst cost range. Default None. minimum_uncertainty (Optional [float]): The minimum uncertainty associated with provided costs. Must be above zero to avoid fitting errors. Default 1e-8. predict_global_minima_at_end (Optional [bool]): If True finds the global minima when the learner is ended. Does not if False. Default True. predict_local_minima_at_end (Optional [bool]): If True finds the all minima when the learner is ended. Does not if False. Default False. - + Attributes: all_params (array): Array containing all parameters sent to learner. all_costs (array): Array containing all costs sent to learner. all_uncers (array): Array containing all uncertainties sent to learner. - scaled_costs (array): Array contaning all the costs scaled to have zero mean and a standard deviation of 1. Needed for training the gaussian process. + scaled_costs (array): Array contaning all the costs scaled to have zero mean and a standard deviation of 1. Needed for training the gaussian process. bad_run_indexs (list): list of indexes to all runs that were marked as bad. best_cost (float): Minimum received cost, updated during execution. best_params (array): Parameters of best run. (reference to element in params array). - best_index (int): index of the best cost and params. + best_index (int): index of the best cost and params. worst_cost (float): Maximum received cost, updated during execution. worst_index (int): index to run with worst cost. cost_range (float): Difference between worst_cost and best_cost generation_num (int): Number of sets of parameters to generate each generation. Set to 5. length_scale_history (list): List of length scales found after each fit. - noise_level_history (list): List of noise levels found after each fit. + noise_level_history (list): List of noise levels found after each fit. fit_count (int): Counter for the number of times the gaussian process has been fit. cost_count (int): Counter for the number of costs, parameters and uncertainties added to learner. - params_count (int): Counter for the number of parameters asked to be evaluated by the learner. + params_count (int): Counter for the number of parameters asked to be evaluated by the learner. gaussian_process (GaussianProcessRegressor): Gaussian process that is fitted to data and used to make predictions - cost_scaler (StandardScaler): Scaler used to normalize the provided costs. - has_trust_region (bool): Whether the learner has a trust region. - ''' - - def __init__(self, + cost_scaler (StandardScaler): Scaler used to normalize the provided costs. + has_trust_region (bool): Whether the learner has a trust region. + ''' + + def __init__(self, update_hyperparameters = True, trust_region=None, default_bad_cost = None, @@ -1519,11 +1519,11 @@ def __init__(self, predict_global_minima_at_end = True, predict_local_minima_at_end = False, **kwargs): - - - + + + super(NeuralNetLearner,self).__init__(**kwargs) - + #Storage variables, archived self.all_params = np.array([], dtype=float) self.all_costs = np.array([], dtype=float) @@ -1537,29 +1537,29 @@ def __init__(self, self.cost_range = float('inf') self.length_scale_history = [] self.noise_level_history = [] - + self.costs_count = 0 self.fit_count = 0 self.params_count = 0 - + self.has_local_minima = False self.has_global_minima = False - + #Multiprocessor controls self.new_params_event = mp.Event() - + #Storage variables and counters self.search_params = [] self.scaled_costs = None self.cost_bias = None self.uncer_bias = None - + #Constants, limits and tolerances self.search_precision = 1.0e-6 self.parameter_searches = max(10,self.num_params) self.hyperparameter_searches = max(10,self.num_params) - self.bad_uncer_frac = 0.1 #Fraction of cost range to set a bad run uncertainty - + self.bad_uncer_frac = 0.1 #Fraction of cost range to set a bad run uncertainty + #Optional user set variables self.update_hyperparameters = bool(update_hyperparameters) self.predict_global_minima_at_end = bool(predict_global_minima_at_end) @@ -1572,30 +1572,30 @@ def __init__(self, self.default_bad_uncertainty = float(default_bad_uncertainty) else: self.default_bad_uncertainty = None - + self._set_trust_region(trust_region) - + #Search bounds self.search_min = self.min_boundary self.search_max = self.max_boundary self.search_diff = self.search_max - self.search_min self.search_region = list(zip(self.search_min, self.search_max)) - + self.cost_scaler = skp.StandardScaler() - - + + #--- FAKE NN CONSTRUCTOR START ---# - + self.length_scale = 1 self.cost_has_noise = True self.noise_level = 1 - + self.create_nerual_net() - - - + + + #--- FAKE NN CONSTRUCTOR END ---# - + self.archive_dict.update({'archive_type':'nerual_net_learner', 'bad_run_indexs':self.bad_run_indexs, 'generation_num':self.generation_num, @@ -1607,54 +1607,54 @@ def __init__(self, 'has_trust_region':self.has_trust_region, 'predict_global_minima_at_end':self.predict_global_minima_at_end, 'predict_local_minima_at_end':self.predict_local_minima_at_end}) - + #Remove logger so gaussian process can be safely picked for multiprocessing on Windows self.log = None - - + + #--- FAKE NN METHODS START ---# - - + + def create_neural_net(self): ''' TO DO: Implement correctly - + Create the nerual net. - + ''' gp_kernel = skk.RBF(length_scale=self.length_scale) + skk.WhiteKernel(noise_level=self.noise_level) - + if self.update_hyperparameters: self.gaussian_process = skg.GaussianProcessRegressor(kernel=gp_kernel,n_restarts_optimizer=self.hyperparameter_searches) else: self.gaussian_process = skg.GaussianProcessRegressor(kernel=gp_kernel,optimizer=None) - + def fit_neural_net(self): ''' TO DO: Implement correctly - - Determine the appropriate number of layers for the NN given the data. - + + Determine the appropriate number of layers for the NN given the data. + Fit the Neural Net with the appropriate topology to the data - + ''' self.log.debug('Fitting Gaussian process.') if self.all_params.size==0 or self.all_costs.size==0 or self.all_uncers.size==0: self.log.error('Asked to fit GP but no data is in all_costs, all_params or all_uncers.') raise ValueError - + self.scaled_costs = self.cost_scaler.fit_transform(self.all_costs[:,np.newaxis])[:,0] self.scaled_uncers = self.all_uncers * self.cost_scaler.scale_ self.gaussian_process.alpha_ = self.scaled_uncers self.gaussian_process.fit(self.all_params,self.scaled_costs) - + if self.update_hyperparameters: - + self.fit_count += 1 self.gaussian_process.kernel = self.gaussian_process.kernel_ - + last_hyperparameters = self.gaussian_process.kernel.get_params() - + if self.cost_has_noise: self.length_scale = last_hyperparameters['k1__length_scale'] if isinstance(self.length_scale, float): @@ -1665,22 +1665,22 @@ def fit_neural_net(self): else: self.length_scale = last_hyperparameters['length_scale'] self.length_scale_history.append(self.length_scale) - + def predict_cost(self,params): ''' - Produces a prediction of cost from the gaussian process at params. - + Produces a prediction of cost from the gaussian process at params. + Returns: float : Predicted cost at paramters ''' return self.gaussian_process.predict(params[np.newaxis,:]) - + #--- FAKE NN CONSTRUCTOR END ---# - + def wait_for_new_params_event(self): ''' - Waits for a new parameters event and starts a new parameter generation cycle. Also checks end event and will break if it is triggered. + Waits for a new parameters event and starts a new parameter generation cycle. Also checks end event and will break if it is triggered. ''' while not self.end_event.is_set(): if self.new_params_event.wait(timeout=self.learner_wait): @@ -1691,26 +1691,26 @@ def wait_for_new_params_event(self): else: self.log.debug('GaussianProcessLearner end signal received. Ending') raise LearnerInterrupt - - + + def get_params_and_costs(self): ''' - Get the parameters and costs from the queue and place in their appropriate all_[type] arrays. Also updates bad costs, best parameters, and search boundaries given trust region. + Get the parameters and costs from the queue and place in their appropriate all_[type] arrays. Also updates bad costs, best parameters, and search boundaries given trust region. ''' if self.costs_in_queue.empty(): self.log.error('Gaussian process asked for new parameters but no new costs were provided.') raise ValueError - + new_params = [] new_costs = [] new_uncers = [] new_bads = [] update_bads_flag = False - + while not self.costs_in_queue.empty(): (param, cost, uncer, bad) = self.costs_in_queue.get_nowait() self.costs_count +=1 - + if bad: new_bads.append(self.costs_count-1) if self.bad_defaults_set: @@ -1719,7 +1719,7 @@ def get_params_and_costs(self): else: cost = self.worst_cost uncer = self.cost_range*self.bad_uncer_frac - + param = np.array(param, dtype=float) if not self.check_num_params(param): self.log.error('Incorrect number of parameters provided to Gaussian process learner:' + repr(param) + '. Number of parameters:' + str(self.num_params)) @@ -1730,7 +1730,7 @@ def get_params_and_costs(self): if uncer < 0: self.log.error('Provided uncertainty must be larger or equal to zero:' + repr(uncer)) uncer = max(float(uncer), self.minimum_uncertainty) - + cost_change_flag = False if cost > self.worst_cost: self.worst_cost = cost @@ -1745,12 +1745,12 @@ def get_params_and_costs(self): self.cost_range = self.worst_cost - self.best_cost if not self.bad_defaults_set: update_bads_flag = True - + new_params.append(param) new_costs.append(cost) new_uncers.append(uncer) - - + + if self.all_params.size==0: self.all_params = np.array(new_params, dtype=float) self.all_costs = np.array(new_costs, dtype=float) @@ -1759,21 +1759,21 @@ def get_params_and_costs(self): self.all_params = np.concatenate((self.all_params, np.array(new_params, dtype=float))) self.all_costs = np.concatenate((self.all_costs, np.array(new_costs, dtype=float))) self.all_uncers = np.concatenate((self.all_uncers, np.array(new_uncers, dtype=float))) - + self.bad_run_indexs.append(new_bads) - + if self.all_params.shape != (self.costs_count,self.num_params): self.log('Saved NN params are the wrong size. THIS SHOULD NOT HAPPEN:' + repr(self.all_params)) if self.all_costs.shape != (self.costs_count,): self.log('Saved NN costs are the wrong size. THIS SHOULD NOT HAPPEN:' + repr(self.all_costs)) if self.all_uncers.shape != (self.costs_count,): self.log('Saved NN uncertainties are the wrong size. THIS SHOULD NOT HAPPEN:' + repr(self.all_uncers)) - + if update_bads_flag: self.update_bads() - + self.update_search_region() - + def update_bads(self): ''' Best and/or worst costs have changed, update the values associated with bad runs accordingly. @@ -1781,7 +1781,7 @@ def update_bads(self): for index in self.bad_run_indexs: self.all_costs[index] = self.worst_cost self.all_uncers[index] = self.cost_range*self.bad_uncer_frac - + def update_search_region(self): ''' If trust boundaries is not none, updates the search boundaries based on the defined trust region. @@ -1791,7 +1791,7 @@ def update_search_region(self): self.search_max = np.minimum(self.best_params + self.trust_region, self.max_boundary) self.search_diff = self.search_max - self.search_min self.search_region = list(zip(self.search_min, self.search_max)) - + def update_search_params(self): ''' Update the list of parameters to use for the next search. @@ -1800,7 +1800,7 @@ def update_search_params(self): self.search_params.append(self.best_params) for _ in range(self.parameter_searches): self.search_params.append(self.search_min + nr.uniform(size=self.num_params) * self.search_diff) - + def update_archive(self): ''' Update the archive. @@ -1817,12 +1817,12 @@ def update_archive(self): 'fit_count':self.fit_count, 'costs_count':self.costs_count, 'params_count':self.params_count, - 'update_hyperparameters':self.update_hyperparameters}) + 'update_hyperparameters':self.update_hyperparameters}) def find_next_parameters(self): ''' Returns next parameters to find. Increments counters and bias function appropriately. - + Return: next_params (array): Returns next parameters from biased cost search. ''' @@ -1837,7 +1837,7 @@ def find_next_parameters(self): next_params = result.x next_cost = result.fun return next_params - + def run(self): ''' Starts running the Gaussian process learner. When the new parameters event is triggered, reads the cost information provided and updates the Gaussian process with the information. Then searches the Gaussian process for new optimal parameters to test based on the biased cost. Parameters to test next are put on the output parameters queue. @@ -1845,7 +1845,7 @@ def run(self): #logging to the main log file from a process (as apposed to a thread) in cpython is currently buggy on windows and/or python 2.7 #current solution is to only log to the console for warning and above from a process self.log = mp.log_to_stderr(logging.WARNING) - + try: while not self.end_event.is_set(): #self.log.debug('Learner waiting for new params event') @@ -1879,27 +1879,27 @@ def run(self): self.params_out_queue.put(end_dict) self._shut_down() self.log.debug('Ended Gaussian Process Learner') - + def find_global_minima(self): ''' Performs a quick search for the predicted global minima from the learner. Does not return any values, but creates the following attributes. - + Attributes: predicted_best_parameters (array): the parameters for the predicted global minima predicted_best_cost (float): the cost at the predicted global minima predicted_best_uncertainty (float): the uncertainty of the predicted global minima ''' self.log.debug('Started search for predicted global minima.') - + self.predicted_best_parameters = None self.predicted_best_scaled_cost = float('inf') self.predicted_best_scaled_uncertainty = None - + search_params = [] search_params.append(self.best_params) for _ in range(self.parameter_searches): search_params.append(self.min_boundary + nr.uniform(size=self.num_params) * self.diff_boundary) - + search_bounds = list(zip(self.min_boundary, self.max_boundary)) for start_params in search_params: result = so.minimize(self.predict_cost, start_params, bounds = search_bounds, tol=self.search_precision) @@ -1909,55 +1909,55 @@ def find_global_minima(self): self.predicted_best_parameters = curr_best_params self.predicted_best_scaled_cost = curr_best_cost self.predicted_best_scaled_uncertainty = curr_best_uncer - + self.predicted_best_cost = self.cost_scaler.inverse_transform(self.predicted_best_scaled_cost) self.predicted_best_uncertainty = self.predicted_best_scaled_uncertainty / self.cost_scaler.scale_ - + self.archive_dict.update({'predicted_best_parameters':self.predicted_best_parameters, 'predicted_best_scaled_cost':self.predicted_best_scaled_cost, 'predicted_best_scaled_uncertainty':self.predicted_best_scaled_uncertainty, 'predicted_best_cost':self.predicted_best_cost, 'predicted_best_uncertainty':self.predicted_best_uncertainty}) - + self.has_global_minima = True - self.log.debug('Predicted global minima found.') - + self.log.debug('Predicted global minima found.') + def find_local_minima(self): ''' - Performs a comprehensive search of the learner for all predicted local minima (and hence the global as well) in the landscape. Note, this can take a very long time. - + Performs a comprehensive search of the learner for all predicted local minima (and hence the global as well) in the landscape. Note, this can take a very long time. + Attributes: local_minima_parameters (list): list of all the parameters for local minima. local_minima_costs (list): list of all the costs at local minima. local_minima_uncers (list): list of all the uncertainties at local minima. - + ''' self.log.info('Searching for all minima.') - + self.minima_tolerance = 10*self.search_precision - + self.number_of_local_minima = 0 self.local_minima_parameters = [] self.local_minima_costs = [] self.local_minima_uncers = [] - + search_bounds = list(zip(self.min_boundary, self.max_boundary)) for start_params in self.all_params: result = so.minimize(self.predict_cost, start_params, bounds = search_bounds, tol=self.search_precision) curr_minima_params = result.x (curr_minima_cost,curr_minima_uncer) = self.gaussian_process.predict(curr_minima_params[np.newaxis,:],return_std=True) - if all( not np.all( np.abs(params - curr_minima_params) < self.minima_tolerance ) for params in self.local_minima_parameters): + if all( not np.all( np.abs(params - curr_minima_params) < self.minima_tolerance ) for params in self.local_minima_parameters): #Non duplicate point so add to the list self.number_of_local_minima += 1 self.local_minima_parameters.append(curr_minima_params) self.local_minima_costs.append(curr_minima_cost) self.local_minima_uncers.append(curr_minima_uncer) - + self.archive_dict.update({'number_of_local_minima':self.number_of_local_minima, 'local_minima_parameters':self.local_minima_parameters, 'local_minima_costs':self.local_minima_costs, 'local_minima_uncers':self.local_minima_uncers}) - + self.has_local_minima = True self.log.info('Search completed')