Package: hyperactive
An optimization and data collection toolbox for convenient and fast prototyping of computationally expensive models.Hyperactive:isvery easyto learn butextremly versatileprovides intelligentoptimization algorithms, support for all mayormachine-learning frameworksand many interestingapplicationsmakes optimizationdata collectionsimplesaves yourcomputation timesupportsparallel computingAs its name suggests Hyperactive started as a hyperparameter optimization package, but it has been generalized to solve expensive gradient-free optimization problems. It uses theGradient-Free-Optimizerspackage as an optimization-backend and expands on it with additional features and tools.Overview•Installation•API reference•Roadmap•Citation•LicenseWhat's new?27.08.2023 v4.5.0 add early-stopping for Optimization Strategies01.03.2023 v4.4.0 add new feature: "Optimization Strategies"18.11.2022 v4.3.0 with three new optimization algorithms (Spiral Optimization, Lipschitz Optimizer, DIRECT Optimizer)OverviewHyperactive features a collection of optimization algorithms that can be used for a variety of optimization problems. The following table shows examples of its capabilities:Optimization TechniquesTested and Supported PackagesOptimization ApplicationsLocal Search:Hill ClimbingRepulsing Hill ClimbingSimulated AnnealingDownhill Simplex OptimizerGlobal Search:Random SearchGrid SearchRandom Restart Hill ClimbingRandom Annealing[*]Powell's MethodPattern SearchPopulation Methods:Parallel TemperingParticle Swarm OptimizerSpiral OptimizationEvolution StrategySequential Methods:Bayesian OptimizationLipschitz OptimizationDirect AlgorithmTree of Parzen EstimatorsForest Optimizer[dto]Machine Learning:Scikit-learnXGBoostLightGBMCatBoostRGFMlxtendDeep Learning:TensorflowKerasPytorchParallel Computing:MultiprocessingJoblibPathosFeature Engineering:Feature TransformationFeature SelectionFeature ConstructionMachine Learning:Hyperparameter TuningModel SelectionSklearn PipelinesEnsemble LearningDeep Learning:Neural Architecture SearchPretrained Neural Architecture SearchTransfer LearningData Collection:Search Data CollectionMeta OptimizationMeta LearningMiscellaneous:Test FunctionsFit Gaussian CurvesManaging multiple objectivesManaging objects in search spaceMemorize evaluationsThe examples above are not necessarily done with realistic datasets or training procedures.
The purpose is fast execution of the solution proposal and giving the user ideas for interesting usecases.Sideprojects and ToolsThe following packages are designed to support Hyperactive and expand its use cases.PackageDescriptionSearch-Data-CollectorSimple tool to save search-data during or after the optimization run into csv-files.Search-Data-ExplorerVisualize search-data with plotly inside a streamlit dashboard.If you want news about Hyperactive and related projects you can follow me ontwitter.Notebooks and TutorialsIntroduction to HyperactiveInstallationThe most recent version of Hyperactive is available on PyPi:pip install hyperactiveExamplefromsklearn.model_selectionimportcross_val_scorefromsklearn.ensembleimportGradientBoostingRegressorfromsklearn.datasetsimportload_diabetesfromhyperactiveimportHyperactivedata=load_diabetes()X,y=data.data,data.target# define the model in a functiondefmodel(opt):# pass the suggested parameter to the machine learning modelgbr=GradientBoostingRegressor(n_estimators=opt["n_estimators"],max_depth=opt["max_depth"])scores=cross_val_score(gbr,X,y,cv=4)# return a single numerical valuereturnscores.mean()# search space determines the ranges of parameters you want the optimizer to search throughsearch_space={"n_estimators":list(range(10,150,5)),"max_depth":list(range(2,12)),}# start the optimization runhyper=Hyperactive()hyper.add_search(model,search_space,n_iter=50)hyper.run()Hyperactive API referenceBasic UsageHyperactive(verbosity, distribution, n_processes)verbosity = ["progress_bar", "print_results", "print_times"]Possible parameter types: (list, False)The verbosity list determines what part of the optimization information will be printed in the command line.distribution = "multiprocessing"Possible parameter types: ("multiprocessing", "joblib", "pathos")Determine, which distribution service you want to use. Each library uses different packages to pickle objects:multiprocessing uses picklejoblib uses dillpathos uses cloudpicklen_processes = "auto",Possible parameter types: (str, int)The maximum number of processes that are allowed to run simultaneously. If n_processes is of int-type there will only run n_processes-number of jobs simultaneously instead of all at once. So if n_processes=10 and n_jobs_total=35, then the schedule would look like this 10 - 10 - 10 - 5. This saves computational resources if there is a large number of n_jobs. If "auto", then n_processes is the sum of all n_jobs (from .add_search(...))..add_search(objective_function, search_space, n_iter, optimizer, n_jobs, initialize, pass_through, callbacks, catch, max_score, early_stopping, random_state, memory, memory_warm_start)objective_functionPossible parameter types: (callable)The objective function defines the optimization problem. The optimization algorithm will try to maximize the numerical value that is returned by the objective function by trying out different parameters from the search space.search_spacePossible parameter types: (dict)Defines the space were the optimization algorithm can search for the best parameters for the given objective function.n_iterPossible parameter types: (int)The number of iterations that will be performed during the optimization run. The entire iteration consists of the optimization-step, which decides the next parameter that will be evaluated and the evaluation-step, which will run the objective function with the chosen parameter and return the score.optimizer = "default"Possible parameter types: ("default", initialized optimizer object)Instance of optimization class that can be imported from Hyperactive. "default" corresponds to the random search optimizer. The imported optimization classes from hyperactive are different from gfo. They only accept optimizer-specific-parameters. The following classes can be imported and used:HillClimbingOptimizerStochasticHillClimbingOptimizerRepulsingHillClimbingOptimizerSimulatedAnnealingOptimizerDownhillSimplexOptimizerRandomSearchOptimizerGridSearchOptimizerRandomRestartHillClimbingOptimizerRandomAnnealingOptimizerPowellsMethodPatternSearchParallelTemperingOptimizerParticleSwarmOptimizerSpiralOptimizationEvolutionStrategyOptimizerBayesianOptimizerLipschitzOptimizerDirectAlgorithmTreeStructuredParzenEstimatorsForestOptimizerExample:...opt_hco=HillClimbingOptimizer(epsilon=0.08)hyper=Hyperactive()hyper.add_search(...,optimizer=opt_hco)hyper.run()...n_jobs = 1Possible parameter types: (int)Number of jobs to run in parallel. Those jobs are optimization runs that work independent from another (no information sharing). If n_jobs == -1 the maximum available number of cpu cores is used.initialize = {"grid": 4, "random": 2, "vertices": 4}Possible parameter types: (dict)The initialization dictionary automatically determines a number of parameters that will be evaluated in the first n iterations (n is the sum of the values in initialize). The initialize keywords are the following:gridInitializes positions in a grid like pattern. Positions that cannot be put into a grid are randomly positioned. For very high dimensional search spaces (>30) this pattern becomes random.verticesInitializes positions at the vertices of the search space. Positions that cannot be put into a new vertex are randomly positioned.randomNumber of random initialized positionswarm_startList of parameter dictionaries that marks additional start points for the optimization run.Example:...search_space={"x1":list(range(10,150,5)),"x2":list(range(2,12)),}ws1={"x1":10,"x2":2}ws2={"x1":15,"x2":10}hyper=Hyperactive()hyper.add_search(model,search_space,n_iter=30,initialize={"grid":4,"random":10,"vertices":4,"warm_start":[ws1,ws2]},)hyper.run()pass_through = {}Possible parameter types: (dict)The pass_through accepts a dictionary that contains information that will be passed to the objective-function argument. This information will not change during the optimization run, unless the user does so by himself (within the objective-function).Example:...defobjective_function(para):para.pass_through["stuff1"]# <--- this variable is 1para.pass_through["stuff2"]# <--- this variable is 2score=-para["x1"]*para["x1"]returnscorepass_through={"stuff1":1,"stuff2":2,}hyper=Hyperactive()hyper.add_search(model,search_space,n_iter=30,pass_through=pass_through,)hyper.run()callbacks = {}Possible parameter types: (dict)The callbacks enables you to pass functions to hyperactive that are called every iteration during the optimization run. The function has access to the same argument as the objective-function. You can decide if the functions are called before or after the objective-function is evaluated via the keys of the callbacks-dictionary. The values of the dictionary are lists of the callback-functions. The following example should show they way to use callbacks:Example:...defcallback_1(access):# do some stuffdefcallback_2(access):# do some stuffdefcallback_3(access):# do some stuffhyper=Hyperactive()hyper.add_search(objective_function,search_space,n_iter=100,callbacks={"after":[callback_1,callback_2],"before":[callback_3]},)hyper.run()catch = {}Possible parameter types: (dict)The catch parameter provides a way to handle exceptions that occur during the evaluation of the objective-function or the callbacks. It is a dictionary that accepts the exception class as a key and the score that is returned instead as the value. This way you can handle multiple types of exceptions and return different scores for each.
In the case of an exception it often makes sense to returnnp.nanas a score. You can see an example of this in the following code-snippet:Example:...hyper=Hyperactive()hyper.add_search(objective_function,search_space,n_iter=100,catch={ValueError:np.nan,},)hyper.run()max_score = NonePossible parameter types: (float, None)Maximum score until the optimization stops. The score will be checked after each completed iteration.early_stopping=None(dict, None)Stops the optimization run early if it did not achive any score-improvement within the last iterations. The early_stopping-parameter enables to set three parameters:n_iter_no_change: Non-optional int-parameter. This marks the last n iterations to look for an improvement over the iterations that came before n. If the best score of the entire run is within those last n iterations the run will continue (until other stopping criteria are met), otherwise the run will stop.tol_abs: Optional float-paramter. The score must have improved at least this absolute tolerance in the last n iterations over the best score in the iterations before n. This is an absolute value, so 0.1 means an imporvement of 0.8 -> 0.9 is acceptable but 0.81 -> 0.9 would stop the run.tol_rel: Optional float-paramter. The score must have imporved at least this relative tolerance (in percentage) in the last n iterations over the best score in the iterations before n. This is a relative value, so 10 means an imporvement of 0.8 -> 0.88 is acceptable but 0.8 -> 0.87 would stop the run.random_state = NonePossible parameter types: (int, None)Random state for random processes in the random, numpy and scipy module.memory = "share"Possible parameter types: (bool, "share")Whether or not to use the "memory"-feature. The memory is a dictionary, which gets filled with parameters and scores during the optimization run. If the optimizer encounters a parameter that is already in the dictionary it just extracts the score instead of reevaluating the objective function (which can take a long time). If memory is set to "share" and there are multiple jobs for the same objective function then the memory dictionary is automatically shared between the different processes.memory_warm_start = NonePossible parameter types: (pandas dataframe, None)Pandas dataframe that contains score and parameter information that will be automatically loaded into the memory-dictionary.example:scorex1x2x...0.7560.10.2...0.8230.30.1............................run(max_time)max_time = NonePossible parameter types: (float, None)Maximum number of seconds until the optimization stops. The time will be checked after each completed iteration.Special ParametersObjective FunctionEach iteration consists of two steps:The optimization step: decides what position in the search space (parameter set) to evaluate nextThe evaluation step: calls the objective function, which returns the score for the given position in the search spaceThe objective function has one argument that is often called "para", "params", "opt" or "access".
This argument is your access to the parameter set that the optimizer has selected in the
corresponding iteration.defobjective_function(opt):# get x1 and x2 from the argument "opt"x1=opt["x1"]x2=opt["x2"]# calculate the score with the parameter setscore=-(x1*x1+x2*x2)# return the scorereturnscoreThe objective function always needs a score, which shows how "good" or "bad" the current parameter set is. But you can also return some additional information with a dictionary:defobjective_function(opt):x1=opt["x1"]x2=opt["x2"]score=-(x1*x1+x2*x2)other_info={"x1 squared":x1**2,"x2 squared":x2**2,}returnscore,other_infoWhen you take a look at the results (a pandas dataframe with all iteration information) after the run has ended you will see the additional information in it. The reason we need a dictionary for this is because Hyperactive needs to know the names of the additonal parameters. The score does not need that, because it is always called "score" in the results. You can runthis example scriptif you want to give it a try.Search Space DictionaryThe search space defines what values the optimizer can select during the search. These selected values will be inside the objective function argument and can be accessed like in a dictionary. The values in each search space dimension should always be in a list. If you use np.arange you should put it in a list afterwards:search_space={"x1":list(np.arange(-100,101,1)),"x2":list(np.arange(-100,101,1)),}A special feature of Hyperactive is shown in the next example. You can put not just numeric values into the search space dimensions, but also strings and functions. This enables a very high flexibility in how you can create your studies.deffunc1():# do stuffreturnstuffdeffunc2():# do stuffreturnstuffsearch_space={"x":list(np.arange(-100,101,1)),"str":["a string","another string"],"function":[func1,func2],}If you want to put other types of variables (like numpy arrays, pandas dataframes, lists, ...) into the search space you can do that via functions:defarray1():returnnp.array([1,2,3])defarray2():returnnp.array([3,2,1])search_space={"x":list(np.arange(-100,101,1)),"str":["a string","another string"],"numpy_array":[array1,array2],}The functions contain the numpy arrays and returns them. This way you can use them inside the objective function.Optimizer ClassesEach of the following optimizer classes can be initialized and passed to the "add_search"-method via the "optimizer"-argument. During this initialization the optimizer class acceptsonly optimizer-specific-paramters(no random_state, initialize, ... ):optimizer=HillClimbingOptimizer(epsilon=0.1,distribution="laplace",n_neighbours=4)for the default parameters you can just write:optimizer=HillClimbingOptimizer()and pass it to Hyperactive:hyper=Hyperactive()hyper.add_search(model,search_space,optimizer=optimizer,n_iter=100)hyper.run()So the optimizer-classes aredifferentfrom Gradient-Free-Optimizers. A more detailed explanation of the optimization-algorithms and the optimizer-specific-paramters can be found in theOptimization Tutorial.HillClimbingOptimizerRepulsingHillClimbingOptimizerSimulatedAnnealingOptimizerDownhillSimplexOptimizerRandomSearchOptimizerGridSearchOptimizerRandomRestartHillClimbingOptimizerRandomAnnealingOptimizerPowellsMethodPatternSearchParallelTemperingOptimizerParticleSwarmOptimizerEvolutionStrategyOptimizerBayesianOptimizerTreeStructuredParzenEstimatorsForestOptimizerResult Attributes.best_para(objective_function)objective_function(callable)returnes: dictionaryParameter dictionary of the best score of the given objective_function found in the previous optimization run.example:{'x1':0.2,'x2':0.3,}.best_score(objective_function)objective_function(callable)returns: int or floatNumerical value of the best score of the given objective_function found in the previous optimization run..search_data(objective_function, times=False)objective_function(callable)returns: Pandas dataframeThe dataframe contains score and parameter information of the given objective_function found in the optimization run. If the parametertimesis set to True the evaluation- and iteration- times are added to the dataframe.example:scorex1x2x...0.7560.10.2...0.8230.30.1...........................Roadmapv2.0.0:heavy_check_mark:Change APIv2.1.0:heavy_check_mark:Save memory of evaluations for later runs (long term memory)Warm start sequence based optimizers with long term memoryGaussian process regressors from various packages (gpy, sklearn, GPflow, ...) via wrapperv2.2.0:heavy_check_mark:Add basic dataset meta-features to long term memoryAdd helper-functions for memoryconnect two different model/dataset hashessplit two different model/dataset hashesdelete memory of model/datasetreturn best known model for datasetreturn search space for best modelreturn best parameter for best modelv2.3.0:heavy_check_mark:Tree-structured Parzen EstimatorDecision Tree Optimizeradd "max_sample_size" and "skip_retrain" parameter for sbom to decrease optimization timev3.0.0:heavy_check_mark:New APIexpand usage of objective-functionNo passing of training data into HyperactiveRemoving "long term memory"-support (better to do in separate package)More intuitive selection of optimization strategies and parametersSeparate optimization algorithms into other packageexpand api so that optimizer parameter can be changed at runtimeadd extensive testing procedure (similar to Gradient-Free-Optimizers)v3.1.0:heavy_check_mark:Decouple number of runs from active processes (Thanks toPartiallyTyped)v3.2.0:heavy_check_mark:Dashboard for visualization of search-data at runtime via streamlit (Progress-Board)v3.3.0:heavy_check_mark:Early stoppingShared memory dictionary between processes with the same objective functionv4.0.0:heavy_check_mark:small adjustments to APImove optimization strategies into sub-module "optimizers"preparation for future add ons (long-term-memory, meta-learn, ...) from separate repositoriesseparate progress board into separate repositoryv4.1.0:heavy_check_mark:add python 3.9 to testingadd pass_through-parameteradd v1 GFO optimization algorithmsv4.2.0:heavy_check_mark:add callbacks-parameteradd catch-parameteradd option to add eval- and iter- times to search-datav4.3.0:heavy_check_mark:add new features from GFOadd Spiral Optimizationadd Lipschitz Optimizeradd DIRECT Optimizerprint the random seed for reproducibilityv4.4.0:heavy_check_mark:add Optimization-Strategiesredesign progress-barv4.5.0:heavy_check_mark:add early stopping feature to custom optimization strategiesdisplay additional outputs from objective-function in results in command-lineadd type hints to hyperactive-apiv4.6.0add support for constrained optimizationv4.7.0add "prune_search_space"-method to custom optimization strategy classFAQKnown Errors + SolutionsRead this before opening a bug-issueAre you sure the bug is located in Hyperactive?The error might be located in the optimization-backend.
Look at the error message from the command line.Ifone of the last messages look like this:File "/.../gradient_free_optimizers/...", line ...Thenyou should post the bug report in:https://github.com/SimonBlanke/Gradient-Free-OptimizersOtherwise you can post the bug report in HyperactiveDo you have the correct Hyperactive version?Every major version update (e.g. v2.2 -> v3.0) the API of Hyperactive changes.
Check which version of Hyperactive you have. If your major version is older you have two options:Recommended:You could just update your Hyperactive version with:pipinstallhyperactive--upgradeThis way you can use all the new documentation and examples from the current repository.Or you could continue using the old version and use an old repository branch as documentation.
You can do that by selecting the corresponding branch. (top right of the repository. The default is "master" or "main")
So if your major version is older (e.g. v2.1.0) you can select the 2.x.x branch to get the old repository for that version.Provide example code for error reproductionTo understand and fix the issue I need an example code to reproduce the error.
I must be able to just copy the code into a py-file and execute it to reproduce the error.MemoryError: Unable to allocate ... for an array with shape (...)This is expected of the current implementation of smb-optimizers. For all Sequential model based algorithms you have to keep your eyes on the search space size:search_space_size=1forvalue_insearch_space.values():search_space_size*=len(value_)print("search_space_size",search_space_size)Reduce the search space size to resolve this error.TypeError: cannot pickle '_thread.RLock' objectThis is because you have classes and/or non-top-level objects in the search space. Pickle (used by multiprocessing) cannot serialize them. Setting distribution to "joblib" or "pathos" may fix this problem:hyper=Hyperactive(distribution="joblib")Command line full of warningsVery often warnings from sklearn or numpy. Those warnings do not correlate with bad performance from Hyperactive. Your code will most likely run fine. Those warnings are very difficult to silence.It should help to put this at the very top of your script:defwarn(*args,**kwargs):passimportwarningswarnings.warn=warnWarning: Not enough initial positions for population sizeThis warning occurs because Hyperactive needs more initial positions to choose from to generate a population for the optimization algorithm:
The number of initial positions is determined by theinitialize-parameter in theadd_search-method.# This is how it looks per defaultinitialize={"grid":4,"random":2,"vertices":4}# You could set it to this for a maximum population of 20initialize={"grid":4,"random":12,"vertices":4}References[dto]Scikit-OptimizeCiting Hyperactive@Misc{hyperactive2021,
  author =   {{Simon Blanke}},
  title =    {{Hyperactive}: An optimization and data collection toolbox for convenient and fast prototyping of computationally expensive models.},
  howpublished = {\url{https://github.com/SimonBlanke}},
  year = {since 2019}
}License