diff --git a/README.md b/README.md index 9dcfc33..2ba5403 100644 --- a/README.md +++ b/README.md @@ -1,384 +1,394 @@                 ![docs_title_logo](./resources/docs_title_logo.png) # A Hyper-Parameter Optimization Toolbox
+Copyright © German Cancer Research Center (DKFZ), Division of Medical Image Computing (MIC). Please make sure that your usage of this code is in compliance with the code [license](https://github.com/MIC-DKFZ/Hyppopy/blob/master/LICENSE). + ## Project Status [![Documentation Status](https://readthedocs.org/projects/hyppopy/badge/?version=latest)](https://hyppopy.readthedocs.io/en/latest/?badge=latest) [![codecov](https://codecov.io/gh/mic-dkfz/hyppopy/branch/master/graph/badge.svg)](https://codecov.io/gh/mic-dkfz/hyppopy) ## What is Hyppopy? Hyppopy is a python toolbox for blackbox optimization. It's purpose is to offer a unified and easy to use interface to a collection of solver libraries. Currently provided solvers are: * [Hyperopt](http://hyperopt.github.io/hyperopt/) * [Optunity](https://optunity.readthedocs.io/en/latest/user/index.html) * [Optuna](https://optuna.org/) * Quasi-Randomsearch Solver * Randomsearch Solver * Gridsearch Solver [See a solver analysis here: https://github.com/MIC-DKFZ/Hyppopy/blob/master/examples/solver_comparison/HyppopyReport.pdf] ## Installation 1. clone the [Hyppopy](http:\\github.com) project from Github 2. (create a virtual environment), open a console (with your activated virtual env) and go to the hyppopy root folder 3. ```$ pip install -r requirements.txt``` 4. ```$ python setup.py install``` (for normal usage) or ```$ python setup.py develop``` (if you want to join the hyppopy development *hooray*) ## How to use Hyppopy? #### The Hyperparamaterspace Hyppopy defines a common hyperparameterspace description, whatever solver is used. A hyperparameter description includes the following fields: * domain: the domain defines how the solver samples the parameter space, options are: * uniform: samples the data range [a,b] evenly, whereas b>a * normal: samples the data range [a,b] using a normal distribution with mu=a+(b-a)/2, sigma=(b-a)/6, whereas b>a * loguniform: samples the data range [a,b] logarithmic using e^x by sampling the exponent range x=[log(a), log(b)] uniformly, whereas a>0 and b>a * categorical: is used to define a data list * data: in case of categorical domain data is a list, all other domains expect a range [a, b] * type: the parameter data type as string 'int', 'float' or 'str' An exeption must be kept in mind when using the GridsearchSolver. The gridsearch additionally needs a number of samples per domain, which must be set using the field: frequency. #### The HyppopyProject class The HyppopyProject class takes care all settings necessary for the solver and your workflow. To setup a HyppopyProject instance we can use a nested dictionary or the classes memberfunctions respectively. ```python # Import the HyppopyProject class from hyppopy.HyppopyProject import HyppopyProject # Create a nested dict with a section hyperparameter. We define a 2 dimensional # hyperparameter space with a numerical dimension named myNumber of type float and # a uniform sampling. The second dimension is a categorical parameter of type string. config = { "hyperparameter": { "myNumber": { "domain": "uniform", "data": [0, 100], "type": float }, "myOption": { "domain": "categorical", "data": ["a", "b", "c"], "type": str } }} # Create a HyppopyProject instance and pass the config dict to # the constructor. Alternatively one can use set_config method. project = HyppopyProject(config=config) # We can also add hyperparameter using the add_hyperparameter method project = HyppopyProject() project.add_hyperparameter(name="myNumber", domain="uniform", data=[0, 100], dtype=float) project.add_hyperparameter(name="myOption", domain="categorical", data=["a", "b", "c"], dtype=str) ``` Additional settings for the solver or custom parameters can be set either as additional entries in the config dict, or via the methods set_settings or add_setting: ```python from hyppopy.HyppopyProject import HyppopyProject config = { "hyperparameter": { "myNumber": { "domain": "uniform", "data": [0, 100], "type": float }, "myOption": { "domain": "categorical", "data": ["a", "b", "c"], "type": str } }, "max_iterations": 500, "anything_you_want": 42 } project = HyppopyProject(config=config) print("max_iterations:", project.max_iterations) print("anything_you_want:", project.anything_you_want) #alternatively project = HyppopyProject() project.set_settings(max_iterations=500, anything_you_want=42) print("anything_you_want:", project.anything_you_want) #alternatively project = HyppopyProject() project.add_setting(name="max_iterations", value=500) project.add_setting(name="anything_you_want", value=42) print("anything_you_want:", project.anything_you_want) ``` #### The HyppopySolver classes Each solver is a child of the HyppopySolver class. This is only interesting if you're planning to write a new solver, we will discuss this in the section Solver Development. All solvers we can use to optimize our blackbox function are part of the module 'hyppopy.solver'. Below is a list of all solvers available along with their access key in squared brackets. * HyperoptSolver [hyperopt] _Bayes Optimization use Tree-Parzen Estimator, supports uniform, normal, loguniform and categorical parameter_ * OptunitySolver [optunity] _Particle Swarm Optimizer, supports uniform and categorical parameter_ * OptunaSolver [optuna] _Bayes Optimization, supports uniform, and categorical parameter_ * RandomsearchSolver [randomsearch] _Naive randomized parameter search, supports uniform, normal, loguniform and categorical parameter_ * QuasiRandomsearchSolver [quasirandomsearch] _Randomized grid ensuring random sample drawing and a good space coverage, supports uniform, normal, loguniform and categorical parameter_ * GridsearchSolver [gridsearch] _Standard gridsearch, supports uniform, normal, loguniform and categorical parameter_ There are two options to get a solver, we can import directly from the hyppopy.solvers package or we use the SolverPool class. We look into both options by optimizing a simple function, starting with the direct import case. ```python # Import the HyppopyProject class from hyppopy.HyppopyProject import HyppopyProject # Import the HyperoptSolver class, in this case wh use Hyperopt from hyppopy.solvers.HyperoptSolver import HyperoptSolver # Our function to optimize def my_loss_func(x, y): return x**2+y**2 # Creating a HyppopyProject instance project = HyppopyProject() project.add_hyperparameter(name="x", domain="uniform", data=[-10, 10], type=float) project.add_hyperparameter(name="y", domain="uniform", data=[-10, 10], type=float) project.add_setting(name="max_iterations", value=300) # create a solver instance solver = HyperoptSolver(project) # pass the loss function to the solver solver.blackbox = my_loss_func # run the solver solver.run() df, best = solver.get_results() print("\n") print("*"*100) print("Best Parameter Set:\n{}".format(best)) print("*"*100) ``` The SolverPool is a class keeping track of all solver classes. We have several options to ask the SolverPool for the desired solver. We can add a setting called solver to our config or to the project instance respectively, or we can use the solver access key (see solver listing above) to ask for the solver directly. ```python # import the SolverPool class from hyppopy.SolverPool import SolverPool # Import the HyppopyProject class from hyppopy.HyppopyProject import HyppopyProject # Our function to optimize def my_loss_func(x, y): return x**2+y**2 # Creating a HyppopyProject instance project = HyppopyProject() project.add_hyperparameter(name="x", domain="uniform", data=[-10, 10], type=float) project.add_hyperparameter(name="y", domain="uniform", data=[-10, 10], type=float) project.set_settings(max_iterations=300, solver="hyperopt") # create a solver instance. The SolverPool class is a singleton # and can be used without instanciating. It looks in the project # instance for the use_solver option and returns the correct solver. solver = SolverPool.get(project=project) # Another option without the usage of the solver field would be: # solver = SolverPool.get(solver_name='hyperopt', project=project) # pass the loss function to the solver solver.blackbox = my_loss_func # run the solver solver.run() df, best = solver.get_results() print("\n") print("*"*100) print("Best Parameter Set:\n{}".format(best)) print("*"*100) ``` #### The BlackboxFunction class To extend the possibilities beyond using parameter only loss functions as in the examples above, we can use the BlackboxFunction class. This class is a wrapper class around the actual loss_function providing a more advanced access interface to data handling and a callback_function for accessing the solvers iteration loop. ```python # import the HyppopyProject class keeping track of inputs from hyppopy.HyppopyProject import HyppopyProject # import the SolverPool singleton class from hyppopy.SolverPool import SolverPool # import the Blackboxfunction class wrapping your problem for Hyppopy from hyppopy.BlackboxFunction import BlackboxFunction # Create the HyppopyProject class instance project = HyppopyProject() project.add_hyperparameter(name="C", domain="uniform", data=[0.0001, 20], type=float) project.add_hyperparameter(name="gamma", domain="uniform", data=[0.0001, 20], type=float) project.add_hyperparameter(name="kernel", domain="categorical", data=["linear", "sigmoid", "poly", "rbf"], type=str) project.add_setting(name="max_iterations", value=500) project.add_setting(name="solver", value="optunity") # The BlackboxFunction signature is as follows: # BlackboxFunction(blackbox_func=None, # dataloader_func=None, # preprocess_func=None, # callback_func=None, # data=None, # **kwargs) # # - blackbox_func: a function pointer to the users loss function # - dataloader_func: a function pointer for handling dataloading. The function is called once before # optimizing. What it returns is passed as first argument to your loss functions # data argument. # - preprocess_func: a function pointer for data preprocessing. The function is called once before # optimizing and gets via kwargs['data'] the raw data object set directly or returned # from dataloader_func. What this function returns is then what is passed as first # argument to your loss function. # - callback_func: a function pointer called after each iteration. The input kwargs is a dictionary # keeping the parameters used in this iteration, the 'iteration' index, the 'loss' # and the 'status'. The function in this example is used for realtime printing it's # input but can also be used for realtime visualization. # - data: if not done via dataloader_func one can set a raw_data object directly # - kwargs: dict that whose content is passed to all functions above. from sklearn.svm import SVC from sklearn.datasets import load_iris from sklearn.model_selection import cross_val_score def my_dataloader_function(**kwargs): print("Dataloading...") # kwargs['params'] allows accessing additional parameter passed, # see below my_preproc_param, my_dataloader_input. print("my loading argument: {}".format(kwargs['params']['my_dataloader_input'])) iris_data = load_iris() return [iris_data.data, iris_data.target] def my_preprocess_function(**kwargs): print("Preprocessing...") # kwargs['data'] allows accessing the input data print("data:", kwargs['data'][0].shape, kwargs['data'][1].shape) # kwargs['params'] allows accessing additional parameter passed, # see below my_preproc_param, my_dataloader_input. print("kwargs['params']['my_preproc_param']={}".format(kwargs['params']['my_preproc_param']), "\n") # if the preprocessing function returns something, # the input data will be replaced with the data returned by this function. x = kwargs['data'][0] y = kwargs['data'][1] for i in range(x.shape[0]): x[i, :] += kwargs['params']['my_preproc_param'] return [x, y] def my_callback_function(**kwargs): print("\r{}".format(kwargs), end="") def my_loss_function(data, params): clf = SVC(**params) return -cross_val_score(estimator=clf, X=data[0], y=data[1], cv=3).mean() # We now create the BlackboxFunction object and pass all function pointers defined above, # as well as 2 dummy parameter (my_preproc_param, my_dataloader_input) for demonstration purposes. blackbox = BlackboxFunction(blackbox_func=my_loss_function, dataloader_func=my_dataloader_function, preprocess_func=my_preprocess_function, callback_func=my_callback_function, my_preproc_param=1, my_dataloader_input='could/be/a/path') # Get the solver solver = SolverPool.get(project=project) # Give the solver your blackbox solver.blackbox = blackbox # Run the solver solver.run() # Get your results df, best = solver.get_results() print("\n") print("*"*100) print("Best Parameter Set:\n{}".format(best)) print("*"*100) ``` #### The Parameter Space Domains Each hyperparameter needs a range and a domain specifier. The range, specified via 'data', is the left and right bound of an interval (exception is the domain 'categorical', here 'data' is the actual list of data elements) and the domain specifier the way this interval is sampled. Currently supported domains are: * uniform (samples the interval [a,b] evenly) * normal* (a gaussian sampling of the interval [a,b] such that mu=a+(b-a)/2 and sigma=(b-a)/6) * loguniform* (a logaritmic sampling of the iterval [a,b], such that the exponent e^x is sampled evenly x=[log(a),log(b)]) * categorical (in this case data is not interpreted as interval but as actual list of objects) *Not all domains are supported by all solvers, this might be fixed in the future, but until, the solver throws an error telling you that the domain is unknown. When using the GridsearchSolver we need to specifiy an interval and a number of samples using a frequency specifier. The max_iterations parameter is obsolet in this case, because each axis specifies an individual number of samples via frequency. This applies only to numerical space domains, categorical space domains need a frequency value of 1. ```python # import the SolverPool class from hyppopy.solvers.GridsearchSolver import GridsearchSolver # Import the HyppopyProject class from hyppopy.HyppopyProject import HyppopyProject # Our function to optimize def my_loss_func(x, y): return x**2+y**2 # Creating a HyppopyProject instance project = HyppopyProject() project.add_hyperparameter(name="x", domain="uniform", data=[-1.1, 1], frequency=10, type=float) project.add_hyperparameter(name="y", domain="uniform", data=[-1.1, 1], frequency=12, type=float) solver = GridsearchSolver(project=project) # pass the loss function to the solver solver.blackbox = my_loss_func # run the solver solver.run() df, best = solver.get_results() print("\n") print("*"*100) print("Best Parameter Set:\n{}".format(best)) print("*"*100) ``` #### Using a Visdom Server to Visualize the Optimization Process We can simply create a realtime visualization using a visdom server. If installed, start your visdom server via console command: ``` >visdom ``` Go to your browser and open the site: http://localhost:8097 To enable the visualization call the function 'start_viewer' before running the solver: ``` #enable visualization solver.start_viewer() # Run the solver solver.run() ``` You can also change the port and the server name in start_viewer(port=8097, server="http://localhost") ## Acknowledgements: _This work is supported by the [Helmholtz Association Initiative and Networking](https://www.helmholtz.de/en/about_us/the_association/initiating_and_networking/) Fund under project number ZT-I-0003._
+ +### Project overview: +The Helmholtz Analytics Framework (HAF) is a data science pilot project funded by the Helmholtz Initiative and Networking Fund. Six Helmholtz centers will pursue a systematic + development of domain-specific data analysis techniques in a co-design approach between domain scientists and information experts in order to strengthen the development of the + data sciences in the Helmholtz Association. In challenging applications from a variety of scientific fields, data analytics methods will be applied to demonstrate their + potential in leading to scientific breakthroughs and new knowledge. In addition, the exchange of methods among the scientific areas will lead to their generalization. + + Additional information can be found [here.](http://www.helmholtz-analytics.de/helmholtz_analytics/EN/Project/_node.html) \ No newline at end of file diff --git a/doc/developer_guide.rst b/doc/developer_guide.rst index af19150..8cf5825 100644 --- a/doc/developer_guide.rst +++ b/doc/developer_guide.rst @@ -1,169 +1,175 @@ **************** Developers Guide **************** The main classes and their connections ************************************** The picture below depicts the releationships between the most important classes of hyppopy. .. image:: _static/class_diagram.png To understand the concept behind Hyppopy the following classes are important: - :py:mod:`hyppopy.solvers.HyppopySolver` - :py:mod:`hyppopy.HyppopyProject` - :py:mod:`hyppopy.BlackboxFunction` The :py:mod:`hyppopy.solvers.HyppopySolver` class is the parent class of all solvers in Hyppopy. It defines an abstract interface that needs to be implemented by each custom solver class. The main idea is to define a common interface for the different approaches the solver libraries are based on. When designing Hyppopy there were three main challenges that drove the design. Each solver library has a different approach to define or describe the hyperparameter space, has a different approach to track the solver information and is different in setting the blackbox function and running the optimization process. To deal with those differences the :py:mod:`hyppopy.solvers.HyppopySolver` class defines the abstract interface functions `convert_searchspace`, `execute_solver`, `loss_function_call` and `define_interface`. Those serve as abstraction layer to handle the individual needs of each solver library. Each solver needs a :py:mod:`hyppopy.HyppopyProject` instance keeping the user configuration input and a :py:mod:`hyppopy.BlackboxFunction` instance, implementing the loss function. Implementing a custom solver **************************** Adding a new solver is only about deriving a new class from :py:mod:`hyppopy.solvers.HyppopySolver` as well as telling the :py:mod:`hyppopy.SolverPool` that it exists. We go through the whole process on the example of the solver :py:mod:`hyppopy.solvers.OptunitySolver`: .. code-block:: python import os import optunity from pprint import pformat from hyppopy.solvers.HyppopySolver import HyppopySolver class OptunitySolver(HyppopySolver): def __init__(self, project=None): HyppopySolver.__init__(self, project) First step is to derive from the HyppopySolver class. Good practice would be that the project can be set via __init__ -and if, is piped through to the HyppopySolver.__init__. Next step is implementing the abstract interface methods. -We start with define_interface. This functions purpose is to define the relevant input parameter and the signature -of the hyperparameter space. Our solver needs an parameter called max_iterations of type int. The hyperparameter -space has a domain that allows values 'uniform' and 'categorical', a field data of type list and a field type of type -type. This guarantees that exceptions are thrown if the user disrespects this signature or forgets to set max_iterations. +and if, is piped through to the HyppopySolver.__init__. + +Next step is implementing the abstract interface methods. We start with define_interface. This functions purpose is to +define the relevant input parameter and the signature of a hyperparameter description. This means the solver developer +can define what parameter the solver expects as well as how a single hyperparameter must be described. The rules defined +here are automatically applied when the solver run method is called and exceptions are thrown if there is a mismatch +between these rules and the settings the user sets via it's config. + +Our solver in this example needs an parameter called max_iterations of type int. The hyperparameter space has a domain +that allows values 'uniform' and 'categorical', a field data of type list and a field type of type type. This guarantees +that exceptions are thrown if the user disrespects this signature or forgets to set max_iterations. .. code-block:: python def define_interface(self): self._add_member("max_iterations", int) self._add_hyperparameter_signature(name="domain", dtype=str, options=["uniform", "categorical"]) self._add_hyperparameter_signature(name="data", dtype=list) self._add_hyperparameter_signature(name="type", dtype=type) Next abstract method to implement is convert_searchspace. This method is responsible for interpreting the users hyperparameter input and convert it to a form the solver framework needs. An input for example can be: .. code-block:: python hyperparameter = { 'C': {'domain': 'uniform', 'data': [0.0001, 20], 'type': float}, 'gamma': {'domain': 'uniform', 'data': [0.0001, 20.0], 'type': float}, 'kernel': {'domain': 'categorical', 'data': ['linear', 'sigmoid', 'poly', 'rbf'], 'type': str}, 'decision_function_shape': {'domain': 'categorical', 'data': ['ovo', 'ovr'], 'type': str'} } Optunity instead expects a hyperparameter space formulation as follows: .. code-block:: python optunity_space = {'decision_function_shape': {'ovo': { 'kernel': { 'linear': {'C': [0.0001, 20], 'gamma': [0.0001, 20.0]}, 'sigmoid': {'C': [0.0001, 20], 'gamma': [0.0001, 20.0]}, 'poly': {'C': [0.0001, 20], 'gamma': [0.0001, 20.0]}, 'rbf': {'C': [0.0001, 20], 'gamma': [0.0001, 20.0]}} }, 'ovr': { 'kernel': { 'linear': {'C': [0.0001, 20], 'gamma': [0.0001, 20.0]}, 'sigmoid': {'C': [0.0001, 20], 'gamma': [0.0001, 20.0]}, 'poly': {'C': [0.0001, 20], 'gamma': [0.0001, 20.0]}, 'rbf': {'C': [0.0001, 20], 'gamma': [0.0001, 20.0]}} } }} This conversion is what convert_searchspace is meant for. .. code-block:: python def convert_searchspace(self, hyperparameter): LOG.debug("convert input parameter\n\n\t{}\n".format(pformat(hyperparameter))) # split input in categorical and non-categorical data cat, uni = self.split_categorical(hyperparameter) # build up dictionary keeping all non-categorical data uniforms = {} for key, value in uni.items(): for key2, value2 in value.items(): if key2 == 'data': if len(value2) == 3: uniforms[key] = value2[0:2] elif len(value2) == 2: uniforms[key] = value2 else: raise AssertionError("precondition violation, optunity searchspace needs list with left and right range bounds!") if len(cat) == 0: return uniforms # build nested categorical structure inner_level = uniforms for key, value in cat.items(): tmp = {} optunity_space = {} for key2, value2 in value.items(): if key2 == 'data': for elem in value2: tmp[elem] = inner_level optunity_space[key] = tmp inner_level = optunity_space return optunity_space Now we have defined how the solver looks from outside and how to convert the parameterspace coming in, we can define how the blackbox function is called. The abstract method loss_function_call is a wrapper function enabling to customize the call of the blackbox function. In case of Optunity we only check if a parameter is of type int and convert it to ensure that no exception are thrown in case of integers are expected in the blackbox. .. code-block:: python def loss_function_call(self, params): for key in params.keys(): if self.project.get_typeof(key) is int: params[key] = int(round(params[key])) return self.blackbox(**params) In execute_solver the actual wrapping of the solver framework call is done. Here call the Optunity optimizing function. A dictionary keeping the optimal parameter set must assigned to self.best. .. code-block:: python def execute_solver(self, searchspace): LOG.debug("execute_solver using solution space:\n\n\t{}\n".format(pformat(searchspace))) try: self.best, _, _ = optunity.minimize_structured(f=self.loss_function, num_evals=self.max_iterations, search_space=searchspace) except Exception as e: LOG.error("internal error in optunity.minimize_structured occured. {}".format(e)) raise BrokenPipeError("internal error in optunity.minimize_structured occured. {}".format(e)) diff --git a/hyppopy/BlackboxFunction.py b/hyppopy/BlackboxFunction.py index 32cce46..1e24f40 100644 --- a/hyppopy/BlackboxFunction.py +++ b/hyppopy/BlackboxFunction.py @@ -1,135 +1,182 @@ # Hyppopy - A Hyper-Parameter Optimization Toolbox # # Copyright (c) German Cancer Research Center, # Division of Medical Image Computing. # All rights reserved. # # This software is distributed WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. # # See LICENSE __all__ = ['BlackboxFunction'] import os import logging import functools from hyppopy.globals import DEBUGLEVEL LOG = logging.getLogger(os.path.basename(__file__)) LOG.setLevel(DEBUGLEVEL) def default_kwargs(**defaultKwargs): """ Decorator defining default args in **kwargs arguments """ + def actual_decorator(fn): @functools.wraps(fn) def g(*args, **kwargs): defaultKwargs.update(kwargs) return fn(*args, **defaultKwargs) + return g + return actual_decorator class BlackboxFunction(object): """ This class is a BlackboxFunction wrapper class encapsulating the loss function. Additional function pointer can be set to get access at different pipelining steps: - dataloader_func: data loading, the function must return a data object and is called first when the solver is executed. The data object returned will be the input of the blackbox function. - preprocess_func: data preprocessing is called after dataloader_func, the functions signature must be foo(data, params) and must return a data object. The input is the data object set directly or via dataloader_func, the params are passed from constructor params. - callback_func: this function is called at each iteration step getting passed the trail info content, can be used for custom visualization - data: add a data object directly + + The constructor accepts several function pointers or a data object which are all None by default (see below). + Additionally one can define an arbitrary number of arg pairs. These are passed as input to each function pointer as + arguments. + + :param dataloader_func: data loading function pointer, default=None + :param preprocess_func: data preprocessing function pointer, default=None + :param callback_func: callback function pointer, default=None + :param data: data object, default=None + :param kwargs: additional arg=value pairs """ @default_kwargs(blackbox_func=None, dataloader_func=None, preprocess_func=None, callback_func=None, data=None) def __init__(self, **kwargs): - """ - Constructor accepts function pointer or a data object which are all None by default. Additionally one can define - an arbitrary number of arg pairs. These are passed as input to each function pointer as arguments. - - :param dataloader_func: data loading function pointer, default=None - :param preprocess_func: data preprocessing function pointer, default=None - :param callback_func: callback function pointer, default=None - :param data: data object, default=None - :param kwargs: additional arg=value pairs - """ self._blackbox_func = None self._preprocess_func = None self._dataloader_func = None self._callback_func = None self._raw_data = None self._data = None self.setup(kwargs) def __call__(self, **kwargs): """ Call method calls blackbox_func passing the data object and the args passed :param kwargs: [dict] args :return: blackbox_func(data, kwargs) """ - return self.blackbox_func(self.data, kwargs) + try: + try: + return self.blackbox_func(self.data, kwargs) + except: + return self.blackbox_func(self.data, **kwargs) + except: + try: + return self.blackbox_func(kwargs) + except: + return self.blackbox_func(**kwargs) def setup(self, kwargs): """ Alternative to Constructor, kwargs signature see __init__ :param kwargs: (see __init__) """ self._blackbox_func = kwargs['blackbox_func'] self._preprocess_func = kwargs['preprocess_func'] self._dataloader_func = kwargs['dataloader_func'] self._callback_func = kwargs['callback_func'] self._raw_data = kwargs['data'] self._data = self._raw_data del kwargs['blackbox_func'] del kwargs['preprocess_func'] del kwargs['dataloader_func'] del kwargs['data'] params = kwargs if self.dataloader_func is not None: self._raw_data = self.dataloader_func(params=params) - assert self._raw_data is not None, "Missing data exception!" - assert self.blackbox_func is not None, "Missing blackbox fucntion exception!" + assert self.blackbox_func is not None, "Missing blackbox function exception!" if self.preprocess_func is not None: result = self.preprocess_func(data=self._raw_data, params=params) if result is not None: self._data = result else: self._data = self._raw_data else: self._data = self._raw_data @property def blackbox_func(self): + """ + BlackboxFunction wrapper class encapsulating the loss function or a function accepting a hyperparameter set and + returning a float. + + :return: [object] pointer to blackbox_func + """ return self._blackbox_func @property def preprocess_func(self): + """ + Data preprocessing is called after dataloader_func, the functions signature must be foo(data, params) and must + return a data object. The input is the data object set directly or via dataloader_func, the params are passed + from constructor params. + + :return: [object] preprocess_func + """ return self._preprocess_func @property def dataloader_func(self): + """ + Data loading, the function must return a data object and is called first when the solver is executed. The data + object returned will be the input of the blackbox function. + + :return: [object] dataloader_func + """ return self._dataloader_func @property def callback_func(self): + """ + This function is called at each iteration step getting passed the trail info content, can be used for + custom visualization + + :return: [object] callback_func + """ return self._callback_func @property def raw_data(self): + """ + This data structure is used to store the return from dataloader_func to serve as input for preprocess_func if + available. + + :return: [object] raw_data + """ return self._raw_data @property def data(self): + """ + Datastructure keeping the input data. + + :return: [object] data + """ return self._data diff --git a/hyppopy/CandidateDescriptor.py b/hyppopy/CandidateDescriptor.py new file mode 100644 index 0000000..5db69df --- /dev/null +++ b/hyppopy/CandidateDescriptor.py @@ -0,0 +1,108 @@ +class CandidateDescriptor(object): + """ + Descriptor that defines an candidate the solver wants to be checked. + It is used to lable/identify the candidates and their results in the case of batch processing. + """ + + def __init__(self, **definingValues): + """ + @param definingValues Class assumes that all variables passed to the computer are parameters of the candidate + the instance should represent. + """ + import uuid + + self._definingValues = definingValues + + self._definingStr = str() + + for item in sorted(definingValues.items()): + self._definingStr = self._definingStr + "'" + str(item[0]) + "':'" + str(item[1]) + "'," + + self.ID = str(uuid.uuid4()) + + def __missing__(self, key): + return None + + def __len__(self): + return len(self._definingValues) + + def __contains__(self, key): + return key in self._definingValues + + def __eq__(self, other): + if isinstance(other, self.__class__): + return self._definingValues == other._definingValues + else: + return False + + def __hash__(self): + return hash(self._definingStr) + + def __ne__(self, other): + return not self.__eq__(other) + + def __repr__(self): + return 'EvalInstanceDescriptor(%s)' % (self._definingValues) + + def __str__(self): + return '(%s)' % (self._definingValues) + + def keys(self): + return self._definingValues.keys() + + def __getitem__(self, key): + if key in self._definingValues: + return self._definingValues[key] + raise KeyError('Unkown defining value key was requested. Key: {}; self: {}'.format(key, self)) + + def get_values(self): + return self._definingValues + + +class CandicateDescriptorWrapper: + + class InternalCandidateValueWrapper: + def __init__(self, value_list): + self._value_list = value_list + + def __gt__(self, other): + boundary_condition = True + for value in self._value_list: + if value > other: + continue + else: + boundary_condition = False + break + return boundary_condition + + def __lt__(self, other): + boundary_condition = True + for value in self._value_list: + if value < other: + continue + else: + boundary_condition = False + break + return boundary_condition + + def get(self): + return self._value_list + + def __init__(self, keys): + self._cand = None + self._keys = keys + + def __iter__(self): + return iter(self._cand) + + def __getitem__(self, key): + return self.InternalCandidateValueWrapper([x[key] for x in self._cand]) + + def keys(self): + return self._keys + + def set(self, obj): + self._cand = obj + + def get(self): + return self._cand diff --git a/hyppopy/FunctionSimulator.py b/hyppopy/FunctionSimulator.py index 38174ff..af9b482 100644 --- a/hyppopy/FunctionSimulator.py +++ b/hyppopy/FunctionSimulator.py @@ -1,240 +1,316 @@ # Hyppopy - A Hyper-Parameter Optimization Toolbox # # Copyright (c) German Cancer Research Center, # Division of Medical Image Computing. # All rights reserved. # # This software is distributed WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. # # See LICENSE ######################################################################################################################## # USAGE # # The class FunctionSimulator is meant to be a virtual energy function with an arbitrary dimensionality. The user can # simply scribble functions as a binary image using e.g. Gimp, defining their ranges using .cfg file and loading them # into the FunctionSimulator. An instance of the class can then be used like a normal function returning the sampling of # each dimension loaded. # # 1. create binary images (IMPORTANT same shape for each), background black the function signature white, ensure that # each column has a white pixel. If more than one pixel appears in a column, only the lowest will be used. # # 2. create a .cfg file, see an example in hyppopy/virtualparameterspace # # 3. vfunc = FunctionSimulator() # vfunc.load_images(path/of/your/binaryfiles/and/the/configfile) # # 4. use vfunc like a normal function, if you loaded 4 dimension binary images use it like f = vfunc(a,b,c,d) ######################################################################################################################## __all__ = ['FunctionSimulator'] import os import sys import numpy as np import configparser from glob import glob import matplotlib.pyplot as plt import matplotlib.image as mpimg from hyppopy.globals import FUNCTIONSIMULATOR_DATAPATH class FunctionSimulator(object): """ The FunctionSimulator class serves as simulation tool for solver testing and evaluation purposes. It's designed to simulate an energy functional by setting axis data for each dimension via binary image files. The binary image files are sampled and a range interval is read from a config file. The class implements __call__ to act like a blackbox function when initialized. f=f(x1,x2,...,xn) [for n binary images and n range config files as image input .png grayscale images are expected as range config .cfg ascii files are expected containing """ def __init__(self): + """ + Default constructor + """ self.config = None self.data = None self.axis = [] def __call__(self, *args, **kwargs): """ the call function expects the hyperparameter :param args: :param kwargs: :return: """ if len(kwargs) == self.dims(): args = [0]*len(kwargs) for key, value in kwargs.items(): index = int(key.split("_")[1]) args[index] = value assert len(args) == self.dims(), "wrong number of arguments!" for i in range(len(args)): assert self.axis[i][0] <= args[i] <= self.axis[i][1], "out of range access on axis {}!".format(i) lpos, rpos, fracs = self.pos_to_indices(args) fl = self.data[(list(range(self.dims())), lpos)] fr = self.data[(list(range(self.dims())), rpos)] return np.sum(fl*np.array(fracs) + fr*(1-np.array(fracs))) def clear(self): + """ + Clears all data structures + """ self.axis.clear() self.data = None self.config = None def dims(self): + """ + Returns the dimensions of the data obejct + + :return: [int] shape[0] + """ return self.data.shape[0] def size(self): + """ + Returns the size of the data obejct + + :return: [int] shape[2] + """ return self.data.shape[1] def range(self, dim): + """ + Returns the data range + + :return: [float] range + """ return np.abs(self.axis[dim][1] - self.axis[dim][0]) def minima(self): + """ + computes the minimum for each axis + + :return: [list] minima per axis + """ glob_mins = [] for dim in range(self.dims()): x = [] fmin = np.min(self.data[dim, :]) for _x in range(self.size()): if self.data[dim, _x] <= fmin: x.append(_x/self.size()*(self.axis[dim][1]-self.axis[dim][0])+self.axis[dim][0]) glob_mins.append([x, fmin]) return glob_mins def pos_to_indices(self, positions): + """ + Converts real positions to index + + :param positions: [list] positions + + :return: [list], [list], [list] left, right fraction + """ lpos = [] rpos = [] pfracs = [] for n in range(self.dims()): pos = positions[n] pos -= self.axis[n][0] pos /= np.abs(self.axis[n][1]-self.axis[n][0]) pos *= self.data.shape[1]-1 lp = int(np.floor(pos)) if lp < 0: lp = 0 rp = int(np.ceil(pos)) if rp > self.data.shape[1]-1: rp = self.data.shape[1]-1 pfracs.append(1.0-(pos-np.floor(pos))) lpos.append(lp) rpos.append(rp) return lpos, rpos, pfracs def plot(self, dim=None, title=""): + """ + Plots the dimension. + + :param dim: [int] axis index + :param title: [str] plot title + """ if dim is None: dim = list(range(self.dims())) else: dim = [dim] fig = plt.figure(figsize=(10, 8)) for i in range(len(dim)): width = np.abs(self.axis[dim[i]][1]-self.axis[dim[i]][0]) ax = np.arange(self.axis[dim[i]][0], self.axis[dim[i]][1], width/self.size()) plt.plot(ax, self.data[dim[i], :], '.', label='axis_{}'.format(str(dim[i]).zfill(2))) plt.legend() plt.grid() plt.title(title) plt.show() def add_dimension(self, data, x_range): + """ + Add dimension data + + :param data: [object] axis data + :param x_range: [list] data absolute range + """ if self.data is None: self.data = data if len(self.data.shape) == 1: self.data = self.data.reshape((1, self.data.shape[0])) else: if len(data.shape) == 1: data = data.reshape((1, data.shape[0])) assert self.data.shape[1] == data.shape[1], "shape mismatch while adding dimension!" dims = self.data.shape[0] size = self.data.shape[1] tmp = np.append(self.data, data) self.data = tmp.reshape((dims+1, size)) self.axis.append(x_range) def load_default(self, name="3D"): + """ + load default images as axis + + :param name: [str] subfolder name + """ path = os.path.join(FUNCTIONSIMULATOR_DATAPATH, "{}".format(name)) if os.path.exists(path): self.load_images(path) else: raise FileExistsError("No FunctionSimulator of dimension {} available".format(name)) def load_images(self, path): + """ + Load axis images and config files from path. + + :param path: [str] data path + """ self.config = None self.data = None self.axis.clear() img_fnames = [] for f in glob(path + os.sep + "*"): if f.endswith(".png"): img_fnames.append(f) elif f.endswith(".cfg"): self.config = self.read_config(f) else: print("WARNING: files of type {} not supported, the file {} is ignored!".format(f.split(".")[-1], os.path.basename(f))) if self.config is None: print("Aborted, failed to read configfile!") sys.exit() sections = self.config.sections() if len(sections) != len(img_fnames): print("Aborted, inconsistent number of image tmplates and axis specifications!") sys.exit() img_fnames.sort() size_x = None size_y = None for n, fname in enumerate(img_fnames): img = mpimg.imread(fname) if len(img.shape) > 2: img = img[:, :, 0] if size_x is None: size_x = img.shape[1] if size_y is None: size_y = img.shape[0] self.data = np.zeros((len(img_fnames), size_x), dtype=np.float32) assert img.shape[0] == size_y, "Shape mismatch in dimension y {} is not {}".format(img.shape[0], size_y) assert img.shape[1] == size_x, "Shape mismatch in dimension x {} is not {}".format(img.shape[1], size_x) self.sample_image(img, n) def sample_image(self, img, dim): + """ + Samples an image to extract function value list. + + :param img: [ndarray] image + + :param dim: [int] axis index + """ sec_name = "axis_{}".format(str(dim).zfill(2)) assert sec_name in self.config.sections(), "config section {} not found!".format(sec_name) settings = self.get_axis_settings(sec_name) self.axis.append([float(settings['min_x']), float(settings['max_x'])]) y_range = [float(settings['min_y']), float(settings['max_y'])] for x in range(img.shape[1]): candidates = np.where(img[:, x] > 0) assert len(candidates[0]) > 0, "non function value in image detected, ensure each column has at least one value > 0!" y_pos = candidates[0][0]/img.shape[0] self.data[dim, x] = 1-y_pos self.data[dim, :] *= np.abs(y_range[1] - y_range[0]) self.data[dim, :] += y_range[0] def read_config(self, fname): + """ + Read a config file. + + :param fname: [str] config file name + + :return: [ConfigParser] config + """ try: config = configparser.ConfigParser() config.read(fname) return config except Exception as e: print(e) return None def get_axis_settings(self, section): + """ + Extract axis settings + + :param section: [str] config section + + :return: [dict] axis options + """ dict1 = {} options = self.config.options(section) for option in options: try: dict1[option] = self.config.get(section, option) if dict1[option] == -1: print("skip: %s" % option) except: print("exception on %s!" % option) dict1[option] = None return dict1 diff --git a/hyppopy/MPIBlackboxFunction.py b/hyppopy/MPIBlackboxFunction.py new file mode 100644 index 0000000..80c749d --- /dev/null +++ b/hyppopy/MPIBlackboxFunction.py @@ -0,0 +1,83 @@ +# Hyppopy - A Hyper-Parameter Optimization Toolbox +# +# Copyright (c) German Cancer Research Center, +# Division of Medical Image Computing. +# All rights reserved. +# +# This software is distributed WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR +# A PARTICULAR PURPOSE. +# +# See LICENSE +from hyppopy.BlackboxFunction import BlackboxFunction + +__all__ = ['MPIBlackboxFunction'] + +import os +import logging +import functools +from hyppopy.globals import DEBUGLEVEL, MPI_TAGS +from mpi4py import MPI + +LOG = logging.getLogger(os.path.basename(__file__)) +LOG.setLevel(DEBUGLEVEL) + + +def default_kwargs(**defaultKwargs): + """ + Decorator defining default args in **kwargs arguments + """ + def actual_decorator(fn): + @functools.wraps(fn) + def g(*args, **kwargs): + defaultKwargs.update(kwargs) + return fn(*args, **defaultKwargs) + return g + return actual_decorator + + +class MPIBlackboxFunction(BlackboxFunction): + """ + This class is a BlackboxFunction wrapper class encapsulating the loss function. + # TODO: complete class documentation + The constructor accepts several function pointers or a data object which are all None by default (see below). + Additionally one can define an arbitrary number of arg pairs. These are passed as input to each function pointer as + arguments. + + :param dataloader_func: data loading function pointer, default=None + :param preprocess_func: data preprocessing function pointer, default=None + :param callback_func: callback function pointer, default=None + :param data: data object, default=None + :param mpi_comm: [MPI communicator] MPI communicator instance. If None, we create a new MPI.COMM_WORLD, default=None + :param kwargs: additional arg=value pairs + """ + + @default_kwargs(blackbox_func=None, dataloader_func=None, preprocess_func=None, callback_func=None, data=None, mpi_comm=None) + def __init__(self, **kwargs): + mpi_comm = kwargs['mpi_comm'] + del kwargs['mpi_comm'] + self._mpi_comm = None + + if mpi_comm is None: + print('MPIBlackboxFunction: No mpi_comm given: Using MPI.COMM_WORLD') + self._mpi_comm = MPI.COMM_WORLD + else: + self._mpi_comm = mpi_comm + + super().__init__(**kwargs) + + def call_batch(self, candidates): + results = dict() + size = self._mpi_comm.Get_size() + + for i, candidate in enumerate(candidates): + dest = (i % (size-1)) + 1 + self._mpi_comm.send(candidate, dest=dest, tag=MPI_TAGS.MPI_SEND_CANDIDATE.value) + + while True: + for i in range(size - 1): + if len(candidates) == len(results): + print('All results received!') + return results + cand_id, result_dict = self._mpi_comm.recv(source=i + 1, tag=MPI_TAGS.MPI_SEND_RESULTS.value) + results[cand_id] = result_dict \ No newline at end of file diff --git a/hyppopy/SolverPool.py b/hyppopy/SolverPool.py index 71868bc..77a477b 100644 --- a/hyppopy/SolverPool.py +++ b/hyppopy/SolverPool.py @@ -1,96 +1,99 @@ # Hyppopy - A Hyper-Parameter Optimization Toolbox # # Copyright (c) German Cancer Research Center, # Division of Medical Image Computing. # All rights reserved. # # This software is distributed WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. # # See LICENSE __all__ = ['SolverPool'] from .Singleton import * import os import logging from hyppopy.HyppopyProject import HyppopyProject from hyppopy.solvers.OptunaSolver import OptunaSolver from hyppopy.solvers.HyperoptSolver import HyperoptSolver from hyppopy.solvers.OptunitySolver import OptunitySolver from hyppopy.solvers.GridsearchSolver import GridsearchSolver from hyppopy.solvers.RandomsearchSolver import RandomsearchSolver from hyppopy.solvers.QuasiRandomsearchSolver import QuasiRandomsearchSolver from hyppopy.globals import DEBUGLEVEL LOG = logging.getLogger(os.path.basename(__file__)) LOG.setLevel(DEBUGLEVEL) @singleton_object class SolverPool(metaclass=Singleton): """ The SolverPool is a helper singleton class to get the desired solver either by name and a HyppopyProject instance or by a HyppopyProject instance only, if it defines a setting field called solver. """ def __init__(self): + """ + Constructor defines the solvers available. If a new solver should be added, add it's name to this list. + """ self._solver_list = ["hyperopt", "optunity", "optuna", "randomsearch", "quasirandomsearch", "gridsearch"] def get_solver_names(self): """ Returns a list of available solvers :return: [list] solver list """ return self._solver_list def get(self, solver_name=None, project=None): """ Get the configured solver instance :param solver_name: [str] solver name, if None, the project must have an attribute solver keeping the solver name, default=None :param project: [HyppopyProject] HyppopyProject instance :return: [HyppopySolver] the configured solver instance """ if solver_name is not None: assert isinstance(solver_name, str), "precondition violation, solver_name type str expected, got {} instead!".format(type(solver_name)) if project is not None: assert isinstance(project, HyppopyProject), "precondition violation, project type HyppopyProject expected, got {} instead!".format(type(project)) if "solver" in project.__dict__: solver_name = project.solver if solver_name not in self._solver_list: raise AssertionError("Solver named [{}] not implemented!".format(solver_name)) if solver_name == "hyperopt": if project is not None: return HyperoptSolver(project) return HyperoptSolver() elif solver_name == "optunity": if project is not None: return OptunitySolver(project) return OptunitySolver() elif solver_name == "optuna": if project is not None: return OptunaSolver(project) return OptunaSolver() elif solver_name == "gridsearch": if project is not None: return GridsearchSolver(project) return GridsearchSolver() elif solver_name == "randomsearch": if project is not None: return RandomsearchSolver(project) return RandomsearchSolver() elif solver_name == "quasirandomsearch": if project is not None: return QuasiRandomsearchSolver(project) return QuasiRandomsearchSolver() diff --git a/hyppopy/VisdomViewer.py b/hyppopy/VisdomViewer.py index d21ee51..bbb4e9c 100644 --- a/hyppopy/VisdomViewer.py +++ b/hyppopy/VisdomViewer.py @@ -1,160 +1,167 @@ # Hyppopy - A Hyper-Parameter Optimization Toolbox # # Copyright (c) German Cancer Research Center, # Division of Medical Image Computing. # All rights reserved. # # This software is distributed WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. # # See LICENSE __all__ = ['VisdomViewer'] import warnings import numpy as np from visdom import Visdom def time_formatter(time_s): """ Formats time in seconds input to more intuitive form h, min, s or ms, depending on magnitude :param time_s: [float] time in seconds :return: """ if time_s < 0.01: return int(time_s * 1000.0 * 1000) / 1000.0, "ms" elif 100 < time_s < 3600: return int(time_s / 60 * 1000) / 1000.0, "min" elif time_s >= 3600: return int(time_s / 3600 * 1000) / 1000.0, "h" else: return int(time_s * 1000) / 1000.0, "s" class VisdomViewer(object): """ The VisdomViewer class implements the live viewer plots via visdom. When extending implement your plot as methos and call it in update. Using this class make it necessary starting a visdom server beforehand $ python -m visdom.server """ def __init__(self, project, port=8097, server="http://localhost"): + """ + The constructor wants a HyppopyProject and accepts a visdom server port and a server name. + + :param project: [HyppopyProject] project instance + :param port: [int] server port, default=8097 + :param server: [str] server name, default=http://localhost + """ self._viz = Visdom(port=port, server=server) self._enabled = self._viz.check_connection(timeout_seconds=3) if not self._enabled: warnings.warn("No connection to visdom server established. Visualization cannot be displayed!") self._project = project self._best_win = None self._best_loss = None self._loss_iter_plot = None self._status_report = None self._axis_tags = None self._axis_plots = None def plot_losshistory(self, input_data): """ This function plots the loss history loss over iteration :param input_data: [dict] trail infos """ loss = np.array([input_data["loss"]]) iter = np.array([input_data["iterations"]]) if self._loss_iter_plot is None: self._loss_iter_plot = self._viz.line(loss, X=iter, opts=dict( markers=True, markersize=5, dash=np.array(['dashdot']), title="Loss History", xlabel='iteration', ylabel='loss' )) else: self._viz.line(loss, X=iter, win=self._loss_iter_plot, update='append') def plot_hyperparameter(self, input_data): """ This function plots each hyperparameter axis :param input_data: [dict] trail infos """ if self._axis_plots is None: self._axis_tags = [] self._axis_plots = {} for item in input_data.keys(): if item == "refresh_time" or item == "book_time" or item == "iterations" or item == "status" or item == "loss": continue self._axis_tags.append(item) for axis in self._axis_tags: xlabel = "value" if isinstance(input_data[axis], str): if self._project.hyperparameter[axis]["domain"] == "categorical": xlabel = '-'.join(self._project.hyperparameter[axis]["data"]) input_data[axis] = self._project.hyperparameter[axis]["data"].index(input_data[axis]) axis_loss = np.array([input_data[axis], input_data["loss"]]).reshape(1, -1) self._axis_plots[axis] = self._viz.scatter(axis_loss, opts=dict( markersize=5, title=axis, xlabel=xlabel, ylabel='loss')) else: for axis in self._axis_tags: if isinstance(input_data[axis], str): if self._project.hyperparameter[axis]["domain"] == "categorical": input_data[axis] = self._project.hyperparameter[axis]["data"].index(input_data[axis]) axis_loss = np.array([input_data[axis], input_data["loss"]]).reshape(1, -1) self._viz.scatter(axis_loss, win=self._axis_plots[axis], update='append') def show_statusreport(self, input_data): """ This function prints status report per iteration :param input_data: [dict] trail infos """ duration = input_data['refresh_time'] - input_data['book_time'] duration, time_format = time_formatter(duration.total_seconds()) report = "Iteration {}: {}{} -> {}\n".format(input_data["iterations"], duration, time_format, input_data["status"]) if self._status_report is None: self._status_report = self._viz.text(report) else: self._viz.text(report, win=self._status_report, append=True) def show_best(self, input_data): """ Shows best parameter set :param input_data: [dict] trail infos """ if self._best_win is None: self._best_loss = input_data["loss"] txt = "Best Parameter Set:
Loss: {}
" self._best_win = self._viz.text(txt) else: if input_data["loss"] < self._best_loss: self._best_loss = input_data["loss"] txt = "Best Parameter Set:
Loss: {}
" self._viz.text(txt, win=self._best_win, append=False) def update(self, input_data): """ This function calls all visdom displaying routines :param input_data: [dict] trail infos """ if self._enabled: self.show_statusreport(input_data) self.plot_losshistory(input_data) self.plot_hyperparameter(input_data) self.show_best(input_data) diff --git a/hyppopy/globals.py b/hyppopy/globals.py index 7d74106..1f966cf 100644 --- a/hyppopy/globals.py +++ b/hyppopy/globals.py @@ -1,34 +1,40 @@ # Hyppopy - A Hyper-Parameter Optimization Toolbox # # Copyright (c) German Cancer Research Center, # Division of Medical Image Computing. # All rights reserved. # # This software is distributed WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. # # See LICENSE import os import sys import logging +from enum import Enum ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) sys.path.insert(0, ROOT) LIBNAME = "hyppopy" TESTDATA_DIR = os.path.join(ROOT, *(LIBNAME, "tests", "data")) HYPERPARAMETERPATH = "hyperparameter" SETTINGSPATH = "settings" FUNCTIONSIMULATOR_DATAPATH = os.path.join(os.path.join(ROOT, LIBNAME), "virtualparameterspace") SUPPORTED_DOMAINS = ["uniform", "normal", "loguniform", "categorical"] SUPPORTED_DTYPES = ["int", "float", "str"] DEFAULTGRIDFREQUENCY = 10 LOGFILENAME = os.path.join(ROOT, '{}_log.log'.format(LIBNAME)) DEBUGLEVEL = logging.DEBUG logging.basicConfig(filename=LOGFILENAME, filemode='w', format='%(levelname)s: %(name)s - %(message)s') + + +class MPI_TAGS(Enum): + MPI_SEND_CANDIDATE = 55 + MPI_SEND_RESULTS = 99 diff --git a/hyppopy/solvers/DynamicPSOSolver.py b/hyppopy/solvers/DynamicPSOSolver.py new file mode 100644 index 0000000..ecf3d69 --- /dev/null +++ b/hyppopy/solvers/DynamicPSOSolver.py @@ -0,0 +1,250 @@ +# Hyppopy - A Hyper-Parameter Optimization Toolbox +# +# Copyright (c) German Cancer Research Center, +# Division of Medical Image Computing. +# All rights reserved. +# +# This software is distributed WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR +# A PARTICULAR PURPOSE. +# +# See LICENSE + +import os +import sys +import numpy +import datetime +import logging +import optunity +from pprint import pformat + +from hyppopy.CandidateDescriptor import CandidateDescriptor, CandicateDescriptorWrapper +from hyppopy.globals import DEBUGLEVEL +from hyperopt import Trials + +LOG = logging.getLogger(os.path.basename(__file__)) +LOG.setLevel(DEBUGLEVEL) + +from hyppopy.solvers.HyppopySolver import HyppopySolver +from .OptunitySolver import OptunitySolver + +class DynamicPSOSolver(OptunitySolver): + """Dynamic PSO HyppoPy Solver Class""" + + def define_interface(self): + """ + Function called after instantiation to define individual parameters for child solver class by calling + _add_member function for each class member variable to be defined. When designing your own solver class, + you need to implement this method to define custom solver options that are automatically converted + to class attributes. + """ + super().define_interface() + self._add_method("update_param") # Pass function used to adapt parameters during dynamic PSO as specified by user. + self._add_method("combine_obj") # Pass function indicating how to combine obj. func. arguments and parameters to obtain scalar value. + self._add_member("num_args_obj", int) # Pass number of arguments/terms contributing to obj. func. + self._add_member("num_params_obj", int) # Pass number of parameters of obj. func. + self._add_member("phi1", float, default=1.5) # Pass first PSO acceleration coefficient. + self._add_member("phi2", float, default=2.0) # Pass second PSO acceleration coefficient. + self._add_hyperparameter_signature(name="domain", dtype=str, options=["uniform", "loguniform", "categorical"]) + + def _add_method(self, name, func=None, default=None): + """ + When designing your child solver class you need to implement the define_interface abstract method where you can + call _add_member_function to define custom solver options, here of Python callable type, which are automatically + converted to class methods. + + :param func: [callable] function object to be passed to solver + """ + assert isinstance(name, str), "Precondition violation, name needs to be of type str, got {}.".format(type(name)) + if func is not None: + assert callable(func), "Precondition violation, passed object is not callable!" + if default is not None: + assert callable(default), "Precondition violation, passed object is not callable!" + setattr(self, name, func) + self._child_members[name] = {"type": "callable", "function": func, "default": default} + + def convert_searchspace(self, hyperparameter): + """ + Get unified hyppopy-like parameter space description as input and, if necessary, + convert it into a solver-lib specific format. The function is invoked when run is called and what it returns + is passed as searchspace argument to the function execute_solver. + + :param hyperparameter: [dict] nested parameter description dict e.g. {'name': {'domain':'uniform', 'data':[0,1], 'type':float}, ...} + + :return: [object] converted hyperparameter space + :return: [dict] dict keeping domains for different hyperparameters. + """ + LOG.debug("convert input parameter\n\n\t{}\n".format(pformat(hyperparameter))) + # Split input in categorical and non-categorical data. + cat, uni = self.split_categorical(hyperparameter) + # Build up dict keeping all non-categorical data. + uniforms = {} + domains = {} + for key, value in uni.items(): + for key2, value2 in value.items(): + if key2 == "data": + if len(value2) == 3: + uniforms[key] = value2[0:2] + elif len(value2) == 2: + uniforms[key] = value2 + else: + raise AssertionError("precondition violation, optunity searchspace needs list with left and right range bounds!") + if key2 == "domain": + domains[key] = value2 + + if len(cat) == 0: + return uniforms, domains + # Build nested categorical structure. + inner_level = uniforms + for key, value in cat.items(): + tmp = {} + optunity_space = {} + for key2, value2 in value.items(): + if key2 == "data": + for elem in value2: + tmp[elem] = inner_level + if key2 == "domain": + domains[key] = value2 + optunity_space[key] = tmp + inner_level = optunity_space + return optunity_space, domains + + def hyppopy_optunity_solver_pmap(self, f, seq): + # Check if seq is empty. I so, return an empty result list. + if len(seq) == 0: + return [] + + candidates = [] + for elem in seq: + can = CandidateDescriptor(**elem) + candidates.append(can) + + cand_list = CandicateDescriptorWrapper(keys=seq[0].keys()) + cand_list.set(candidates) + + f_result = f(cand_list) + + # If one candidate does not match the constraints, f() returns a single default value. + # This is a problem as all the other candidates are not calculated either. + # The following is a workaround. We split the candidate_list into 2 lists and call the map function recursively until all valid parameters are processed. + if not isinstance(f_result, list): + # First half + seq_A = seq[:len(seq) // 2] + temp_result_a = self.hyppopy_optunity_solver_pmap(f, seq_A) + + seq_B = seq[len(seq) // 2:] + temp_result_b = self.hyppopy_optunity_solver_pmap(f, seq_B) + # f_result = [42] + + f_result = temp_result_a + temp_result_b + + return f_result + + def execute_solver(self, searchspace, domains): + """ + This function is called immediately after convert_searchspace and uses the output of the latter as input. Its + purpose is to call the solver lib's main optimization function. + + :param searchspace: converted hyperparameter space + """ + LOG.debug("execute_solver using solution space:\n\n\t{}\n".format(pformat(searchspace))) + tree = optunity.search_spaces.SearchTree(searchspace) # Set up tree structure to model search space. + box = tree.to_box() # Create set of box constraints to define given search space. + f = optunity.functions.logged(self.loss_function_batch) # Call log here because function signature used later on is internal logic. + f = tree.wrap_decoder(f) # Wrap decoder and constraints for internal search space rep. + f = optunity.constraints.wrap_constraints(f, default=sys.float_info.max*numpy.ones(self.num_args_obj), range_oo=box) + # 'wrap_constraints' decorates function f with given input domain constraints. default [float] gives a + # function value to default to in case of constraint violations. range_oo [dict] gives open range + # constraints lb and lu, i.e. lb < x < ub and range = (lb, ub), respectively. + + try: + self.best, _ = optunity.optimize_dyn_PSO(func=f, + box=box, + domains=domains, + maximize=False, + max_evals=self.max_iterations, + num_args_obj=self.num_args_obj, + num_params_obj=self.num_params_obj, + pmap=self.hyppopy_optunity_solver_pmap, #map,#optunity.pmap, + decoder=tree.decode, + update_param=self.update_param, + eval_obj=self.combine_obj, + phi1=self.phi1, + phi2=self.phi2 + ) + # Workaround: Unpack best result, im max_iterations was reached. + try: + for key in self.best: + self.best[key] = self.best[key].get()[0] + except: + pass + """ + optimize_dyn_PSO(func, maximize=False, max_evals=0, pmap=map, decoder=None, update_param=None, eval_obj=None) + Optimize func with dynamic PSO solver. + :param func: [callable] objective function + :param maximize: [bool] maximize or minimize + :param max_evals: [int] maximum number of permitted function evaluations + :param pmap: [function] map() function to use + :param update_param: [function] function to update parameters of objective function + based on current state of knowledge + :param eval_obj: [function] function giving functional form of objective function, i.e. + how to combine parameters and terms to obtain scalar fitness/loss. + + :return: solution, named tuple with further details + optimize_dyn_PSO function (api.py) internally uses 'optimize' function from dynamic PSO solver module. + """ + except Exception as e: + LOG.error("Internal error in optunity.optimize_dyn_PSO occured. {}".format(e)) + raise BrokenPipeError("Internal error in optunity.optimize_dyn_PSO occured. {}".format(e)) + + def print_best(self): + """ + Optimization result console output printing. + """ + print("\n") + print("#" * 40) + print("### Best Parameter Choice ###") + print("#" * 40) + for name, value in self.best.items(): + print(" - {}\t:\t{}".format(name, value)) + #print("\n - number of iterations\t:\t{}".format(self.trials.trials[-1]['tid']+1)) + #print(" - total time\t:\t{}d:{}h:{}m:{}s:{}ms".format(self._total_duration[0], + # self._total_duration[1], + # self._total_duration[2], + # self._total_duration[3], + # self._total_duration[4])) + print("#" * 40) + + def run(self, print_stats=True): + """ + This function starts the optimization process. + :param print_stats: [bool] en- or disable console output + """ + self._idx = 0 + self.trials = Trials() + + start_time = datetime.datetime.now() + try: + search_space, domains = self.convert_searchspace(self.project.hyperparameter) + except Exception as e: + msg = "Failed to convert searchspace, error: {}".format(e) + LOG.error(msg) + raise AssertionError(msg) + try: + self.execute_solver(search_space, domains) + except Exception as e: + msg = "Failed to execute solver, error: {}".format(e) + LOG.error(msg) + raise AssertionError(msg) + end_time = datetime.datetime.now() + dt = end_time - start_time + days = divmod(dt.total_seconds(), 86400) + hours = divmod(days[1], 3600) + minutes = divmod(hours[1], 60) + seconds = divmod(minutes[1], 1) + milliseconds = divmod(seconds[1], 0.001) + self._total_duration = [int(days[0]), int(hours[0]), int(minutes[0]), int(seconds[0]), int(milliseconds[0])] + self.print_best() + if print_stats: + self.print_timestats() + diff --git a/hyppopy/solvers/GridsearchSolver.py b/hyppopy/solvers/GridsearchSolver.py index 1b43ea2..f11df27 100644 --- a/hyppopy/solvers/GridsearchSolver.py +++ b/hyppopy/solvers/GridsearchSolver.py @@ -1,206 +1,234 @@ # Hyppopy - A Hyper-Parameter Optimization Toolbox # # Copyright (c) German Cancer Research Center, # Division of Medical Image Computing. # All rights reserved. # # This software is distributed WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. # # See LICENSE import os import logging import warnings import numpy as np from pprint import pformat + from scipy.stats import norm from itertools import product from hyppopy.globals import DEBUGLEVEL, DEFAULTGRIDFREQUENCY from hyppopy.solvers.HyppopySolver import HyppopySolver +from hyppopy.CandidateDescriptor import CandidateDescriptor LOG = logging.getLogger(os.path.basename(__file__)) LOG.setLevel(DEBUGLEVEL) def get_uniform_axis_sample(a, b, N, dtype): """ Returns a uniform sample x(n) in the range [a,b] sampled at N pojnts :param a: left value range bound :param b: right value range bound :param N: discretization of intervall [a,b] :param dtype: data type :return: [list] axis range """ assert a < b, "condition a < b violated!" assert isinstance(N, int), "condition N of type int violated!" if dtype is int: return list(np.linspace(a, b, N).astype(int)) elif dtype is float: return list(np.linspace(a, b, N)) else: raise AssertionError("dtype {} not supported for uniform sampling!".format(dtype)) def get_norm_cdf(N): """ Returns a normed gaussian cdf (range [0,1]) with N sampling points :param N: sampling points :return: [ndarray] gaussian cdf function values """ assert isinstance(N, int), "condition N of type int violated!" even = True if N % 2 != 0: N -= 1 even = False N = int(N/2) sigma = 1/3 x = np.linspace(0, 1, N) y1 = norm.cdf(x, loc=0, scale=sigma)-0.5 if not even: y1 = np.append(y1, [0.5]) y2 = 1-(norm.cdf(x, loc=0, scale=sigma)-0.5) y2 = np.flip(y2, axis=0) y = np.concatenate((y1, y2), axis=0) return y def get_gaussian_axis_sample(a, b, N, dtype): """ Returns a function value f(n) where f is a gaussian cdf in range [a, b] and N sampling points :param a: left value range bound :param b: right value range bound :param N: discretization of intervall [a,b] :param dtype: data type :return: [list] axis range """ assert a < b, "condition a < b violated!" assert isinstance(N, int), "condition N of type int violated!" data = [] for n in range(N): x = a + get_norm_cdf(N)[n]*(b-a) if dtype is int: data.append(int(x)) elif dtype is float: data.append(x) else: raise AssertionError("dtype {} not supported for uniform sampling!".format(dtype)) return data def get_logarithmic_axis_sample(a, b, N, dtype): """ Returns a function value f(n) where f is logarithmic function e^x sampling the exponent range [log(a), log(b)] linear at N sampling points. The function values returned are in the range [a, b]. :param a: left value range bound :param b: right value range bound :param N: discretization of intervall [a,b] :param dtype: data type :return: [list] axis range """ assert a < b, "condition a < b violated!" assert a > 0, "condition a > 0 violated!" assert isinstance(N, int), "condition N of type int violated!" # convert input range into exponent range lexp = np.log(a) rexp = np.log(b) exp_range = np.linspace(lexp, rexp, N) data = [] for n in range(exp_range.shape[0]): x = np.exp(exp_range[n]) if dtype is int: data.append(int(x)) elif dtype is float: data.append(x) else: raise AssertionError("dtype {} not supported for uniform sampling!".format(dtype)) return data class GridsearchSolver(HyppopySolver): """ The GridsearchSolver class implements a gridsearch optimization. The gridsearch supports categorical, uniform, normal and loguniform sampling. To use the GridsearchSolver, besides a range, one must specifiy the number of samples in the domain, e.g. 'data': [0, 1, 100] """ def __init__(self, project=None): + """ + The constructor accepts a HyppopyProject. + + :param project: [HyppopyProject] project instance, default=None + """ HyppopySolver.__init__(self, project) def define_interface(self): + """ + This function is called when HyppopySolver.__init__ function finished. Child classes need to define their + individual parameter here by calling the _add_member function for each class member variable need to be defined. + Using _add_hyperparameter_signature the structure of a hyperparameter the solver expects must be defined. + Both, members and hyperparameter signatures are later get checked, before executing the solver, ensuring + settings passed fullfill solver needs. + """ self._add_hyperparameter_signature(name="domain", dtype=str, options=["uniform", "normal", "loguniform", "categorical"]) self._add_hyperparameter_signature(name="data", dtype=list) self._add_hyperparameter_signature(name="frequency", dtype=int) self._add_hyperparameter_signature(name="type", dtype=type) - def loss_function_call(self, params): - loss = self.blackbox(**params) - if loss is None: - return np.nan - return loss + def get_candidates(self, searchspace): + """ + This function converts the searchspace to a candidate_list that can then be used to distribute via MPI. - def execute_solver(self, searchspace): - for x in product(*searchspace[1]): + :param searchspace: converted hyperparameter space + """ + candidates_list = list() + candidates = [x for x in product(*searchspace[1])] + for c in candidates: params = {} - for name, value in zip(searchspace[0], x): + for name, value in zip(searchspace[0], c): params[name] = value - try: - self.loss_function(**params) - except Exception as e: - msg = "internal error in randomsearch execute_solver occured. {}".format(e) - LOG.error(msg) - raise BrokenPipeError(msg) + candidates_list.append(CandidateDescriptor(**params)) + + return candidates_list + + def execute_solver(self, searchspace): + """ + This function is called immediately after convert_searchspace and get the output of the latter as input. It's + purpose is to call the solver libs main optimization function. + + :param searchspace: converted hyperparameter space + """ + candidates = self.get_candidates(searchspace) + + try: + self.loss_function_batch(candidates) + except Exception as e: + msg = "internal error in gridsearch execute_solver occured. {}".format(e) + LOG.error(msg) + raise BrokenPipeError(msg) self.best = self._trials.argmin def convert_searchspace(self, hyperparameter): """ The function converts the standard parameter input into a range list depending on the domain. These rangelists are later used with itertools product to create a paramater space sample of each combination. :param hyperparameter: [dict] hyperparameter space :return: [list] name and range for each parameter space axis """ LOG.debug("convert input parameter\n\n\t{}\n".format(pformat(hyperparameter))) searchspace = [[], []] for name, param in hyperparameter.items(): if param["domain"] != "categorical" and "frequency" not in param.keys(): param["frequency"] = DEFAULTGRIDFREQUENCY warnings.warn("No frequency field found, used default gridsearch frequency {}".format(DEFAULTGRIDFREQUENCY)) if param["domain"] == "categorical": searchspace[0].append(name) searchspace[1].append(param["data"]) elif param["domain"] == "uniform": searchspace[0].append(name) searchspace[1].append(get_uniform_axis_sample(param["data"][0], param["data"][1], param["frequency"], param["type"])) elif param["domain"] == "normal": searchspace[0].append(name) searchspace[1].append(get_gaussian_axis_sample(param["data"][0], param["data"][1], param["frequency"], param["type"])) elif param["domain"] == "loguniform": searchspace[0].append(name) searchspace[1].append(get_logarithmic_axis_sample(param["data"][0], param["data"][1], param["frequency"], param["type"])) return searchspace diff --git a/hyppopy/solvers/HyperoptSolver.py b/hyppopy/solvers/HyperoptSolver.py index aba08c0..bc8fdc8 100644 --- a/hyppopy/solvers/HyperoptSolver.py +++ b/hyppopy/solvers/HyperoptSolver.py @@ -1,161 +1,236 @@ # Hyppopy - A Hyper-Parameter Optimization Toolbox # # Copyright (c) German Cancer Research Center, # Division of Medical Image Computing. # All rights reserved. # # This software is distributed WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. # # See LICENSE import os import copy import logging import numpy as np from pprint import pformat from hyperopt import fmin, tpe, hp, STATUS_OK, STATUS_FAIL, Trials from hyppopy.globals import DEBUGLEVEL from hyppopy.solvers.HyppopySolver import HyppopySolver from hyppopy.BlackboxFunction import BlackboxFunction LOG = logging.getLogger(os.path.basename(__file__)) LOG.setLevel(DEBUGLEVEL) class HyperoptSolver(HyppopySolver): def __init__(self, project=None): + """ + The constructor accepts a HyppopyProject. + + :param project: [HyppopyProject] project instance, default=None + """ HyppopySolver.__init__(self, project) self._searchspace = None def define_interface(self): + """ + This function is called when HyppopySolver.__init__ function finished. Child classes need to define their + individual parameter here by calling the _add_member function for each class member variable need to be defined. + Using _add_hyperparameter_signature the structure of a hyperparameter the solver expects must be defined. + Both, members and hyperparameter signatures are later get checked, before executing the solver, ensuring + settings passed fullfill solver needs. + """ self._add_member("max_iterations", int) self._add_hyperparameter_signature(name="domain", dtype=str, options=["uniform", "normal", "loguniform", "categorical"]) self._add_hyperparameter_signature(name="data", dtype=list) self._add_hyperparameter_signature(name="type", dtype=type) def loss_function(self, params): + """ + Loss function wrapper function. + + :param params: [dict] hyperparameter set + + :return: [float] loss + """ for name, p in self._searchspace.items(): if p["domain"] != "categorical": if params[name] < p["data"][0]: params[name] = p["data"][0] if params[name] > p["data"][1]: params[name] = p["data"][1] status = STATUS_FAIL try: loss = self.blackbox(**params) if loss is not None: status = STATUS_OK else: loss = 1e9 except Exception as e: LOG.error("execution of self.blackbox(**params) failed due to:\n {}".format(e)) status = STATUS_FAIL loss = 1e9 cbd = copy.deepcopy(params) cbd['iterations'] = self._trials.trials[-1]['tid'] + 1 cbd['loss'] = loss cbd['status'] = status cbd['book_time'] = self._trials.trials[-1]['book_time'] cbd['refresh_time'] = self._trials.trials[-1]['refresh_time'] if isinstance(self.blackbox, BlackboxFunction) and self.blackbox.callback_func is not None: self.blackbox.callback_func(**cbd) if self._visdom_viewer is not None: self._visdom_viewer.update(cbd) return {'loss': loss, 'status': status} + def loss_func_cand_preprocess(self, params): + """ + Loss function wrapper function. + + :param params: [dict] hyperparameter set + + :return: [float] loss + """ + for name, p in self._searchspace.items(): + if p["domain"] != "categorical": + if params[name] < p["data"][0]: + params[name] = p["data"][0] + if params[name] > p["data"][1]: + params[name] = p["data"][1] + + return params + + def loss_func_postprocess(self, loss): + """ + Loss function wrapper function. + + :param params: [dict] hyperparameter set + + :return: [float] loss + """ + + if loss is not None: + status = STATUS_OK + else: + loss = 1e9 + + # return {'loss': loss, 'status': status} + return loss + def execute_solver(self, searchspace): + """ + This function is called immediately after convert_searchspace and get the output of the latter as input. It's + purpose is to call the solver libs main optimization function. + + :param searchspace: converted hyperparameter space + """ LOG.debug("execute_solver using solution space:\n\n\t{}\n".format(pformat(searchspace))) self.trials = Trials() try: self.best = fmin(fn=self.loss_function, space=searchspace, algo=tpe.suggest, max_evals=self.max_iterations, trials=self.trials) except Exception as e: msg = "internal error in hyperopt.fmin occured. {}".format(e) LOG.error(msg) raise BrokenPipeError(msg) def convert_searchspace(self, hyperparameter): + """ + This function gets the unified hyppopy-like parameterspace description as input and, if necessary, should + convert it into a solver lib specific format. The function is invoked when run is called and what it returns + is passed as searchspace argument to the function execute_solver. + + :param hyperparameter: [dict] nested parameter description dict e.g. {'name': {'domain':'uniform', 'data':[0,1], 'type':'float'}, ...} + + :return: [object] converted hyperparameter space + """ self._searchspace = hyperparameter solution_space = {} for name, content in hyperparameter.items(): param_settings = {'name': name} for key, value in content.items(): if key == 'domain': param_settings['domain'] = value elif key == 'data': param_settings['data'] = value elif key == 'type': param_settings['dtype'] = value solution_space[name] = self.convert(param_settings) return solution_space def convert(self, param_settings): + """ + Convert searchspace to hyperopt specific searchspace + + :param param_settings: [dict] hyperparameter description + + :return: [object] hyperopt description + """ name = param_settings["name"] domain = param_settings["domain"] dtype = param_settings["dtype"] data = param_settings["data"] if domain == "uniform": if dtype is float: return hp.uniform(name, data[0], data[1]) elif dtype is int: data = list(np.arange(int(data[0]), int(data[1] + 1))) return hp.choice(name, data) else: msg = "cannot convert the type {} in domain {}".format(dtype, domain) LOG.error(msg) raise LookupError(msg) elif domain == "loguniform": if dtype is float: if data[0] == 0: data[0] += 1e-23 assert data[0] > 0, "precondition Violation, a < 0!" assert data[0] < data[1], "precondition Violation, a > b!" assert data[1] > 0, "precondition Violation, b < 0!" lexp = np.log(data[0]) rexp = np.log(data[1]) assert lexp is not np.nan, "precondition violation, left bound input error, results in nan!" assert rexp is not np.nan, "precondition violation, right bound input error, results in nan!" return hp.loguniform(name, lexp, rexp) else: msg = "cannot convert the type {} in domain {}".format(dtype, domain) LOG.error(msg) raise LookupError(msg) elif domain == "normal": if dtype is float: mu = (data[1] - data[0]) / 2.0 sigma = mu / 3 return hp.normal(name, data[0] + mu, sigma) else: msg = "cannot convert the type {} in domain {}".format(dtype, domain) LOG.error(msg) raise LookupError(msg) elif domain == "categorical": if dtype is str: return hp.choice(name, data) elif dtype is bool: - data = [] + conv = [] for elem in data: - if elem == "true" or elem == "True" or elem == 1 or elem == "1": - data.append(True) - elif elem == "false" or elem == "False" or elem == 0 or elem == "0": - data.append(False) + if elem == "true" or elem == "True" or elem == 1 or elem == "1" or elem == True: + conv.append(True) + elif elem == "false" or elem == "False" or elem == 0 or elem == "0" or elem == False: + conv.append(False) else: msg = "cannot convert the type {} in domain {}, unknown bool type value".format(dtype, domain) LOG.error(msg) raise LookupError(msg) - return hp.choice(name, data) + return hp.choice(name, conv) else: msg = "Precondition violation, domain named {} not available!".format(domain) LOG.error(msg) raise IOError(msg) diff --git a/hyppopy/solvers/HyppopySolver.py b/hyppopy/solvers/HyppopySolver.py index c774ad4..8264476 100644 --- a/hyppopy/solvers/HyppopySolver.py +++ b/hyppopy/solvers/HyppopySolver.py @@ -1,445 +1,590 @@ # Hyppopy - A Hyper-Parameter Optimization Toolbox # # Copyright (c) German Cancer Research Center, # Division of Medical Image Computing. # All rights reserved. # # This software is distributed WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. # # See LICENSE +from _pytest import deprecated + +from hyppopy import CandidateDescriptor __all__ = ['HyppopySolver'] import abc import copy import types import datetime import numpy as np import pandas as pd from hyperopt import Trials from hyppopy.globals import * +from hyppopy.CandidateDescriptor import CandidateDescriptor from hyppopy.VisdomViewer import VisdomViewer from hyppopy.HyppopyProject import HyppopyProject from hyppopy.BlackboxFunction import BlackboxFunction from hyppopy.FunctionSimulator import FunctionSimulator from hyppopy.globals import DEBUGLEVEL LOG = logging.getLogger(os.path.basename(__file__)) LOG.setLevel(DEBUGLEVEL) class HyppopySolver(object): """ The HyppopySolver class is the base class for all solver addons. It defines virtual functions a child class has to implement to deal with the front-end communication, orchestrating the optimization process and ensuring a proper process information storing. The key idea is that the HyppopySolver class defines an interface to configure and run an object instance of itself independently from the concrete solver lib used to optimize in the background. To achieve this goal an addon - developer needs to implement the abstract methods 'convert_searchspace', 'execute_solver' and 'loss_function_call'. + developer needs to implement the abstract methods 'convert_searchspace', 'execute_solver'. These methods abstract the peculiarities of the solver libs to offer, on the user side, a simple and consistent parameter space configuration and optimization procedure. The method 'convert_searchspace' transforms the hyppopy - parameter space description into the solver lib specific description. The method loss_function_call is used to - handle solver lib specifics of calling the actual blackbox function and execute_solver is executed when the run - method is invoked und takes care of calling the solver lib solving routine. + parameter space description into the solver lib specific description. The methods loss_func_cand_preprocess and + loss_func_postprocess are used to handle solver lib specifics of calling the actual blackbox function and + execute_solver is executed when the run method is invoked und takes care of calling the solver lib solving routine. The class HyppopySolver defines an interface to be implemented when writing a custom solver. Each solver derivative needs to implement the abstract methods: - convert_searchspace - execute_solver - - loss_function_call + - TODO - define_interface The dev-user interface consists of the methods: - _add_member - _add_hyperparameter_signature - _check_project The end-user interface consists of the methods: - run - get_results - print_best - print_timestats - start_viewer """ def __init__(self, project=None): - self._idx = None # current iteration counter + """ + The constructor accepts a HyppopyProject. + + :param project: [HyppopyProject] project instance, default=None + """ + self._idx = 0 # current iteration counter self._best = None # best parameter set self._trials = None # trials object, hyppopy uses the Trials object from hyperopt self._blackbox = None # blackbox function, eiter a function or a BlackboxFunction instance self._total_duration = None # keeps track of the solvers running time self._solver_overhead = None # stores the time overhead of the solver, means total time minus time in blackbox self._time_per_iteration = None # mean time per iterration self._accumulated_blackbox_time = None # summed time the solver was in the blackbox function self._visdom_viewer = None # visdom viewer instance self._child_members = {} # this dict keeps track of the settings the child solver defines self._hopt_signatures = {} # this dict keeps track of the hyperparameter signatures the child solver defines self.define_interface() # the child define interface function is called which defines settings and hyperparameter signatures if project is not None: self.project = project @abc.abstractmethod def convert_searchspace(self, hyperparameter): """ This function gets the unified hyppopy-like parameterspace description as input and, if necessary, should convert it into a solver lib specific format. The function is invoked when run is called and what it returns is passed as searchspace argument to the function execute_solver. :param hyperparameter: [dict] nested parameter description dict e.g. {'name': {'domain':'uniform', 'data':[0,1], 'type':'float'}, ...} :return: [object] converted hyperparameter space """ raise NotImplementedError('users must define convert_searchspace to use this class') @abc.abstractmethod def execute_solver(self, searchspace): """ - This function is called immediatly after convert_searchspace and get the output of the latter as input. It's + This function is called immediately after convert_searchspace and get the output of the latter as input. It's purpose is to call the solver libs main optimization function. :param searchspace: converted hyperparameter space """ raise NotImplementedError('users must define execute_solver to use this class') @abc.abstractmethod - def loss_function_call(self, params): + def loss_function_batch_call(self, candidates): # TODO: Delete me... + """ + TODO + :param candidates: + :return: """ - This function is called within the function loss_function and encapsulates the actual blackbox function call - in each iteration. The function loss_function takes care of the iteration driving and reporting, but each solver - lib might need some special treatment between the parameter set selection and the calling of the actual blackbox - function, e.g. parameter converting. - :param params: [dict] hyperparameter space sample e.g. {'p1': 0.123, 'p2': 3.87, ...} + # TODO This is deprecated! Mark or remove... + raise NotImplementedError('users must define loss_function_batch_call to use this class') - :return: [float] loss + def loss_func_cand_preprocess(self, candidates): # TODO: Delete me... + """ + TODO + :param candidates: + :return: """ - raise NotImplementedError('users must define loss_function_call to use this class') + # User may implement this function to preprocess candidates before calling the actual loss_function + # raise NotImplementedError('users must define loss_function_batch_call to use this class') + return candidates + + def loss_func_postprocess(self, results): # TODO: Delete me... + """ + TODO + :param candidates: + :return: + """ + # User may implement this function to postprocess results after calling the actual loss_function + # raise NotImplementedError('users must define loss_function_batch_call to use this class') + return results + @abc.abstractmethod def define_interface(self): """ This function is called when HyppopySolver.__init__ function finished. Child classes need to define their individual parameter here by calling the _add_member function for each class member variable need to be defined. Using _add_hyperparameter_signature the structure of a hyperparameter the solver expects must be defined. Both, members and hyperparameter signatures are later get checked, before executing the solver, ensuring settings passed fullfill solver needs. """ raise NotImplementedError('users must define define_interface to use this class') def _add_member(self, name, dtype, value=None, default=None): """ When designing your child solver class you need to implement the define_interface abstract method where you can call _add_member to define custom solver options that are automatically converted to class attributes. :param name: [str] option name :param dtype: [type] option data type :param value: [object] option value :param default: [object] option default value """ assert isinstance(name, str), "precondition violation, name needs to be of type str, got {}".format(type(name)) if value is not None: assert isinstance(value, dtype), "precondition violation, value does not match dtype condition!" if default is not None: assert isinstance(default, dtype), "precondition violation, default does not match dtype condition!" setattr(self, name, value) self._child_members[name] = {"type": dtype, "value": value, "default": default} def _add_hyperparameter_signature(self, name, dtype, options=None): """ When designing your child solver class you need to implement the define_interface abstract method where you can call _add_hyperparameter_signature to define a hyperparamter signature which is automatically checked for consistency while solver execution. :param name: [str] hyperparameter name :param dtype: [type] hyperparameter data type :param options: [list] list of possible values the hp can be set, if None no option check is done """ assert isinstance(name, str), "precondition violation, name needs to be of type str, got {}".format(type(name)) self._hopt_signatures[name] = {"type": dtype, "options": options} def _check_project(self): """ The function checks the members and hyperparameter signatures read from the project instance to be consistent with the members and signatures defined in the child class via define_interface. """ assert isinstance(self.project, HyppopyProject), "Invalid project instance, either not set or setting failed!" # check hyperparameter signatures for name, param in self.project.hyperparameter.items(): for sig, settings in self._hopt_signatures.items(): if sig not in param.keys(): msg = "Missing hyperparameter signature {}!".format(sig) LOG.error(msg) raise LookupError(msg) else: if not isinstance(param[sig], settings["type"]): msg = "Hyperparameter signature type mismatch, expected type {} got {}!".format(settings["type"], param[sig]) LOG.error(msg) raise TypeError(msg) if settings["options"] is not None: if param[sig] not in settings["options"]: msg = "Wrong signature value, {} not found in signature options!".format(param[sig]) LOG.error(msg) raise LookupError(msg) # check child members for name in self._child_members.keys(): if name not in self.project.__dict__.keys(): msg = "missing settings field {}!".format(name) LOG.error(msg) raise LookupError(msg) self.__dict__[name] = self.project.settings[name] def __compute_time_statistics(self): """ Evaluates all timestatistic values available """ dts = [] for trial in self._trials.trials: if 'book_time' in trial.keys() and 'refresh_time' in trial.keys(): dt = trial['refresh_time'] - trial['book_time'] dts.append(dt.total_seconds()) self._time_per_iteration = np.mean(dts) * 1e3 self._accumulated_blackbox_time = np.sum(dts) * 1e3 tmp = self.total_duration - self._accumulated_blackbox_time self._solver_overhead = int(np.round(100.0 / (self.total_duration + 1e-12) * tmp)) def loss_function(self, **params): """ This function is called each iteration with a selected parameter set. The parameter set selection is driven by - the solver lib itself. The purpose of this function is to take care of the iteration reporting and the calling - of the callback_func is available. As a developer you might want to overwrite this function completely (e.g. - HyperoptSolver) but then you need to take care for iteration reporting for yourself. The alternative is to only - implement loss_function_call (e.g. OptunitySolver). + the solver lib itself. + This function just calls loss_function_batch() with a batch size of one. It takes care of converting the params to CandidateDescriptors. :param params: [dict] hyperparameter space sample e.g. {'p1': 0.123, 'p2': 3.87, ...} :return: [float] loss """ - self._idx += 1 - vals = {} - idx = {} - for key, value in params.items(): - vals[key] = [value] - idx[key] = [self._idx] - trial = {'tid': self._idx, - 'result': {'loss': None, 'status': 'ok'}, - 'misc': { - 'tid': self._idx, - 'idxs': idx, - 'vals': vals - }, - 'book_time': datetime.datetime.now(), - 'refresh_time': None - } + + newCandidate = CandidateDescriptor(**params) + results = self.loss_function_batch([newCandidate]) + + return list(results.values())[0]['loss'] # Here 'results' will always contain a single dict. We extract the loss from it and return it. + + def loss_function_batch(self, candidates): + """ + This function is called with a list of candidates. This list is driven by the solver lib itself. + The purpose of this function is to take care of the iteration reporting and the calling + of the callback_func if available. As a developer you might want to overwrite this function (or the 'non-batch'-version completely (e.g. + HyperoptSolver). + + :param candidates: [list of CandidateDescriptors] + + :return: [dict] result e.g. {'loss': 0.5, 'book_time': ..., 'refresh_time': ...} + """ + + results = dict() try: - loss = self.loss_function_call(params) - trial['result']['loss'] = loss - trial['result']['status'] = 'ok' - if loss == np.nan: - trial['result']['status'] = 'failed' + candidates = self.loss_func_cand_preprocess(candidates) + results = self.blackbox.call_batch(candidates) + if results is None: + results = np.nan + results = self.loss_func_postprocess(results) + except ZeroDivisionError as e: + # Fallback: If call_batch is not supported in BlackboxFunction, we iterate over the candidates in the batch. + message = "Script not started via MPI:\n {}".format(e) + LOG.error(message) except Exception as e: - LOG.error("computing loss failed due to:\n {}".format(e)) - loss = np.nan - trial['result']['loss'] = np.nan - trial['result']['status'] = 'failed' - trial['refresh_time'] = datetime.datetime.now() - self._trials.trials.append(trial) - cbd = copy.deepcopy(params) - cbd['iterations'] = self._idx - cbd['loss'] = loss - cbd['status'] = trial['result']['status'] - cbd['book_time'] = trial['book_time'] - cbd['refresh_time'] = trial['refresh_time'] - if isinstance(self.blackbox, BlackboxFunction) and self.blackbox.callback_func is not None: - self.blackbox.callback_func(**cbd) - if self._visdom_viewer is not None: - self._visdom_viewer.update(cbd) - return loss + message = "call_batch not supported in BlackboxFunction:\n {}".format(e) + LOG.error(message) + finally: + for i, candidate in enumerate(candidates): + cand_id = candidate.ID + # params = candidate.get_values() + + cand_results = dict() + cand_results['book_time'] = datetime.datetime.now() + try: + preprocessed_candidate_list = self.loss_func_cand_preprocess([candidate]) + candidate = preprocessed_candidate_list[0] + params = candidate.get_values() + try: + loss = self.blackbox(**params) + except: + loss = self.blackbox(params) + if loss is None: + loss = np.nan + cand_results['loss'] = loss + except Exception as e: + LOG.error("computing loss failed due to:\n {}".format(e)) + cand_results['loss'] = np.nan + cand_results['refresh_time'] = datetime.datetime.now() + results[cand_id] = cand_results + results = self.loss_func_postprocess(results) + + # initialize trials + for i, candidate in enumerate(candidates): + self._idx += 1 + vals = {} + idx = {} + for key in candidate.keys(): + vals[key] = [candidate[key]] + idx[key] = [self._idx] + trial = {'tid': self._idx, + 'result': {'loss': None, 'status': 'ok'}, + 'misc': { + 'tid': self._idx, + 'idxs': idx, + 'vals': vals + }, + 'book_time': results[candidate.ID]['book_time'], + 'refresh_time': results[candidate.ID]['refresh_time'] + } + try: + loss = results[candidate.ID]['loss'] + trial['result']['loss'] = loss + trial['result']['status'] = 'ok' + if loss is np.nan: + trial['result']['status'] = 'failed' + except Exception as e: + LOG.error("computing loss failed due to:\n {}".format(e)) + loss = np.nan + trial['result']['loss'] = np.nan + trial['result']['status'] = 'failed' + self._trials.trials.append(trial) + cbd = copy.deepcopy(candidate.get_values()) + cbd['iterations'] = self._idx + cbd['loss'] = loss + cbd['status'] = trial['result']['status'] + cbd['book_time'] = trial['book_time'] + cbd['refresh_time'] = trial['refresh_time'] + if isinstance(self.blackbox, BlackboxFunction) and self.blackbox.callback_func is not None: + self.blackbox.callback_func(**cbd) + + return results def run(self, print_stats=True): """ This function starts the optimization process. :param print_stats: [bool] en- or disable console output """ self._idx = 0 self.trials = Trials() start_time = datetime.datetime.now() try: search_space = self.convert_searchspace(self.project.hyperparameter) except Exception as e: msg = "Failed to convert searchspace, error: {}".format(e) LOG.error(msg) raise AssertionError(msg) try: self.execute_solver(search_space) except Exception as e: msg = "Failed to execute solver, error: {}".format(e) LOG.error(msg) raise AssertionError(msg) end_time = datetime.datetime.now() dt = end_time - start_time days = divmod(dt.total_seconds(), 86400) hours = divmod(days[1], 3600) minutes = divmod(hours[1], 60) seconds = divmod(minutes[1], 1) milliseconds = divmod(seconds[1], 0.001) self._total_duration = [int(days[0]), int(hours[0]), int(minutes[0]), int(seconds[0]), int(milliseconds[0])] if print_stats: self.print_best() self.print_timestats() def get_results(self): """ This function returns a complete optimization history as pandas DataFrame and a dict with the optimal parameter set. :return: [DataFrame], [dict] history and optimal parameter set """ assert isinstance(self.trials, Trials), "precondition violation, wrong trials type! Maybe solver was not yet executed?" results = {'duration': [], 'losses': [], 'status': []} pset = self.trials.trials[0]['misc']['vals'] for p in pset.keys(): results[p] = [] for n, trial in enumerate(self.trials.trials): t1 = trial['book_time'] t2 = trial['refresh_time'] results['duration'].append((t2 - t1).microseconds / 1000.0) results['losses'].append(trial['result']['loss']) results['status'].append(trial['result']['status'] == 'ok') losses = np.array(results['losses']) results['losses'] = list(losses) pset = trial['misc']['vals'] for p in pset.items(): results[p[0]].append(p[1][0]) return pd.DataFrame.from_dict(results), self.best def print_best(self): """ Optimization result console output printing. """ print("\n") print("#" * 40) print("### Best Parameter Choice ###") print("#" * 40) for name, value in self.best.items(): print(" - {}\t:\t{}".format(name, value)) + print("\n - number of iterations\t:\t{}".format(self.trials.trials[-1]['tid']+1)) print(" - total time\t:\t{}d:{}h:{}m:{}s:{}ms".format(self._total_duration[0], self._total_duration[1], self._total_duration[2], self._total_duration[3], self._total_duration[4])) print("#" * 40) def print_timestats(self): """ Time statistic console output printing. """ print("\n") print("#" * 40) print("### Timing Statistics ###") print("#" * 40) print(" - per iteration: {}ms".format(int(self.time_per_iteration*1e4)/10000)) print(" - total time: {}d:{}h:{}m:{}s:{}ms".format(self._total_duration[0], self._total_duration[1], self._total_duration[2], self._total_duration[3], self._total_duration[4])) print("#" * 40) print(" - solver overhead: {}%".format(self.solver_overhead)) def start_viewer(self, port=8097, server="http://localhost"): """ Starts the visdom viewer. :param port: [int] port number, default: 8097 :param server: [str] server name, default: http://localhost """ try: self._visdom_viewer = VisdomViewer(self._project, port, server) except Exception as e: import warnings warnings.warn("Failed starting VisdomViewer. Is the server running? If not start it via $visdom") LOG.error("Failed starting VisdomViewer: {}".format(e)) self._visdom_viewer = None @property def project(self): + """ + HyppopyProject instance + + :return: [HyppopyProject] project instance + """ return self._project @project.setter def project(self, value): + """ + Set HyppopyProject instance + + :param value: [HyppopyProject] project instance + """ if isinstance(value, dict): self._project = HyppopyProject(value) elif isinstance(value, HyppopyProject): self._project = value else: msg = "Input error, project_manager of type: {} not allowed!".format(type(value)) LOG.error(msg) raise TypeError(msg) self._check_project() @property def blackbox(self): + """ + Get the BlackboxFunction object. + + :return: [object] BlackboxFunction instance or function + """ return self._blackbox @blackbox.setter def blackbox(self, value): - if isinstance(value, types.FunctionType) or isinstance(value, BlackboxFunction) or isinstance(value, FunctionSimulator): + """ + Set the BlackboxFunction wrapper class encapsulating the loss function or a function accepting a hyperparameter set + and returning a float. + + :return: [object] pointer to blackbox_func + """ + if isinstance(value, types.FunctionType) or isinstance(value, BlackboxFunction) or isinstance(value, FunctionSimulator) or isinstance(value, MPIBlackboxFunction): self._blackbox = value else: self._blackbox = None msg = "Input error, blackbox of type: {} not allowed!".format(type(value)) LOG.error(msg) raise TypeError(msg) @property def best(self): + """ + Returns best parameter set. + + :return: [dict] best parameter set + """ return self._best @best.setter def best(self, value): + """ + Set the best parameter set. + + :param value: [dict] best parameter set + + """ if not isinstance(value, dict): msg = "Input error, best of type: {} not allowed!".format(type(value)) LOG.error(msg) raise TypeError(msg) self._best = value @property def trials(self): + """ + Get the Trials instance. + + :return: [object] Trials instance + """ return self._trials @trials.setter def trials(self, value): + """ + Set the Trials object. + + :param value: [object] Trials instance + """ self._trials = value @property def total_duration(self): + """ + Get total computation duration. + + :return: [float] total computation time + """ return (self._total_duration[0]*86400 + self._total_duration[1] * 3600 + self._total_duration[2] * 60 + self._total_duration[3]) * 1000 + self._total_duration[4] @property def solver_overhead(self): + """ + Get the solver overhead, this is the total time minus the duration of the blackbox function calls. + + :return: [float] solver overhead duration + """ if self._solver_overhead is None: self.__compute_time_statistics() return self._solver_overhead @property def time_per_iteration(self): + """ + Get the mean duration per iteration. + + :return: [float] time per iteration + """ if self._time_per_iteration is None: self.__compute_time_statistics() return self._time_per_iteration @property def accumulated_blackbox_time(self): + """ + Get the summed blackbox function computation time. + + :return: [float] blackbox function computation time + """ if self._accumulated_blackbox_time is None: self.__compute_time_statistics() return self._accumulated_blackbox_time diff --git a/hyppopy/solvers/MPISolverWrapper.py b/hyppopy/solvers/MPISolverWrapper.py new file mode 100644 index 0000000..a0a678f --- /dev/null +++ b/hyppopy/solvers/MPISolverWrapper.py @@ -0,0 +1,171 @@ +# Hyppopy - A Hyper-Parameter Optimization Toolbox +# +# Copyright (c) German Cancer Research Center, +# Division of Medical Image Computing. +# All rights reserved. +# +# This software is distributed WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR +# A PARTICULAR PURPOSE. +# +# See LICENSE +import datetime +import os +import logging + +import numpy as np +from mpi4py import MPI +from hyppopy.globals import DEBUGLEVEL, MPI_TAGS +from hyppopy.MPIBlackboxFunction import MPIBlackboxFunction + +LOG = logging.getLogger(os.path.basename(__file__)) +LOG.setLevel(DEBUGLEVEL) + + +class MPISolverWrapper: + """ + TODO Class description + The MPISolverWrapper class wraps the functionality of solvers in Hyppopy to extend them with MPI functionality. + It builds upon the interface defined by the HyppopySolver class. + """ + def __init__(self, solver=None, mpi_comm=None): + """ + The constructor accepts a HyppopySolver. + + :param solver: [HyppopySolver] solver instance, default=None + :param mpi_comm: [MPI communicator] MPI communicator instance. If None, we create a new MPI.COMM_WORLD, default=None + """ + self._solver = solver + self._mpi_comm = None + if mpi_comm is None: + print('MPISolverWrapper: No mpi_comm given: Using MPI.COMM_WORLD') + self._mpi_comm = MPI.COMM_WORLD + else: + self._mpi_comm = mpi_comm + + @property + def blackbox(self): + """ + Get the BlackboxFunction object. + + :return: [object] BlackboxFunction instance or function of member solver + """ + return self._solver.blackbox + + @blackbox.setter + def blackbox(self, value): + """ + Set the BlackboxFunction wrapper class encapsulating the loss function or a function accepting a hyperparameter + set and returning a float. + If the passed value is not an instance of MPIBlackboxFunction (or a derived class) it will automatically + wrapped by an MPIBackboxFunction. + :return: + """ + if isinstance(value, MPIBlackboxFunction): + self._solver.blackbox = value + else: + self._solver.blackbox = MPIBlackboxFunction(blackbox_func=value, mpi_comm=self._mpi_comm) + + def get_results(self): + """ + Just call get_results of the member solver and return the result. + :return: return value of self._solver.get_results() + """ + # Only rank==0 returns results, the workers return None. + mpi_rank = self._mpi_comm.Get_rank() + if mpi_rank == 0: + return self._solver.get_results() + return None, None + + def run_worker_mode(self): + """ + This function is called if the wrapper should run as a worker for a specific MPI rank. + It receives messages for the following tags: + tag==MPI_SEND_CANDIDATE: parameters for the loss calculation. It param==None, the worker finishes. + It sends messages for the following tags: + tag==MPI_SEND_RESULT: result of an evaluated candidate. + + :return: the evaluated loss of the candidate + """ + rank = self._mpi_comm.Get_rank() + print("Starting worker {}. Waiting for param...".format(rank)) + + cand_results = dict() + + while True: + try: + candidate = self._mpi_comm.recv(source=0, tag=MPI_TAGS.MPI_SEND_CANDIDATE.value) # Wait here till params are received + + if candidate is None: + print("[RECEIVE] Process {} received finish signal.".format(rank)) + return + + # if candidate.ID == 9999: + # comm.gather(losses, root=0) + # continue + + # print("[WORKING] Process {} is actually doing things.".format(rank)) + cand_id = candidate.ID + params = candidate.get_values() + + try: + loss = self._solver.blackbox.blackbox_func(params) + except: + loss = self._solver.blackbox.blackbox_func(**params) + + except Exception as e: + msg = "Error in Worker(rank={}): {}".format(rank, e) + LOG.error(msg) + print(msg) + + loss = np.nan + finally: + cand_results['book_time'] = datetime.datetime.now() + cand_results['loss'] = loss # Write loss to dictionary. This dictionary will be send back to the master via gather + cand_results['refresh_time'] = datetime.datetime.now() + + cand_results['book_time'] = datetime.datetime.now() + + cand_results['loss'] = loss # Write loss to dictionary. This dictionary will be send back to the master via gather + cand_results['refresh_time'] = datetime.datetime.now() + + self._mpi_comm.send((cand_id, cand_results), dest=0, tag=MPI_TAGS.MPI_SEND_RESULTS.value) + + def signal_worker_finished(self): + """ + This function sends data==None to all workers from the master. This is the signal that tells the workers to finish. + + :return: + """ + print('[SEND] signal_worker_finished') + size = self._mpi_comm.Get_size() + for i in range(size - 1): + self._mpi_comm.send(None, dest=i + 1, tag=MPI_TAGS.MPI_SEND_CANDIDATE.value) + + def run(self, *args, **kwargs): + """ + This function starts the optimization process of the underlying solver and takes care of the MPI awareness. + """ + + mpi_rank = self._mpi_comm.Get_rank() + if mpi_rank == 0: + # This is the master process. From here we run the solver and start all the other processes. + self._solver.run(*args, **kwargs) + self.signal_worker_finished() # Tell the workers to finish. + else: + # this script execution should be in worker mode as it is an mpi worker. + self.run_worker_mode() + + def is_master(self): + mpi_rank = self._mpi_comm.Get_rank() + if mpi_rank == 0: + return True + else: + return False + + def is_worker(self): + mpi_rank = self._mpi_comm.Get_rank() + if mpi_rank != 0: + return True + else: + return False diff --git a/hyppopy/solvers/OptunaSolver.py b/hyppopy/solvers/OptunaSolver.py index f02b086..126f455 100644 --- a/hyppopy/solvers/OptunaSolver.py +++ b/hyppopy/solvers/OptunaSolver.py @@ -1,86 +1,150 @@ # Hyppopy - A Hyper-Parameter Optimization Toolbox # # Copyright (c) German Cancer Research Center, # Division of Medical Image Computing. # All rights reserved. # # This software is distributed WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. # # See LICENSE import os import optuna import logging import warnings import numpy as np from pprint import pformat from hyppopy.globals import DEBUGLEVEL from hyppopy.solvers.HyppopySolver import HyppopySolver +from hyppopy.CandidateDescriptor import CandidateDescriptor + LOG = logging.getLogger(os.path.basename(__file__)) LOG.setLevel(DEBUGLEVEL) class OptunaSolver(HyppopySolver): def __init__(self, project=None): + """ + The constructor accepts a HyppopyProject. + + :param project: [HyppopyProject] project instance, default=None + """ HyppopySolver.__init__(self, project) self._searchspace = None + self.candidates_list = list() def define_interface(self): + """ + This function is called when HyppopySolver.__init__ function finished. Child classes need to define their + individual parameter here by calling the _add_member function for each class member variable need to be defined. + Using _add_hyperparameter_signature the structure of a hyperparameter the solver expects must be defined. + Both, members and hyperparameter signatures are later get checked, before executing the solver, ensuring + settings passed fullfill solver needs. + """ self._add_member("max_iterations", int) self._add_hyperparameter_signature(name="domain", dtype=str, options=["uniform", "categorical"]) self._add_hyperparameter_signature(name="data", dtype=list) self._add_hyperparameter_signature(name="type", dtype=type) - def reformat_parameter(self, params): - out_params = {} - for name, value in params.items(): - if self._searchspace[name]["domain"] == "categorical": - out_params[name] = self._searchspace[name]["data"][int(np.round(value))] - else: - if self._searchspace[name]["type"] is int: - out_params[name] = int(np.round(value)) + def get_candidates(self, trial=None): + """ + This function converts the searchspace to a candidate_list that can then be used to distribute via MPI. + + :param searchspace: converted hyperparameter space + """ + + candidates_list = list() + N = self.max_iterations + for n in range(N): + print(n) + # Todo: Ugly hack that does not even work... + from optuna import trial as trial_module + # temp_study = optuna.create_study() + trial_id = self.study._storage.create_new_trial_id(0) + trial = trial_module.Trial(self.study, trial_id) + ## trial.report(result) + ## self._storage.set_trial_state(trial_id, structs.TrialState.COMPLETE) + ## self._log_completed_trial(trial_number, result) + + params = {} + for name, param in self._searchspace.items(): + if param["domain"] == "categorical": + params[name] = trial.suggest_categorical(name, param["data"]) else: - out_params[name] = value - return out_params + params[name] = trial.suggest_uniform(name, param["data"][0], param["data"][1]) + candidates_list.append(CandidateDescriptor(**params)) + + return candidates_list + + N = self.max_iterations + for n in range(N): + params = {} + for name, param in self._searchspace.items(): + if param["domain"] == "categorical": + params[name] = trial.suggest_categorical(name, param["data"]) + else: + params[name] = trial.suggest_uniform(name, param["data"][0], param["data"][1]) + candidates_list.append(CandidateDescriptor(**params)) + + return candidates_list def trial_cache(self, trial): + """ + Optuna specific loss function wrapper + + :param trial: [Trial] instance + + :return: [function] loss function + """ + params = {} + for name, param in self._searchspace.items(): if param["domain"] == "categorical": params[name] = trial.suggest_categorical(name, param["data"]) else: params[name] = trial.suggest_uniform(name, param["data"][0], param["data"][1]) - return self.loss_function(**params) - def loss_function_call(self, params): - for key in params.keys(): - if self.project.get_typeof(key) is int: - params[key] = int(round(params[key])) - return self.blackbox(**params) + return self.loss_function(**params) def execute_solver(self, searchspace): + """ + This function is called immediately after convert_searchspace and get the output of the latter as input. It's + purpose is to call the solver libs main optimization function. + + :param searchspace: converted hyperparameter space + """ LOG.debug("execute_solver using solution space:\n\n\t{}\n".format(pformat(searchspace))) self._searchspace = searchspace try: study = optuna.create_study() study.optimize(self.trial_cache, n_trials=self.max_iterations) self.best = study.best_trial.params except Exception as e: LOG.error("internal error in bayes_opt maximize occured. {}".format(e)) raise BrokenPipeError("internal error in bayes_opt maximize occured. {}".format(e)) def convert_searchspace(self, hyperparameter): + """ + This function gets the unified hyppopy-like parameterspace description as input and, if necessary, should + convert it into a solver lib specific format. The function is invoked when run is called and what it returns + is passed as searchspace argument to the function execute_solver. + + :param hyperparameter: [dict] nested parameter description dict e.g. {'name': {'domain':'uniform', 'data':[0,1], 'type':'float'}, ...} + + :return: [object] converted hyperparameter space + """ LOG.debug("convert input parameter\n\n\t{}\n".format(pformat(hyperparameter))) for name, param in hyperparameter.items(): if param["domain"] != "categorical" and param["domain"] != "uniform": msg = "Warning: Optuna cannot handle {} domain. Only uniform and categorical domains are supported!".format(param["domain"]) warnings.warn(msg) LOG.warning(msg) return hyperparameter diff --git a/hyppopy/solvers/OptunitySolver.py b/hyppopy/solvers/OptunitySolver.py index 2c894af..bfb04b8 100644 --- a/hyppopy/solvers/OptunitySolver.py +++ b/hyppopy/solvers/OptunitySolver.py @@ -1,93 +1,123 @@ # Hyppopy - A Hyper-Parameter Optimization Toolbox # # Copyright (c) German Cancer Research Center, # Division of Medical Image Computing. # All rights reserved. # # This software is distributed WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. # # See LICENSE import os import logging import optunity from pprint import pformat + +from hyppopy.CandidateDescriptor import CandidateDescriptor, CandicateDescriptorWrapper from hyppopy.globals import DEBUGLEVEL LOG = logging.getLogger(os.path.basename(__file__)) LOG.setLevel(DEBUGLEVEL) from hyppopy.solvers.HyppopySolver import HyppopySolver class OptunitySolver(HyppopySolver): def __init__(self, project=None): + """ + The constructor accepts a HyppopyProject. + + :param project: [HyppopyProject] project instance, default=None + """ HyppopySolver.__init__(self, project) def define_interface(self): + """ + This function is called when HyppopySolver.__init__ function finished. Child classes need to define their + individual parameter here by calling the _add_member function for each class member variable need to be defined. + Using _add_hyperparameter_signature the structure of a hyperparameter the solver expects must be defined. + Both, members and hyperparameter signatures are later get checked, before executing the solver, ensuring + settings passed fullfill solver needs. + """ self._add_member("max_iterations", int) self._add_hyperparameter_signature(name="domain", dtype=str, options=["uniform", "categorical"]) self._add_hyperparameter_signature(name="data", dtype=list) self._add_hyperparameter_signature(name="type", dtype=type) - def loss_function_call(self, params): - for key in params.keys(): - if self.project.get_typeof(key) is int: - params[key] = int(round(params[key])) - return self.blackbox(**params) - def execute_solver(self, searchspace): + """ + This function is called immediately after convert_searchspace and get the output of the latter as input. It's + purpose is to call the solver libs main optimization function. + + :param searchspace: converted hyperparameter space + """ LOG.debug("execute_solver using solution space:\n\n\t{}\n".format(pformat(searchspace))) try: self.best, _, _ = optunity.minimize_structured(f=self.loss_function, - num_evals=self.max_iterations, - search_space=searchspace) + num_evals=self.max_iterations, + search_space=searchspace) except Exception as e: LOG.error("internal error in optunity.minimize_structured occured. {}".format(e)) raise BrokenPipeError("internal error in optunity.minimize_structured occured. {}".format(e)) def split_categorical(self, pdict): + """ + This function splits the incoming dict into two parts, categorical only entries and other. + + :param pdict: [dict] input parameter description dict + + :return: [dict],[dict] categorical only, others + """ categorical = {} uniform = {} for name, pset in pdict.items(): for key, value in pset.items(): if key == 'domain' and value == 'categorical': categorical[name] = pset elif key == 'domain': uniform[name] = pset return categorical, uniform def convert_searchspace(self, hyperparameter): + """ + This function gets the unified hyppopy-like parameterspace description as input and, if necessary, should + convert it into a solver lib specific format. The function is invoked when run is called and what it returns + is passed as searchspace argument to the function execute_solver. + + :param hyperparameter: [dict] nested parameter description dict e.g. {'name': {'domain':'uniform', 'data':[0,1], 'type':'float'}, ...} + + :return: [object] converted hyperparameter space + """ LOG.debug("convert input parameter\n\n\t{}\n".format(pformat(hyperparameter))) # split input in categorical and non-categorical data cat, uni = self.split_categorical(hyperparameter) # build up dictionary keeping all non-categorical data uniforms = {} for key, value in uni.items(): for key2, value2 in value.items(): if key2 == 'data': if len(value2) == 3: uniforms[key] = value2[0:2] elif len(value2) == 2: uniforms[key] = value2 else: raise AssertionError("precondition violation, optunity searchspace needs list with left and right range bounds!") if len(cat) == 0: return uniforms # build nested categorical structure inner_level = uniforms for key, value in cat.items(): tmp = {} optunity_space = {} for key2, value2 in value.items(): if key2 == 'data': for elem in value2: tmp[elem] = inner_level optunity_space[key] = tmp inner_level = optunity_space return optunity_space diff --git a/hyppopy/solvers/QuasiRandomsearchSolver.py b/hyppopy/solvers/QuasiRandomsearchSolver.py index b9159ec..4a7e5c4 100644 --- a/hyppopy/solvers/QuasiRandomsearchSolver.py +++ b/hyppopy/solvers/QuasiRandomsearchSolver.py @@ -1,201 +1,222 @@ # Hyppopy - A Hyper-Parameter Optimization Toolbox # # Copyright (c) German Cancer Research Center, # Division of Medical Image Computing. # All rights reserved. # # This software is distributed WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. # # See LICENSE __all__ = ['HaltonSequenceGenerator', 'QuasiRandomSampleGenerator', 'QuasiRandomsearchSolver'] import os import logging import warnings import numpy as np from pprint import pformat from hyppopy.globals import DEBUGLEVEL from hyppopy.solvers.HyppopySolver import HyppopySolver LOG = logging.getLogger(os.path.basename(__file__)) LOG.setLevel(DEBUGLEVEL) class HaltonSequenceGenerator(object): """ This class generates Halton sequences (https://en.wikipedia.org/wiki/Halton_sequence). The class needs a total number of samples and the number of dimensions to generate a quasirandom sequence for each axis. The method get_unit_space returns a sequence list with N_samples for each axis representing N_samples vectors on a unit sphere. """ def __init__(self): pass def __next_prime(self): """ Checks if num is a prime value """ def is_prime(num): for i in range(2, int(num ** 0.5) + 1): if (num % i) == 0: return False return True prime = 3 while 1: if is_prime(prime): yield prime prime += 2 def __vdc(self, n, base): vdc, denom = 0, 1 while n: denom *= base n, remainder = divmod(n, base) vdc += remainder / float(denom) return vdc def get_unit_space(self, N_samples, N_dims): """ Returns a unit space in form of a sequence list keeping N_dims sequences with N_sample samplings. Each sample represents a N_dims dimensional vector on a unit sphere. :param N_samples: [int] Number of samples :param N_dims: [int] Number of dimensions :return: [list] samples list of length N_dims keeping lists each of length N_samples """ seq = [] primeGen = self.__next_prime() next(primeGen) for d in range(N_dims): base = next(primeGen) seq.append([self.__vdc(i, base) for i in range(N_samples)]) return seq class QuasiRandomSampleGenerator(object): """ This class takes care of the hyperparameter space creation and next sample delivery. """ def __init__(self, N_samples=None): self._axis = None self._samples = [] self._numerical = [] self._categorical = [] self._N_samples = N_samples def set_axis(self, name, data, domain, dtype): """ Add an axis description. :param name: [str] axis name :param data: [list] axis range [min, max] :param domain: [str] axis domain :param dtype: [type] axis data type """ if domain == "categorical": if dtype is int: data = [int(i) for i in data] elif dtype is str: data = [str(i) for i in data] elif dtype is float: data = [float(i) for i in data] self._categorical.append({"name": name, "data": data, "type": dtype}) else: self._numerical.append({"name": name, "data": data, "type": dtype, "domain": domain}) def generate_samples(self, N_samples=None): """ This function is called once when the first sample is requested. It generates the halton sequence space. :param N_samples: [int] number of samples """ self._axis = [] if N_samples is None: assert isinstance(self._N_samples, int), "Precondition violation, no number of samples specified!" else: self._N_samples = N_samples axis_samples = {} if len(self._numerical) > 0: generator = HaltonSequenceGenerator() unit_space = generator.get_unit_space(self._N_samples, len(self._numerical)) for n, axis in enumerate(self._numerical): width = abs(axis["data"][1] - axis["data"][0]) unit_space[n] = [x * width for x in unit_space[n]] unit_space[n] = [x + axis["data"][0] for x in unit_space[n]] if axis["type"] is int: unit_space[n] = [int(round(x)) for x in unit_space[n]] axis_samples[axis["name"]] = unit_space[n] else: warnings.warn("No numerical axis defined, this warning can be ignored if searchspace is categorical only, otherwise check if axis was set!") for n in range(self._N_samples): sample = {} for name, data in axis_samples.items(): sample[name] = data[n] for cat in self._categorical: choice = np.random.choice(len(cat["data"]), 1)[0] sample[cat["name"]] = cat["data"][choice] self._samples.append(sample) def next(self): """ Returns the next sample. Returns None if all samples are requested. :return: [dict] sample dict {'name':value, ...} """ if len(self._samples) == 0: self.generate_samples() if len(self._samples) == 0: return None next_index = np.random.choice(len(self._samples), 1)[0] sample = self._samples.pop(next_index) return sample class QuasiRandomsearchSolver(HyppopySolver): """ The QuasiRandomsearchSolver class implements a quasi randomsearch optimization. The quasi randomsearch supports categorical and uniform sampling. The solver defines a Halton Sequence distributed hyperparameter space. This means a rather evenly distributed space sampling but no real randomness. """ def __init__(self, project=None): + """ + The constructor accepts a HyppopyProject. + + :param project: [HyppopyProject] project instance, default=None + """ HyppopySolver.__init__(self, project) self._sampler = None def define_interface(self): + """ + This function is called when HyppopySolver.__init__ function finished. Child classes need to define their + individual parameter here by calling the _add_member function for each class member variable need to be defined. + Using _add_hyperparameter_signature the structure of a hyperparameter the solver expects must be defined. + Both, members and hyperparameter signatures are later get checked, before executing the solver, ensuring + settings passed fullfill solver needs. + """ self._add_member("max_iterations", int) self._add_hyperparameter_signature(name="domain", dtype=str, options=["uniform", "categorical"]) self._add_hyperparameter_signature(name="data", dtype=list) self._add_hyperparameter_signature(name="type", dtype=type) - def loss_function_call(self, params): - loss = self.blackbox(**params) - if loss is None: - return np.nan - return loss - def execute_solver(self, searchspace): + """ + This function is called immediately after convert_searchspace and get the output of the latter as input. It's + purpose is to call the solver libs main optimization function. + + :param searchspace: converted hyperparameter space + """ N = self.max_iterations self._sampler = QuasiRandomSampleGenerator(N) for name, axis in searchspace.items(): self._sampler.set_axis(name, axis["data"], axis["domain"], axis["type"]) try: for n in range(N): params = self._sampler.next() if params is None: break self.loss_function(**params) except Exception as e: msg = "internal error in randomsearch execute_solver occured. {}".format(e) LOG.error(msg) raise BrokenPipeError(msg) self.best = self._trials.argmin def convert_searchspace(self, hyperparameter): + """ + This function gets the unified hyppopy-like parameterspace description as input and, if necessary, should + convert it into a solver lib specific format. The function is invoked when run is called and what it returns + is passed as searchspace argument to the function execute_solver. + + :param hyperparameter: [dict] nested parameter description dict e.g. {'name': {'domain':'uniform', 'data':[0,1], 'type':'float'}, ...} + + :return: [object] converted hyperparameter space + """ LOG.debug("convert input parameter\n\n\t{}\n".format(pformat(hyperparameter))) return hyperparameter diff --git a/hyppopy/solvers/RandomsearchSolver.py b/hyppopy/solvers/RandomsearchSolver.py index abbf85d..60cab3d 100644 --- a/hyppopy/solvers/RandomsearchSolver.py +++ b/hyppopy/solvers/RandomsearchSolver.py @@ -1,172 +1,207 @@ # Hyppopy - A Hyper-Parameter Optimization Toolbox # # Copyright (c) German Cancer Research Center, # Division of Medical Image Computing. # All rights reserved. # # This software is distributed WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. # # See LICENSE +from hyppopy.CandidateDescriptor import CandidateDescriptor __all__ = ['RandomsearchSolver', 'draw_uniform_sample', 'draw_normal_sample', 'draw_loguniform_sample', 'draw_categorical_sample', 'draw_sample'] import os import copy import random import logging import numpy as np from pprint import pformat from hyppopy.globals import DEBUGLEVEL from hyppopy.solvers.HyppopySolver import HyppopySolver LOG = logging.getLogger(os.path.basename(__file__)) LOG.setLevel(DEBUGLEVEL) def draw_uniform_sample(param): """ Function draws a random sample from a uniform range :param param: [dict] input hyperparameter discription :return: random sample value of type data['type'] """ assert param['type'] is not str, "cannot sample a string list!" assert param['data'][0] < param['data'][1], "precondition violation: data[0] > data[1]!" s = random.random() s *= np.abs(param['data'][1] - param['data'][0]) s += param['data'][0] if param['type'] is int: s = int(np.round(s)) if s < param['data'][0]: s = int(param['data'][0]) if s > param['data'][1]: s = int(param['data'][1]) return s def draw_normal_sample(param): """ Function draws a random sample from a normal distributed range :param param: [dict] input hyperparameter discription :return: random sample value of type data['type'] """ assert param['type'] is not str, "cannot sample a string list!" assert param['data'][0] < param['data'][1], "precondition violation: data[0] > data[1]!" mu = (param['data'][1] - param['data'][0]) / 2 sigma = mu / 3 s = np.random.normal(loc=param['data'][0] + mu, scale=sigma) if s > param['data'][1]: s = param['data'][1] if s < param['data'][0]: s = param['data'][0] s = float(s) if param["type"] is int: s = int(np.round(s)) return s def draw_loguniform_sample(param): """ Function draws a random sample from a logarithmic distributed range :param param: [dict] input hyperparameter discription :return: random sample value of type data['type'] """ assert param['type'] is not str, "cannot sample a string list!" assert param['data'][0] < param['data'][1], "precondition violation: data[0] > data[1]!" p = copy.deepcopy(param) p['data'][0] = np.log(param['data'][0]) p['data'][1] = np.log(param['data'][1]) assert p['data'][0] is not np.nan, "Precondition violation, left bound input error, results in nan!" assert p['data'][1] is not np.nan, "Precondition violation, right bound input error, results in nan!" x = draw_uniform_sample(p) s = np.exp(x) if s > param['data'][1]: s = param['data'][1] if s < param['data'][0]: s = param['data'][0] return s def draw_categorical_sample(param): """ Function draws a random sample from a categorical list :param param: [dict] input hyperparameter discription :return: random sample value of type data['type'] """ return random.sample(param['data'], 1)[0] def draw_sample(param): """ Function draws a sample from the input hyperparameter descriptor depending on it's domain :param param: [dict] input hyperparameter discription :return: random sample value of type data['type'] """ assert isinstance(param, dict), "input error, hyperparam descriptors of type {} not allowed!".format(type(param)) if param['domain'] == "uniform": return draw_uniform_sample(param) elif param['domain'] == "normal": return draw_normal_sample(param) elif param['domain'] == "loguniform": return draw_loguniform_sample(param) elif param['domain'] == "categorical": return draw_categorical_sample(param) else: raise LookupError("Unknown domain {}".format(param['domain'])) class RandomsearchSolver(HyppopySolver): """ The RandomsearchSolver class implements a randomsearch optimization. The randomsearch supports categorical, uniform, normal and loguniform sampling. The solver draws an independent sample from the parameter space each iteration. """ def __init__(self, project=None): + """ + The constructor accepts a HyppopyProject. + + :param project: [HyppopyProject] project instance, default=None + """ HyppopySolver.__init__(self, project) def define_interface(self): + """ + This function is called when HyppopySolver.__init__ function finished. Child classes need to define their + individual parameter here by calling the _add_member function for each class member variable need to be defined. + Using _add_hyperparameter_signature the structure of a hyperparameter the solver expects must be defined. + Both, members and hyperparameter signatures are later get checked, before executing the solver, ensuring + settings passed fullfill solver needs. + """ self._add_member("max_iterations", int) self._add_hyperparameter_signature(name="domain", dtype=str, options=["uniform", "normal", "loguniform", "categorical"]) self._add_hyperparameter_signature(name="data", dtype=list) self._add_hyperparameter_signature(name="type", dtype=type) - def loss_function_call(self, params): - loss = self.blackbox(**params) - if loss is None: - return np.nan - return loss + def get_candidates(self, searchspace): + """ + This function converts the searchspace to a candidate_list that can then be used to distribute via MPI. - def execute_solver(self, searchspace): + :param searchspace: converted hyperparameter space + """ + candidates_list = list() N = self.max_iterations + for n in range(N): + params = {} + for name, p in searchspace.items(): + params[name] = draw_sample(p) + candidates_list.append(CandidateDescriptor(**params)) + + return candidates_list + + def execute_solver(self, searchspace): + """ + This function is called immediately after convert_searchspace and get the output of the latter as input. It's + purpose is to call the solver libs main optimization function. + + :param searchspace: converted hyperparameter space + """ + + candidates = self.get_candidates(searchspace) try: - for n in range(N): - params = {} - for name, p in searchspace.items(): - params[name] = draw_sample(p) - self.loss_function(**params) + self.loss_function_batch(candidates) except Exception as e: msg = "internal error in randomsearch execute_solver occured. {}".format(e) LOG.error(msg) raise BrokenPipeError(msg) self.best = self._trials.argmin def convert_searchspace(self, hyperparameter): + """ + This function gets the unified hyppopy-like parameterspace description as input and, if necessary, should + convert it into a solver lib specific format. The function is invoked when run is called and what it returns + is passed as searchspace argument to the function execute_solver. + + :param hyperparameter: [dict] nested parameter description dict e.g. {'name': {'domain':'uniform', 'data':[0,1], 'type':'float'}, ...} + + :return: [object] converted hyperparameter space + """ LOG.debug("convert input parameter\n\n\t{}\n".format(pformat(hyperparameter))) return hyperparameter diff --git a/hyppopy/tests/test_hyperoptsolver.py b/hyppopy/tests/test_hyperoptsolver.py index 8552450..a44bb68 100644 --- a/hyppopy/tests/test_hyperoptsolver.py +++ b/hyppopy/tests/test_hyperoptsolver.py @@ -1,103 +1,188 @@ # Hyppopy - A Hyper-Parameter Optimization Toolbox # # Copyright (c) German Cancer Research Center, # Division of Medical Image Computing. # All rights reserved. # # This software is distributed WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. # # See LICENSE import unittest from hyppopy.solvers.HyperoptSolver import * from hyppopy.FunctionSimulator import FunctionSimulator from hyppopy.HyppopyProject import HyppopyProject class HyperoptSolverTestSuite(unittest.TestCase): def setUp(self): pass def test_solver_complete(self): config = { "hyperparameter": { "axis_00": { "domain": "uniform", "data": [300, 700], "type": float }, "axis_01": { "domain": "uniform", "data": [0, 0.8], "type": float }, "axis_02": { "domain": "uniform", "data": [3.5, 6.5], "type": float } }, "max_iterations": 500 } project = HyppopyProject(config) solver = HyperoptSolver(project) vfunc = FunctionSimulator() vfunc.load_default() solver.blackbox = vfunc solver.run(print_stats=False) df, best = solver.get_results() self.assertTrue(575 <= best['axis_00'] <= 585) self.assertTrue(0.1 <= best['axis_01'] <= 0.8) self.assertTrue(4.7 <= best['axis_02'] <= 5.3) for status in df['status']: self.assertTrue(status) for loss in df['losses']: self.assertTrue(isinstance(loss, float)) def test_solver_normal(self): config = { "hyperparameter": { "axis_00": { "domain": "normal", "data": [500, 650], "type": float }, "axis_01": { "domain": "normal", "data": [0.1, 0.8], "type": float }, "axis_02": { "domain": "normal", "data": [4.5, 5.5], "type": float } }, "max_iterations": 500, } project = HyppopyProject(config) solver = HyperoptSolver(project) vfunc = FunctionSimulator() vfunc.load_default() solver.blackbox = vfunc solver.run(print_stats=False) df, best = solver.get_results() self.assertTrue(575 <= best['axis_00'] <= 585) self.assertTrue(0.1 <= best['axis_01'] <= 0.8) self.assertTrue(4.7 <= best['axis_02'] <= 5.3) for status in df['status']: self.assertTrue(status) for loss in df['losses']: self.assertTrue(isinstance(loss, float)) + def test_solver_loguniform(self): + config = { + "hyperparameter": { + "axis_00": { + "domain": "normal", + "data": [500, 650], + "type": float + }, + "axis_01": { + "domain": "loguniform", + "data": [0.001, 1], + "type": float + }, + "axis_02": { + "domain": "normal", + "data": [4.5, 5.5], + "type": float + } + }, + "max_iterations": 500, + } + + project = HyppopyProject(config) + solver = HyperoptSolver(project) + vfunc = FunctionSimulator() + vfunc.load_default() + solver.blackbox = vfunc + solver.run(print_stats=False) + df, best = solver.get_results() + self.assertTrue(575 <= best['axis_00'] <= 585) + self.assertTrue(0.001 <= best['axis_01'] <= 1.0) + self.assertTrue(4.7 <= best['axis_02'] <= 5.3) + + for status in df['status']: + self.assertTrue(status) + for loss in df['losses']: + self.assertTrue(isinstance(loss, float)) + + def test_categorical(self): + config = { + "hyperparameter": { + "C": { + "domain": "uniform", + "data": [1, 20], + "type": int + }, + "gamma": { + "domain": "loguniform", + "data": [0.0, 20.0], + "type": float + }, + "kernel": { + "domain": "categorical", + "data": ["linear", "sigmoid", "poly", "rbf"], + "type": str + }, + "with_ovr": { + "domain": "categorical", + "data": [True, False], + "type": bool + } + }, + "max_iterations": 300 + } + project = HyppopyProject(config=config) + from sklearn.svm import SVC + from sklearn.datasets import load_iris + from sklearn.model_selection import cross_val_score + iris_data = load_iris() + data = [iris_data.data, iris_data.target] + + def my_loss_function(data, params): + if params["with_ovr"]: + params["decision_function_shape"] = "ovr" + else: + params["decision_function_shape"] = "ovo" + del params["with_ovr"] + clf = SVC(**params) + return -cross_val_score(estimator=clf, X=data[0], y=data[1], cv=3).mean() + + blackbox = BlackboxFunction(blackbox_func=my_loss_function, data=data) + solver = HyperoptSolver(project=project) + solver.blackbox = blackbox + solver.run() + if __name__ == '__main__': unittest.main() diff --git a/hyppopy/tests/test_hyppopysolver.py b/hyppopy/tests/test_hyppopysolver.py new file mode 100644 index 0000000..1a24a96 --- /dev/null +++ b/hyppopy/tests/test_hyppopysolver.py @@ -0,0 +1,344 @@ +# Hyppopy - A Hyper-Parameter Optimization Toolbox +# +# Copyright (c) German Cancer Research Center, +# Division of Medical Image Computing. +# All rights reserved. +# +# This software is distributed WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR +# A PARTICULAR PURPOSE. +# +# See LICENSE + +import unittest + +from hyppopy.HyppopyProject import HyppopyProject +from hyppopy.solvers.HyppopySolver import HyppopySolver + + +class FooSolver1(HyppopySolver): + + def __init__(self, project=None): + HyppopySolver.__init__(self, project) + self._searchspace = None + + +class FooSolver2(HyppopySolver): + + def __init__(self, project=None): + HyppopySolver.__init__(self, project) + self._searchspace = None + + def convert_searchspace(self, hyperparameter): + pass + + +class FooSolver3(HyppopySolver): + + def __init__(self, project=None): + HyppopySolver.__init__(self, project) + self._searchspace = None + + def convert_searchspace(self, hyperparameter): + pass + + def define_interface(self): + pass + + +class FooSolver4(HyppopySolver): + + def __init__(self, project=None): + HyppopySolver.__init__(self, project) + self._searchspace = None + + def convert_searchspace(self, hyperparameter): + pass + + def define_interface(self): + pass + + +class GooSolver1(HyppopySolver): + def __init__(self, project=None): + HyppopySolver.__init__(self, project) + self._searchspace = None + + def convert_searchspace(self, hyperparameter): + pass + + def define_interface(self): + self._add_member("max_iterations", int, 1.0, 100) + + def execute_solver(self, searchspace): + pass + + +class GooSolver2(HyppopySolver): + def __init__(self, project=None): + HyppopySolver.__init__(self, project) + self._searchspace = None + + def convert_searchspace(self, hyperparameter): + pass + + def define_interface(self): + self._add_member("max_iterations", int, 100, 5.0) + + def execute_solver(self, searchspace): + pass + + +class TestSolver1(HyppopySolver): + def __init__(self, project=None): + config = { + "hyperparameter": { + "gamma": { + "domain": "uniform", + "data": [0.0001, 20.0], + "type": float + }, + "kernel": { + "domain": "categorical", + "data": ["linear", "sigmoid", "poly", "rbf"], + "type": str + } + }, + "foo1": 300, + "goo": 1.0 + } + project = HyppopyProject(config) + + HyppopySolver.__init__(self, project) + self._searchspace = None + + def convert_searchspace(self, hyperparameter): + pass + + def execute_solver(self, searchspace): + pass + + def define_interface(self): + self._add_member("foo", int) + self._add_member("goo", float) + self._add_hyperparameter_signature(name="domain", dtype=str, + options=["uniform", "categorical"]) + self._add_hyperparameter_signature(name="data", dtype=list) + self._add_hyperparameter_signature(name="type", dtype=type) + + +class TestSolver2(HyppopySolver): + def __init__(self, project=None): + config = { + "hyperparameter": { + "gamma": { + "domain": "normal", + "data": [0.0001, 20.0], + "type": float + }, + "kernel": { + "domain": "categorical", + "data": ["linear", "sigmoid", "poly", "rbf"], + "type": str + } + }, + "foo": 300, + "goo": 1.0 + } + project = HyppopyProject(config) + + HyppopySolver.__init__(self, project) + self._searchspace = None + + def convert_searchspace(self, hyperparameter): + pass + + def execute_solver(self, searchspace): + pass + + def define_interface(self): + self._add_member("foo", int) + self._add_member("goo", float) + self._add_hyperparameter_signature(name="domain", dtype=str, + options=["uniform", "categorical"]) + self._add_hyperparameter_signature(name="data", dtype=list) + self._add_hyperparameter_signature(name="type", dtype=type) + + +class TestSolver3(HyppopySolver): + def __init__(self, project=None): + config = { + "hyperparameter": { + "gamma": { + "domain": 100, + "data": [0.0001, 20.0], + "type": float + }, + "kernel": { + "domain": "categorical", + "data": ["linear", "sigmoid", "poly", "rbf"], + "type": str + } + }, + "foo": 300, + "goo": 1.0 + } + project = HyppopyProject(config) + + HyppopySolver.__init__(self, project) + self._searchspace = None + + def convert_searchspace(self, hyperparameter): + pass + + def execute_solver(self, searchspace): + pass + + def define_interface(self): + self._add_member("foo", int) + self._add_member("goo", float) + self._add_hyperparameter_signature(name="domain", dtype=str, + options=["uniform", "categorical"]) + self._add_hyperparameter_signature(name="data", dtype=list) + self._add_hyperparameter_signature(name="type", dtype=type) + + +class TestSolver4(HyppopySolver): + def __init__(self, project=None): + config = { + "hyperparameter": { + "gamma": { + "domina": "uniform", + "data": [0.0001, 20.0], + "type": float + }, + "kernel": { + "domain": "categorical", + "data": ["linear", "sigmoid", "poly", "rbf"], + "type": str + } + }, + "foo": 300, + "goo": 1.0 + } + project = HyppopyProject(config) + + HyppopySolver.__init__(self, project) + self._searchspace = None + + def convert_searchspace(self, hyperparameter): + pass + + def execute_solver(self, searchspace): + pass + + def define_interface(self): + self._add_member("foo", int) + self._add_member("goo", float) + self._add_hyperparameter_signature(name="domain", dtype=str, + options=["uniform", "categorical"]) + self._add_hyperparameter_signature(name="data", dtype=list) + self._add_hyperparameter_signature(name="type", dtype=type) + + +class TestRunSolver1(HyppopySolver): + def __init__(self, project=None): + project = HyppopyProject({}) + + HyppopySolver.__init__(self, project) + self._searchspace = None + + def convert_searchspace(self, hyperparameter): + raise EnvironmentError("ForTesting") + + def execute_solver(self, searchspace): + pass + + def define_interface(self): + pass + + +class TestRunSolver2(HyppopySolver): + def __init__(self, project=None): + project = HyppopyProject({}) + + HyppopySolver.__init__(self, project) + self._searchspace = None + + def convert_searchspace(self, hyperparameter): + pass + + def execute_solver(self, searchspace): + raise EnvironmentError("ForTesting") + + def define_interface(self): + pass + + +class TestLossFuncSolver1(HyppopySolver): + def __init__(self, project=None): + project = HyppopyProject({}) + + HyppopySolver.__init__(self, project) + self._searchspace = None + + def convert_searchspace(self, hyperparameter): + pass + + def execute_solver(self, searchspace): + self.loss_function(**{}) + + def define_interface(self): + pass + + +class TestLossFuncSolver2(HyppopySolver): + def __init__(self, project=None): + project = HyppopyProject({}) + + HyppopySolver.__init__(self, project) + self._searchspace = None + + def convert_searchspace(self, hyperparameter): + pass + + def execute_solver(self, searchspace): + self.loss_function(**{}) + + def define_interface(self): + pass + + +class HyppopySolverTestSuite(unittest.TestCase): + + def setUp(self): + pass + + def test_class(self): + self.assertRaises(NotImplementedError, HyppopySolver) + self.assertRaises(NotImplementedError, FooSolver1) + self.assertRaises(NotImplementedError, FooSolver2) + foo = FooSolver4() + self.assertRaises(NotImplementedError, foo.execute_solver, {}) + + self.assertRaises(AssertionError, GooSolver1) + self.assertRaises(AssertionError, GooSolver2) + + def test_check_project(self): + self.assertRaises(LookupError, TestSolver1) + self.assertRaises(LookupError, TestSolver2) + self.assertRaises(TypeError, TestSolver3) + self.assertRaises(LookupError, TestSolver4) + + def test_run(self): + solver = TestRunSolver1() + self.assertRaises(AssertionError, solver.run) + solver = TestRunSolver2() + self.assertRaises(AssertionError, solver.run) + self.assertRaises(TypeError, solver.project, 100) + self.assertRaises(TypeError, solver.blackbox, 100) + self.assertRaises(TypeError, solver.best, 100) + + def test_lossfunccall(self): + TestLossFuncSolver1().run(print_stats=False) + TestLossFuncSolver2().run(print_stats=False) diff --git a/hyppopy/tests/test_randomsearchsolver.py b/hyppopy/tests/test_randomsearchsolver.py index 0be138c..99ba381 100644 --- a/hyppopy/tests/test_randomsearchsolver.py +++ b/hyppopy/tests/test_randomsearchsolver.py @@ -1,165 +1,165 @@ # Hyppopy - A Hyper-Parameter Optimization Toolbox # # Copyright (c) German Cancer Research Center, # Division of Medical Image Computing. # All rights reserved. # # This software is distributed WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. # # See LICENSE import unittest import numpy as np import matplotlib.pylab as plt from hyppopy.solvers.RandomsearchSolver import * from hyppopy.FunctionSimulator import FunctionSimulator from hyppopy.HyppopyProject import HyppopyProject class RandomsearchTestSuite(unittest.TestCase): def setUp(self): pass def test_draw_uniform_sample(self): param = {"data": [0, 1, 10], "type": float} values = [] for i in range(10000): values.append(draw_uniform_sample(param)) self.assertTrue(0 <= values[-1] <= 1) self.assertTrue(isinstance(values[-1], float)) - hist = plt.hist(values, bins=10, normed=True) + hist = plt.hist(values, bins=10, density=True) std = np.std(hist[0]) mean = np.mean(hist[0]) self.assertTrue(std < 0.05) self.assertTrue(0.9 < mean < 1.1) param = {"data": [0, 10, 11], "type": int} values = [] for i in range(10000): values.append(draw_uniform_sample(param)) self.assertTrue(0 <= values[-1] <= 10) self.assertTrue(isinstance(values[-1], int)) - hist = plt.hist(values, bins=11, normed=True) + hist = plt.hist(values, bins=11, density=True) std = np.std(hist[0]) mean = np.mean(hist[0]) self.assertTrue(std < 0.05) self.assertTrue(0.09 < mean < 0.11) def test_draw_normal_sample(self): param = {"data": [0, 10, 11], "type": int} values = [] for i in range(10000): values.append(draw_normal_sample(param)) self.assertTrue(0 <= values[-1] <= 10) self.assertTrue(isinstance(values[-1], int)) - hist = plt.hist(values, bins=11, normed=True) + hist = plt.hist(values, bins=11, density=True) for i in range(1, 5): self.assertTrue(hist[0][i-1]-hist[0][i] < 0) for i in range(5, 10): self.assertTrue(hist[0][i] - hist[0][i+1] > 0) def test_draw_loguniform_sample(self): param = {"data": [1, 1000, 11], "type": float} values = [] for i in range(10000): values.append(draw_loguniform_sample(param)) self.assertTrue(1 <= values[-1] <= 1000) self.assertTrue(isinstance(values[-1], float)) - hist = plt.hist(values, bins=11, normed=True) + hist = plt.hist(values, bins=11, density=True) for i in range(4): self.assertTrue(hist[0][i] > hist[0][i+1]) self.assertTrue((hist[0][i] - hist[0][i+1]) > 0) def test_draw_categorical_sample(self): param = {"data": [1, 2, 3], "type": int} values = [] for i in range(10000): values.append(draw_categorical_sample(param)) self.assertTrue(values[-1] == 1 or values[-1] == 2 or values[-1] == 3) self.assertTrue(isinstance(values[-1], int)) - hist = plt.hist(values, bins=3, normed=True) + hist = plt.hist(values, bins=3, density=True) for i in range(3): self.assertTrue(0.45 < hist[0][i] < 0.55) def test_solver_uniform(self): config = { "hyperparameter": { "axis_00": { "domain": "uniform", "data": [0, 800], "type": float }, "axis_01": { "domain": "uniform", "data": [-1, 1], "type": float }, "axis_02": { "domain": "uniform", "data": [0, 10], "type": float } }, "max_iterations": 300 } project = HyppopyProject(config) solver = RandomsearchSolver(project) vfunc = FunctionSimulator() vfunc.load_default() solver.blackbox = vfunc solver.run(print_stats=False) df, best = solver.get_results() self.assertTrue(0 <= best['axis_00'] <= 800) self.assertTrue(-1 <= best['axis_01'] <= 1) self.assertTrue(0 <= best['axis_02'] <= 10) for status in df['status']: self.assertTrue(status) for loss in df['losses']: self.assertTrue(isinstance(loss, float)) def test_solver_normal(self): config = { "hyperparameter": { "axis_00": { "domain": "normal", "data": [500, 650], "type": float }, "axis_01": { "domain": "normal", "data": [0, 1], "type": float }, "axis_02": { "domain": "normal", "data": [4, 5], "type": float } }, "max_iterations": 500, } solver = RandomsearchSolver(config) vfunc = FunctionSimulator() vfunc.load_default() solver.blackbox = vfunc solver.run(print_stats=False) df, best = solver.get_results() self.assertTrue(500 <= best['axis_00'] <= 650) self.assertTrue(0 <= best['axis_01'] <= 1) self.assertTrue(4 <= best['axis_02'] <= 5) for status in df['status']: self.assertTrue(status) for loss in df['losses']: self.assertTrue(isinstance(loss, float)) if __name__ == '__main__': unittest.main() diff --git a/hyppopy/tests/test_solverpool.py b/hyppopy/tests/test_solverpool.py new file mode 100644 index 0000000..9086a05 --- /dev/null +++ b/hyppopy/tests/test_solverpool.py @@ -0,0 +1,289 @@ +# Hyppopy - A Hyper-Parameter Optimization Toolbox +# +# Copyright (c) German Cancer Research Center, +# Division of Medical Image Computing. +# All rights reserved. +# +# This software is distributed WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR +# A PARTICULAR PURPOSE. +# +# See LICENSE + +import unittest + +from hyppopy.SolverPool import SolverPool +from hyppopy.HyppopyProject import HyppopyProject +from hyppopy.FunctionSimulator import FunctionSimulator +from hyppopy.solvers.HyperoptSolver import HyperoptSolver +from hyppopy.solvers.OptunitySolver import OptunitySolver +from hyppopy.solvers.OptunaSolver import OptunaSolver +from hyppopy.solvers.RandomsearchSolver import RandomsearchSolver +from hyppopy.solvers.QuasiRandomsearchSolver import QuasiRandomsearchSolver +from hyppopy.solvers.GridsearchSolver import GridsearchSolver + + +class SolverPoolTestSuite(unittest.TestCase): + + def setUp(self): + pass + + def test_PoolContent(self): + names = SolverPool.get_solver_names() + self.assertTrue("hyperopt" in names) + self.assertTrue("optunity" in names) + self.assertTrue("optuna" in names) + self.assertTrue("randomsearch" in names) + self.assertTrue("quasirandomsearch" in names) + self.assertTrue("gridsearch" in names) + + def test_getHyperoptSolver(self): + config = { + "hyperparameter": { + "axis_00": { + "domain": "uniform", + "data": [300, 700], + "type": float + }, + "axis_01": { + "domain": "uniform", + "data": [0, 0.8], + "type": float + }, + "axis_02": { + "domain": "uniform", + "data": [3.5, 6.5], + "type": float + } + }, + "max_iterations": 500 + } + + project = HyppopyProject(config) + solver = SolverPool.get("hyperopt", project) + self.assertTrue(isinstance(solver, HyperoptSolver)) + vfunc = FunctionSimulator() + vfunc.load_default() + solver.blackbox = vfunc + solver.run(print_stats=False) + df, best = solver.get_results() + self.assertTrue(300 <= best['axis_00'] <= 700) + self.assertTrue(0 <= best['axis_01'] <= 0.8) + self.assertTrue(3.5 <= best['axis_02'] <= 6.5) + + for status in df['status']: + self.assertTrue(status) + for loss in df['losses']: + self.assertTrue(isinstance(loss, float)) + + def test_getOptunitySolver(self): + config = { + "hyperparameter": { + "axis_00": { + "domain": "uniform", + "data": [300, 800], + "type": float + }, + "axis_01": { + "domain": "uniform", + "data": [-1, 1], + "type": float + }, + "axis_02": { + "domain": "uniform", + "data": [0, 10], + "type": float + } + }, + "max_iterations": 100 + } + + project = HyppopyProject(config) + solver = SolverPool.get("optunity", project) + self.assertTrue(isinstance(solver, OptunitySolver)) + vfunc = FunctionSimulator() + vfunc.load_default() + solver.blackbox = vfunc + solver.run(print_stats=False) + df, best = solver.get_results() + self.assertTrue(300 <= best['axis_00'] <= 800) + self.assertTrue(-1 <= best['axis_01'] <= 1) + self.assertTrue(0 <= best['axis_02'] <= 10) + + for status in df['status']: + self.assertTrue(status) + for loss in df['losses']: + self.assertTrue(isinstance(loss, float)) + + def test_getOptunaSolver(self): + config = { + "hyperparameter": { + "axis_00": { + "domain": "uniform", + "data": [300, 800], + "type": float + }, + "axis_01": { + "domain": "uniform", + "data": [-1, 1], + "type": float + }, + "axis_02": { + "domain": "uniform", + "data": [0, 10], + "type": float + } + }, + "max_iterations": 100 + } + + project = HyppopyProject(config) + solver = SolverPool.get("optuna", project) + self.assertTrue(isinstance(solver, OptunaSolver)) + vfunc = FunctionSimulator() + vfunc.load_default() + solver.blackbox = vfunc + solver.run(print_stats=False) + df, best = solver.get_results() + self.assertTrue(300 <= best['axis_00'] <= 800) + self.assertTrue(-1 <= best['axis_01'] <= 1) + self.assertTrue(0 <= best['axis_02'] <= 10) + + for status in df['status']: + self.assertTrue(status) + for loss in df['losses']: + self.assertTrue(isinstance(loss, float)) + + def test_getRandomsearchSolver(self): + config = { + "hyperparameter": { + "axis_00": { + "domain": "uniform", + "data": [0, 800], + "type": float + }, + "axis_01": { + "domain": "uniform", + "data": [-1, 1], + "type": float + }, + "axis_02": { + "domain": "uniform", + "data": [0, 10], + "type": float + } + }, + "max_iterations": 300 + } + + project = HyppopyProject(config) + solver = SolverPool.get("randomsearch", project) + self.assertTrue(isinstance(solver, RandomsearchSolver)) + vfunc = FunctionSimulator() + vfunc.load_default() + solver.blackbox = vfunc + solver.run(print_stats=False) + df, best = solver.get_results() + self.assertTrue(0 <= best['axis_00'] <= 800) + self.assertTrue(-1 <= best['axis_01'] <= 1) + self.assertTrue(0 <= best['axis_02'] <= 10) + + for status in df['status']: + self.assertTrue(status) + for loss in df['losses']: + self.assertTrue(isinstance(loss, float)) + + def test_getQuasiRandomsearchSolver(self): + config = { + "hyperparameter": { + "axis_00": { + "domain": "uniform", + "data": [0, 800], + "type": float + }, + "axis_01": { + "domain": "uniform", + "data": [-1, 1], + "type": float + }, + "axis_02": { + "domain": "uniform", + "data": [0, 10], + "type": float + } + }, + "max_iterations": 300 + } + + project = HyppopyProject(config) + solver = SolverPool.get("quasirandomsearch", project) + self.assertTrue(isinstance(solver, QuasiRandomsearchSolver)) + vfunc = FunctionSimulator() + vfunc.load_default() + solver.blackbox = vfunc + solver.run(print_stats=False) + df, best = solver.get_results() + self.assertTrue(0 <= best['axis_00'] <= 800) + self.assertTrue(-1 <= best['axis_01'] <= 1) + self.assertTrue(0 <= best['axis_02'] <= 10) + + for status in df['status']: + self.assertTrue(status) + for loss in df['losses']: + self.assertTrue(isinstance(loss, float)) + + def test_getGridsearchSolver(self): + config = { + "hyperparameter": { + "value 1": { + "domain": "uniform", + "data": [0, 20], + "type": int, + "frequency": 11 + }, + "value 2": { + "domain": "normal", + "data": [0, 20.0], + "type": float, + "frequency": 11 + }, + "value 3": { + "domain": "loguniform", + "data": [1, 10000], + "type": float, + "frequency": 11 + }, + "categorical": { + "domain": "categorical", + "data": ["a", "b"], + "type": str, + "frequency": 1 + } + }} + res_labels = ['value 1', 'value 2', 'value 3', 'categorical'] + res_values = [[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20], + [0.0, 5.467452952462635, 8.663855974622837, 9.755510546899107, 9.973002039367397, 10.0, + 10.026997960632603, 10.244489453100893, 11.336144025377163, 14.532547047537365, 20.0], + [1.0, 2.51188643150958, 6.309573444801933, 15.848931924611136, 39.810717055349734, + 100.00000000000004, 251.18864315095806, 630.9573444801938, 1584.8931924611143, + 3981.071705534977, 10000.00000000001], + ['a', 'b']] + project = HyppopyProject(config) + solver = SolverPool.get("gridsearch", project) + self.assertTrue(isinstance(solver, GridsearchSolver)) + searchspace = solver.convert_searchspace(config["hyperparameter"]) + for n in range(len(res_labels)): + self.assertEqual(res_labels[n], searchspace[0][n]) + for i in range(3): + self.assertAlmostEqual(res_values[i], searchspace[1][i]) + self.assertEqual(res_values[3], searchspace[1][3]) + + def test_projectNone(self): + solver = SolverPool.get("hyperopt") + solver = SolverPool.get("optunity") + solver = SolverPool.get("optuna") + solver = SolverPool.get("randomsearch") + solver = SolverPool.get("quasirandomsearch") + solver = SolverPool.get("gridsearch") + + self.assertRaises(AssertionError, SolverPool.get, "foo") diff --git a/mpiplayground.py b/mpiplayground.py new file mode 100644 index 0000000..185e5c9 --- /dev/null +++ b/mpiplayground.py @@ -0,0 +1,78 @@ +# DKFZ +# +# +# Copyright (c) German Cancer Research Center, +# Division of Medical Image Computing. +# All rights reserved. +# +# This software is distributed WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR +# A PARTICULAR PURPOSE. +# +# See LICENSE + +# A hyppopy minimal example optimizing a simple demo function f(x,y) = x**2+y**2 + +# import the HyppopyProject class keeping track of inputs +from hyppopy.HyppopyProject import HyppopyProject +from hyppopy.SolverPool import SolverPool +from hyppopy.solvers.MPISolverWrapper import MPISolverWrapper + +# To configure the Hyppopy solver we use a simple nested dictionary with two obligatory main sections, +# hyperparameter and settings. The hyperparameter section defines your searchspace. Each hyperparameter +# is again a dictionary with: +# +# - a domain ['categorical', 'uniform', 'normal', 'loguniform'] +# - the domain data [left bound, right bound] and +# - a type of your domain ['str', 'int', 'float'] +# +# The settings section has two subcategories, solver and custom. The first contains settings for the solver, +# here 'max_iterations' - is the maximum number of iteration. +# +# The custom section allows defining custom parameter. An entry here is transformed to a member variable of the +# HyppopyProject class. These can be useful when implementing new solver classes or for control your hyppopy script. +# Here we use it as a solver switch to control the usage of our solver via the config. This means with the script +# below your can try out every solver by changing use_solver to 'optunity', 'randomsearch', 'gridsearch',... +# It can be used like so: project.custom_use_plugin (see below) If using the gridsearch solver, max_iterations is +# ignored, instead each hyperparameter must specifiy a number of samples additionally to the range like so: +# 'data': [0, 1, 100] which means sampling the space from 0 to 1 in 100 intervals. + +config = { + "hyperparameter": { + "x": { + "domain": "uniform", + "data": [-10.0, 10.0], + "type": float, + "frequency": 10 + }, + "y": { + "domain": "uniform", + "data": [-10.0, 10.0], + "type": float, + "frequency": 10 + } + }, + "max_iterations": 500, + "solver": "optunity" +} + +project = HyppopyProject(config=config) + +# The user defined loss function +def my_loss_function_params(params): + x = params['x'] + y = params['y'] + return x**2+y**3 + +solver = MPISolverWrapper(solver=SolverPool.get(project=project)) +solver.blackbox = my_loss_function_params + +solver.run() + +df, best = solver.get_results() + +if solver.is_master() is True: + print("\n") + print("*" * 100) + print("Best Parameter Set:\n{}".format(best)) + print("*" * 100) diff --git a/mpiplayground_dynpso.py b/mpiplayground_dynpso.py new file mode 100644 index 0000000..71511e8 --- /dev/null +++ b/mpiplayground_dynpso.py @@ -0,0 +1,54 @@ +# Minimal setup to test dynPSO code: Reproduce normal PSO with dynamic PSO. + +# Insert path to Marie's optunity +import sys + +dir = None +assert dir != None, 'Please adapt the path to the location of specialized Optunity' +sys.path.insert(1, dir) + + +from mpi4py import MPI + +from hyppopy.MPIBlackboxFunction import MPIBlackboxFunction +from hyppopy.solvers.MPISolverWrapper import MPISolverWrapper + +import hyppopy.HyppopyProject +import hyppopy.solvers.DynamicPSOSolver +import numpy + + +def updateParam(pop_history, num_params_obj): + return numpy.ones(num_params_obj) + + +def combineObj(args, params): + return sum([a * p for a, p in zip(args, params)]) + + +def f(x, y): + return [x ** 2, y ** 2] + + +project = hyppopy.HyppopyProject.HyppopyProject() +project.add_hyperparameter(name="x", domain="uniform", data=[-10, 10], type=float) +project.add_hyperparameter(name="y", domain="uniform", data=[-10, 10], type=float) +project.add_setting(name="max_iterations", value=300) +project.add_setting(name="num_params_obj", value=2) +project.add_setting(name="num_args_obj", value=2) +project.add_setting(name="combine_obj", value=combineObj) +project.add_setting(name="update_param", value=updateParam) +project.add_setting(name="phi1", value=1.5) +project.add_setting(name="phi2", value=2.0) + +# ====================================================================================== +my_solver = hyppopy.solvers.DynamicPSOSolver.DynamicPSOSolver(project) +# solver.blackbox = f + +comm = MPI.COMM_WORLD +solver = MPISolverWrapper(solver=my_solver, mpi_comm=comm) +blackbox = MPIBlackboxFunction(blackbox_func=f, mpi_comm=comm) +solver.blackbox = blackbox +# ====================================================================================== + +solver.run() \ No newline at end of file diff --git a/optional_requirements.txt b/optional_requirements.txt new file mode 100644 index 0000000..a3298be --- /dev/null +++ b/optional_requirements.txt @@ -0,0 +1 @@ +mpi4py==3.0.2 \ No newline at end of file diff --git a/setup.py b/setup.py index 98abd06..d1d3753 100644 --- a/setup.py +++ b/setup.py @@ -1,54 +1,52 @@ import os from setuptools import setup, find_packages with open('README.md') as f: readme = f.read() with open('LICENSE') as f: license = f.read() -VERSION = "0.5.0.1" +VERSION = "0.5.0.8" ROOT = os.path.dirname(os.path.realpath(__file__)) new_init = [] with open(os.path.join(ROOT, *("hyppopy", "__init__.py")), "r") as infile: for line in infile: new_init.append(line) for n in range(len(new_init)): if new_init[n].startswith("__version__"): split = line.split("=") new_init[n] = "__version__ = '" + VERSION + "'\n" with open(os.path.join(ROOT, *("hyppopy", "__init__.py")), "w") as outfile: outfile.writelines(new_init) setup( name='hyppopy', version=VERSION, description='Hyper-Parameter Optimization Toolbox for Blackboxfunction Optimization', long_description=readme, # if you want, put your own name here # (this would likely result in people sending you emails) - author='Sven Wanner', - author_email='s.wanner@dkfz.de', - url='', + author='MIC @ DKFZ', + author_email='', + url='https://github.com/MIC-DKFZ/Hyppopy', license=license, packages=find_packages(exclude=('tests', 'doc')), - # the requirements to install this project. - # Since this one is so simple this is empty. install_requires=[ 'bayesian-optimization>=1.0.1', 'hyperopt>=0.1.2', 'matplotlib>=3.0.3', 'numpy>=1.16.2', 'optuna>=0.9.0', 'Optunity>=1.1.1', 'pandas>=0.24.2', 'pytest>=4.3.1', 'scikit-learn>=0.20.3', 'scipy>=1.2.1', 'visdom>=0.1.8.8' ], )