Package: bayesmark
InstallationThis project provides a benchmark framework to easily compare Bayesian optimization methods on real machine learning tasks.This project is experimental and the APIs are not considered stable.This Bayesian optimization (BO) benchmark framework requires a few easy steps for setup. It can be run either on a local machine (in serial) or prepare acommands fileto run on a cluster as parallel experiments (dry run mode).OnlyPython>=3.6is officially supported, but older versions of Python likely work as well.The core package itself can be installed with:pipinstallbayesmarkHowever, to also require installation of all the “built in” optimizers for evaluation, run:pipinstallbayesmark[optimizers]It is also possible to use the same pinned dependencies we used in testing byinstalling from the repo.Building an environment to run the included notebooks can be done with:pipinstallbayesmark[notebooks]Or,bayesmark[optimizers,notebooks]can be used.A quick example of running the benchmark ishere. The instructions are used to generate results as below:Non-pip dependenciesTo be able to installopentunersome system level (non-pip) dependencies must be installed. This can be done with:sudoapt-getinstalllibsqlite3-0sudoapt-getinstalllibsqlite3-devOn Ubuntu, this results in:> dpkg -l | grep libsqlite
ii  libsqlite3-0:amd64    3.11.0-1ubuntu1  amd64  SQLite 3 shared library
ii  libsqlite3-dev:amd64  3.11.0-1ubuntu1  amd64  SQLite 3 development filesThe environment should now all be setup to run the BO benchmark.RunningNow we can run each step of the experiments. First, we run all combinations and then run some quick commands to analyze the output.Launch the experimentsThe experiments are run using the experiment launcher, which has the following interface:usage: bayesmark-launch [-h] [-dir DB_ROOT] [-odir OPTIMIZER_ROOT] [-v] [-u UUID]
                  [-dr DATA_ROOT] [-b DB] [-o OPTIMIZER [OPTIMIZER ...]]
                  [-d DATA [DATA ...]]
                  [-c [{DT,MLP-adam,MLP-sgd,RF,SVM,ada,kNN,lasso,linear} ...]]
                  [-m [{acc,mae,mse,nll} ...]] [-n N_CALLS]
                  [-p N_SUGGEST] [-r N_REPEAT] [-nj N_JOBS] [-ofile JOBS_FILE]The arguments are:-h, --help            show this help message and exit
-dir DB_ROOT, -db-root DB_ROOT
                      root directory for all benchmark experiments output
-odir OPTIMIZER_ROOT, --opt-root OPTIMIZER_ROOT
                      Directory with optimization wrappers
-v, --verbose         print the study logs to console
-u UUID, --uuid UUID  length 32 hex UUID for this experiment
-dr DATA_ROOT, --data-root DATA_ROOT
                      root directory for all custom csv files
-b DB, --db DB        database ID of this benchmark experiment
-o OPTIMIZER [OPTIMIZER ...], --opt OPTIMIZER [OPTIMIZER ...]
                      optimizers to use
-d DATA [DATA ...], --data DATA [DATA ...]
                      data sets to use
-c, --classifier [{DT,MLP-adam,MLP-sgd,RF,SVM,ada,kNN,lasso,linear} ...]
                      classifiers to use
-m, --metric [{acc,mae,mse,nll} ...]
                      scoring metric to use
-n N_CALLS, --calls N_CALLS
                      number of function evaluations
-p N_SUGGEST, --suggestions N_SUGGEST
                      number of suggestions to provide in parallel
-r N_REPEAT, --repeat N_REPEAT
                      number of repetitions of each study
-nj N_JOBS, --num-jobs N_JOBS
                      number of jobs to put in the dry run file, the default
                      0 value disables dry run (real run)
-ofile JOBS_FILE, --jobs-file JOBS_FILE
                      a jobs file with all commands to be runThe output files will be placed in[DB_ROOT]/[DBID]. IfDBIDis not specified, it will be a randomly created subdirectory with a new name to avoid overwriting previous experiments. The path toDBIDis shown at the beginning ofstdoutwhen runningbayesmark-launch. In general, let the launcher create and setupDBIDunless you are appending to a previous experiment, in which case, specify the existingDBID.The launcher’s sequence of commands can be accessed programmatically via.experiment_launcher.gen_commands. The individual experiments can be launched programmatically via.experiment.run_sklearn_study.Selecting the experimentsA list of optimizers, classifiers, data sets, and metrics can be listed using the-o/-c/-d/-mcommands, respectively. If not specified, the program launches all possible options.Selecting the optimizerA few different open source optimizers have been included as an example and are considered the “built-in” optimizers. The original repos are shown in theLinks.The data argument-oallows a list containing the “built-in” optimizers:"HyperOpt", "Nevergrad-OnePlusOne", "OpenTuner-BanditA", "OpenTuner-GA", "OpenTuner-GA-DE", "PySOT", "RandomSearch", "Scikit-GBRT-Hedge", "Scikit-GP-Hedge", "Scikit-GP-LCB"or, one can specify a user-defined optimizer. The class containing an optimizer conforming to the API must be found in in the folder specified by--opt-root. Additionally, a configuration defining each optimizer must be defined in[OPT_ROOT]/config.json. The--opt-rootandconfig.jsonmay be omitted if only built-in optimizers are used.Additional details for providing a new optimizer are found inadding a new optimizer.Selecting the data setBy default, this benchmark uses thesklearn example data setsas the “built-in” data sets for use in ML model tuning problems.The data argument-dallows a list containing the “built-in” data sets:"breast", "digits", "iris", "wine", "boston", "diabetes"or, it can refer to a customcsvfile, which is the name of file in the folder specified by--data-root. It also follows the convention that regression data sets start withreg-and classification data sets start withclf-. For example, the classification data set in[DATA_ROOT]/clf-foo.csvis specified with-dclf-foo.Thecsvfile can be anything readable by pandas, but we assume the final column is the target and all other columns are features. The target column should be integer for classification data and float for regression. The features should float (orstrfor categorical variable columns). Seebayesmark.data.load_datafor more information.Dry run for cluster jobsIt is also possible to do a “dry run” of the launcher by specifying a value for--num-jobsgreater than zero. For example, if--num-jobs50is provided, a text file listing 50 commands to run is produced, with one command (job) per line. This is useful when preparing a list of commands to run later on a cluster.A dry run will generate a command file (e.g.,jobs.txt) like the following (with a meta-data header). Each line corresponds to a command that can be used as a job on a different worker:# running: {'--uuid': None, '-db-root': '/foo', '--opt-root': '/example_opt_root', '--data-root': None, '--db': 'bo_example_folder', '--opt': ['RandomSearch', 'PySOT'], '--data': None, '--classifier': ['SVM', 'DT'], '--metric': None, '--calls': 15, '--suggestions': 1, '--repeat': 3, '--num-jobs': 50, '--jobs-file': '/jobs.txt', '--verbose': False, 'dry_run': True, 'rev': '9a14ef2', 'opt_rev': None}
# cmd: python bayesmark-launch -n 15 -r 3 -dir foo -o RandomSearch PySOT -c SVM DT -nj 50 -b bo_example_folder
job_e2b63a9_00 bayesmark-exp -c SVM -d diabetes -o PySOT -u 079a155f03095d2ba414a5d2cedde08c -m mse -n 15 -p 1 -dir foo -b bo_example_folder && bayesmark-exp -c SVM -d boston -o RandomSearch -u 400e4c0be8295ad59db22d9b5f31d153 -m mse -n 15 -p 1 -dir foo -b bo_example_folder && bayesmark-exp -c SVM -d digits -o RandomSearch -u fe73a2aa960a5e3f8d78bfc4bcf51428 -m acc -n 15 -p 1 -dir foo -b bo_example_folder
job_e2b63a9_01 bayesmark-exp -c DT -d diabetes -o PySOT -u db1d9297948554e096006c172a0486fb -m mse -n 15 -p 1 -dir foo -b bo_example_folder && bayesmark-exp -c SVM -d boston -o RandomSearch -u 7148f690ed6a543890639cc59db8320b -m mse -n 15 -p 1 -dir foo -b bo_example_folder && bayesmark-exp -c SVM -d breast -o PySOT -u 72c104ba1b6d5bb8a546b0064a7c52b1 -m nll -n 15 -p 1 -dir foo -b bo_example_folder
job_e2b63a9_02 bayesmark-exp -c SVM -d iris -o PySOT -u cc63b2c1e4315a9aac0f5f7b496bfb0f -m nll -n 15 -p 1 -dir foo -b bo_example_folder && bayesmark-exp -c DT -d breast -o RandomSearch -u aec62e1c8b5552e6b12836f0c59c1681 -m nll -n 15 -p 1 -dir foo -b bo_example_folder && bayesmark-exp -c DT -d digits -o RandomSearch -u 4d0a175d56105b6bb3055c3b62937b2d -m acc -n 15 -p 1 -dir foo -b bo_example_folder
...This package does not have built in support for deploying these jobs on a cluster or cloud environment (.e.g., AWS).The UUID argumentTheUUIDis a 32-char hex string used as a master random seed which we use to draw random seeds for the experiments. IfUUIDis not specified a version 4 UUID is generated. The used UUID is displayed at the beginning ofstdout. In general, theUUIDshould not specified/re-used except for debugging because it violates the assumption that the experiment UUIDs are unique.Aggregate resultsNext to aggregate all the experiment files into combined (json) files we need to run the aggregation command:usage: bayesmark-agg [-h] [-dir DB_ROOT] [-odir OPTIMIZER_ROOT] [-v] -b DB [-rv]The arguments are:-h, --help            show this help message and exit
-dir DB_ROOT, -db-root DB_ROOT
                      root directory for all benchmark experiments output
-odir OPTIMIZER_ROOT, --opt-root OPTIMIZER_ROOT
                      Directory with optimization wrappers
-v, --verbose         print the study logs to console
-b DB, --db DB        database ID of this benchmark experiment
-rv, --ravel          ravel all studies to store batch suggestions as if
                      they were serialTheDB_ROOTmust match the folder from the launcherbayesmark-launch, andDBIDmust match that displayed from the launcher as well. The aggregate files are found in[DB_ROOT]/[DBID]/derived.The result aggregation can be done programmatically via.experiment_aggregate.concat_experiments.Analyze and summarize resultsFinally, to run a statistical analysis presenting a summary of the experiments we runusage: bayesmark-anal [-h] [-dir DB_ROOT] [-odir OPTIMIZER_ROOT] [-v] -b DBThe arguments are:-h, --help            show this help message and exit
-dir DB_ROOT, -db-root DB_ROOT
                      root directory for all benchmark experiments output
-odir OPTIMIZER_ROOT, --opt-root OPTIMIZER_ROOT
                      Directory with optimization wrappers
-v, --verbose         print the study logs to console
-b DB, --db DB        database ID of this benchmark experimentTheDB_ROOTmust match the folder from the launcherbayesmark-launch, andDBIDmust match that displayed from the launcher as well. The aggregate files are found in[DB_ROOT]/[DBID]/derived.Thebayesmark-analcommand looks for abaseline.jsonfile in[DB_ROOT]/[DBID]/derived, which states the best possible and random search performance. If no such file is present,bayesmark-analautomatically callsbayesmark-baselineto build it. The baselines are inferred from the random search performance in the logs. The baseline values are considered fixed (not random) quantities whenbayesmark-analbuilds confidence intervals. Therefore, we allow the user to leave them fixed and do not rebuild them whenbayesmark-analis called if a baselines file is already present.The result analysis can be done programmatically via.experiment_analysis.compute_aggregates, and the baseline computation via.experiment_baseline.compute_baseline.Seehow-scoring-worksfor more information on how the scores are computed and aggregated.ExampleAfter finishing the setup (environment) a small-scale serial can be run as follows:> # setup
> DB_ROOT=./notebooks  # path/to/where/you/put/results
> DBID=bo_example_folder
> mkdir $DB_ROOT
> # experiments
> bayesmark-launch -n 15 -r 3 -dir $DB_ROOT -b $DBID -o RandomSearch PySOT -c SVM DT -v
Supply --uuid 3adc3182635e44ea96969d267591f034 to reproduce this run.
Supply --dbid bo_example_folder to append to this experiment or reproduce jobs file.
User must ensure equal reps of each optimizer for unbiased results
-c DT -d boston -o PySOT -u a1b287b450385ad09b2abd7582f404a2 -m mae -n 15 -p 1 -dir /notebooks -b bo_example_folder
-c DT -d boston -o PySOT -u 63746599ae3f5111a96942d930ba1898 -m mse -n 15 -p 1 -dir /notebooks -b bo_example_folder
-c DT -d boston -o RandomSearch -u 8ba16c880ef45b27ba0909199ab7aa8a -m mae -n 15 -p 1 -dir /notebooks -b bo_example_folder
...
0 failures of benchmark script after 144 studies.
done
> # aggregate
> bayesmark-agg -dir $DB_ROOT -b $DBID
> # analyze
> bayesmark-anal -dir $DB_ROOT -b $DBID -v
...
median score @ 15:
optimizer
PySOT_0.2.3_9b766b6           0.330404
RandomSearch_0.0.1_9b766b6    0.961829
mean score @ 15:
optimizer
PySOT_0.2.3_9b766b6           0.124262
RandomSearch_0.0.1_9b766b6    0.256422
normed mean score @ 15:
optimizer
PySOT_0.2.3_9b766b6           0.475775
RandomSearch_0.0.1_9b766b6    0.981787
doneThe aggregate result files (i.e.,summary.json) will now be available in$DB_ROOT/$DBID/derived. However, this will be high variance since it was from only 3 trials and only to 15 function evaluations.Plotting and notebooksPlotting the quantitative results found in$DB_ROOT/$DBID/derivedcan be done using the notebooks found in thenotebooks/folder of the git repository. The notebookplot_mean_score.ipynbgenerates plots for aggregate scores averaging over all problems. The notebookplot_test_case.ipynbgenerates plots for each test problem.To use the notebooks, first copy over thenotebooks/folder from git repository.To setup the kernel for running the notebooks use:virtualenvbobm_ipynb--python=python3.6source./bobm_ipynb/bin/activatepipinstallbayesmark[notebooks]python-mipykernelinstall--name=bobm_ipynb--userNow, the notebooks for plotting can be run with the commandjupyter notebookand selecting the kernelbobm_ipynb.It is also possible to convert the notebooks to an HTML report at the command line usingnbconvert. For example, use the command:jupyternbconvert--tohtml--executenotebooks/plot_mean_score.ipynbThe output file will be in./notebooks/plot_mean_score.html. Here is an exampleexport. See thenbconvertdocumentation pagefor more output formats. By default, the notebooks look in./notebooks/bo_example_folder/for thesummary.jsonfrombayesmark-anal.To runplot_test_case.ipynbuse the command:jupyternbconvert--tohtml--executenotebooks/plot_test_case.ipynb--ExecutePreprocessor.timeout=600The--ExecutePreprocessor.timeout=600timeout increase is needed due to the large number of plots being generated. The output will be in./notebooks/plot_test_case.html.Adding a new optimizerAll optimizers in this benchmark are required to follow the interface specified of theAbstractOptimizerclass inbayesmark.abstract_optimizer. In general, this requires creating a wrapper class around the new optimizer. The wrapper classes must all be placed in a folder referred to by the--opt-rootargument. This folder must also contain theconfig.jsonfolder.The interface is simple, one must merely implement thesuggestandobservefunctions. Thesuggestfunction generates new guesses for evaluating the function. Once evaluated, the function evaluations are passed to theobservefunction. The objective function isnotevaluated by the optimizer class. The objective function is evaluated on outside and results are passed toobserve. This is the correct setup for Bayesian optimization because:We can observe/try inputs that were never suggestedWe can ignore suggestionsThe objective function may not be something as simple as a Python functionSo passing the function as an argument as is done inscipy.optimizationis artificially restrictive.The implementation of the wrapper will look like the following:frombayesmark.abstract_optimizerimportAbstractOptimizerfrombayesmark.experimentimportexperiment_mainclassNewOptimizerName(AbstractOptimizer):# Used for determining the version number of package usedprimary_import="name of import used e.g, opentuner"def__init__(self,api_config,optional_arg_foo=None,optional_arg_bar=None):"""Build wrapper class to use optimizer in benchmark.

        Parameters
        ----------
        api_config : dict-like of dict-like
            Configuration of the optimization variables. See API description.
        """AbstractOptimizer.__init__(self,api_config)# Do whatever other setup is needed# ...defsuggest(self,n_suggestions=1):"""Get suggestion from the optimizer.

        Parameters
        ----------
        n_suggestions : int
            Desired number of parallel suggestions in the output

        Returns
        -------
        next_guess : list of dict
            List of `n_suggestions` suggestions to evaluate the objective
            function. Each suggestion is a dictionary where each key
            corresponds to a parameter being optimized.
        """# Do whatever is needed to get the parallel guesses# ...returnx_guessdefobserve(self,X,y):"""Feed an observation back.

        Parameters
        ----------
        X : list of dict-like
            Places where the objective function has already been evaluated.
            Each suggestion is a dictionary where each key corresponds to a
            parameter being optimized.
        y : array-like, shape (n,)
            Corresponding values where objective has been evaluated
        """# Update the model with new objective function observations# ...# No return statement neededif__name__=="__main__":# This is the entry point for experiments, so pass the class to experiment_main to use this optimizer.# This statement must be included in the wrapper class file:experiment_main(NewOptimizerName)Depending on the API of the optimizer being wrapped, building this wrapper class may only or require a few lines of code, or be a total pain.The config fileNote: A config file is now optional. If noconfig.jsonis provided, the experiment launcher will look for all folders with anoptimizer.pyin the--opt-rootdirectory.Each optimizer wrapper can have multiple configurations, which is each referred to as a different optimizer in the benchmark. For example, the JSON config file will have entries as follows:{"OpenTuner-BanditA-New":["opentuner_optimizer.py",{"techniques":["AUCBanditMetaTechniqueA"]}],"OpenTuner-GA-DE-New":["opentuner_optimizer.py",{"techniques":["PSO_GA_DE"]}],"OpenTuner-GA-New":["opentuner_optimizer.py",{"techniques":["PSO_GA_Bandit"]}]}Basically, the entries are"name_of_strategy": ["file_with_class", {kwargs_for_the_constructor}]. Here,OpenTuner-BanditA,OpenTuner-GA-DE, andOpenTuner-GAare all treated as different optimizers by the benchmark even though the all use the same class fromopentuner_optimizer.py.Thisconfig.jsonmust be in the same folder as the optimizer classes (e.g.,opentuner_optimizer.py).Running with a new optimizerTo run the benchmarks using a new optimizer, simply provide its name (fromconfig.json) in the-olist. The--opt-rootargument must be specified in this case. For example, the launch command from theexamplebecomes:bayesmark-launch-n15-r3-dir$DB_ROOT-b$DBID-oRandomSearchPySOT-New-cSVMDT--opt-root./example_opt_root-vHere, we are using the examplePySOT-Newwrapper from theexample_opt_rootfolder in the git repo. It is equivalent to the builtinPySOT, but gives an example of how to provide a new custom optimizer.ContributingThe following instructions have been tested with Python 3.6.8 on Ubuntu (16.04.5 LTS).Install in editable modeFirst, define the variables for the paths we will use:GIT=/path/to/where/you/put/reposENVS=/path/to/where/you/put/virtualenvsThen clone the repo in your git directory$GIT:cd$GITgitclonehttps://github.com/uber/bayesmark.gitInside your virtual environments folder$ENVS, make the environment:cd$ENVSvirtualenvbayesmark--python=python3.6source$ENVS/bayesmark/bin/activateNow we can install the pip dependencies. Move back into your git directory and runcd$GIT/bayesmarkpipinstall-rrequirements/base.txtpipinstall-rrequirements/optimizers.txtpipinstall-e.# Install the benchmark itselfYou may want to runpip install-Upipfirst if you have an old version ofpip. The fileoptimizers.txtcontains the dependencies for all the optimizers used in the benchmark. The analysis and aggregation programs can be run using only the requirements inbase.txt.Contributor toolsFirst, we need to setup some needed tools:cd$ENVSvirtualenvbayesmark_tools--python=python3.6source$ENVS/bayesmark_tools/bin/activatepipinstall-r$GIT/bayesmark/requirements/tools.txtTo install the pre-commit hooks for contributing run (in thebayesmark_toolsenvironment):cd$GIT/bayesmarkpre-commitinstallTo rebuild the requirements, we can run:cd$GIT/bayesmark# Get py files from notebooks to analyzejupyternbconvert--toscriptnotebooks/*.ipynb# Generate the .in files (but pins to latest, which we might not want)pipreqsbayesmark/--ignorebayesmark/builtin_opt/--savepathrequirements/base.inpipreqstest/--savepathrequirements/test.inpipreqsbayesmark/builtin_opt/--savepathrequirements/optimizers.inpipreqsnotebooks/--savepathrequirements/ipynb.inpipreqsdocs/--savepathrequirements/docs.in# Regenerate the .txt files from .in filespip-compile-multi--no-upgradeGenerating the documentationFirst setup the environment for building withSphinx:cd$ENVSvirtualenvbayesmark_docs--python=python3.6source$ENVS/bayesmark_docs/bin/activatepipinstall-r$GIT/bayesmark/requirements/docs.txtThen we can do the build:cd$GIT/bayesmark/docsmakeallopen_build/html/index.htmlDocumentation will be available in all formats inMakefile. Usemake htmlto only generate the HTML documentation.Running the testsThe tests for this package can be run with:cd$GIT/bayesmark./test.shThe script creates a conda environment using the requirements found inrequirements/test.txt.Thetest.shscriptmustbe run from acleangit repo.Or if we only want to run the unit tests and not check the adequacy of the requirements files, one can use# Setup environmentcd$ENVSvirtualenvbayesmark_test--python=python3.6source$ENVS/bayesmark_test/bin/activatepipinstall-r$GIT/bayesmark/requirements/test.txtpipinstall-e$GIT/bayesmark# Now run testscd$GIT/bayesmark/pytesttest/-s-v--hypothesis-seed=0--disable-pytest-warnings--cov=bayesmark--cov-reporthtmlA code coverage report will also be produced in$GIT/bayesmark/htmlcov/index.html.DeploymentThe wheel (tar ball) for deployment as a pip installable package can be built using the script:cd$GIT/bayesmark/./build_wheel.shLinksThesourceis hosted on GitHub.Thedocumentationis hosted at Read the Docs.Installable fromPyPI.The builtin optimizers are wrappers on the following projects:HyperOptNevergradOpenTunerPySOTScikit-optimizeLicenseThis project is licensed under the Apache 2 License - see the LICENSE file for details.