{"id":13570037,"url":"https://github.com/bayesian-optimization/BayesianOptimization","last_synced_at":"2025-04-04T06:31:51.866Z","repository":{"id":37276130,"uuid":"20556335","full_name":"bayesian-optimization/BayesianOptimization","owner":"bayesian-optimization","description":"A Python implementation of global optimization with gaussian processes.","archived":false,"fork":false,"pushed_at":"2025-03-17T12:46:17.000Z","size":47388,"stargazers_count":8160,"open_issues_count":9,"forks_count":1566,"subscribers_count":131,"default_branch":"master","last_synced_at":"2025-04-03T03:27:13.854Z","etag":null,"topics":["bayesian-optimization","gaussian-processes","optimization","python","simple"],"latest_commit_sha":null,"homepage":"https://bayesian-optimization.github.io/BayesianOptimization/index.html","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/bayesian-optimization.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2014-06-06T08:18:56.000Z","updated_at":"2025-04-03T01:11:58.000Z","dependencies_parsed_at":"2023-10-15T11:01:24.010Z","dependency_job_id":"856823ea-3e24-4e0b-b2eb-13ef6d806c1a","html_url":"https://github.com/bayesian-optimization/BayesianOptimization","commit_stats":{"total_commits":322,"total_committers":44,"mean_commits":7.318181818181818,"dds":0.65527950310559,"last_synced_commit":"8cc0f0e751a28befbee2ce300f62ec6271f19037"},"previous_names":["fmfn/bayesianoptimization"],"tags_count":19,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bayesian-optimization%2FBayesianOptimization","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bayesian-optimization%2FBayesianOptimization/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bayesian-optimization%2FBayesianOptimization/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bayesian-optimization%2FBayesianOptimization/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/bayesian-optimization","download_url":"https://codeload.github.com/bayesian-optimization/BayesianOptimization/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247134525,"owners_count":20889401,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bayesian-optimization","gaussian-processes","optimization","python","simple"],"created_at":"2024-08-01T14:00:47.485Z","updated_at":"2025-04-04T06:31:46.856Z","avatar_url":"https://github.com/bayesian-optimization.png","language":"Python","funding_links":[],"categories":["Python","Uncategorized"],"sub_categories":["Uncategorized"],"readme":"\u003cdiv align=\"center\"\u003e\n  \u003cimg src=\"https://raw.githubusercontent.com/bayesian-optimization/BayesianOptimization/master/docsrc/static/func.png\"\u003e\u003cbr\u003e\u003cbr\u003e\n\u003c/div\u003e\n\n# Bayesian Optimization\n\n![tests](https://github.com/bayesian-optimization/BayesianOptimization/actions/workflows/run_tests.yml/badge.svg)\n[![Codecov](https://codecov.io/github/bayesian-optimization/BayesianOptimization/badge.svg?branch=master\u0026service=github)](https://codecov.io/github/bayesian-optimization/BayesianOptimization?branch=master)\n[![Pypi](https://img.shields.io/pypi/v/bayesian-optimization.svg)](https://pypi.python.org/pypi/bayesian-optimization)![PyPI - Python Version](https://img.shields.io/pypi/pyversions/bayesian-optimization)\n\nPure Python implementation of bayesian global optimization with gaussian\nprocesses.\n\n## Installation\n\n* PyPI (pip):\n\n```console\n$ pip install bayesian-optimization\n```\n\n* Conda from conda-forge channel:\n\n```console\n$ conda install -c conda-forge bayesian-optimization\n```\n\nThis is a constrained global optimization package built upon bayesian inference\nand gaussian process, that attempts to find the maximum value of an unknown\nfunction in as few iterations as possible. This technique is particularly\nsuited for optimization of high cost functions, situations where the balance\nbetween exploration and exploitation is important.\n\n## Quick Start\nSee below for a quick tour over the basics of the Bayesian Optimization package. More detailed information, other advanced features, and tips on usage/implementation can be found in the [examples](http://bayesian-optimization.github.io/BayesianOptimization/examples.html) folder. I suggest that you:\n- Follow the [basic tour notebook](http://bayesian-optimization.github.io/BayesianOptimization/basic-tour.html) to learn how to use the package's most important features.\n- Take a look at the [advanced tour notebook](http://bayesian-optimization.github.io/BayesianOptimization/advanced-tour.html) to learn how to make the package more flexible, how to deal with categorical parameters, how to use observers, and more.\n- Check out this [notebook](http://bayesian-optimization.github.io/BayesianOptimization/visualization.html) with a step by step visualization of how this method works.\n- To understand how to use bayesian optimization when additional constraints are present, see the [constrained optimization notebook](http://bayesian-optimization.github.io/BayesianOptimization/constraints.html).\n- Explore this [notebook](http://bayesian-optimization.github.io/BayesianOptimization/exploitation_vs_exploration.html)\nexemplifying the balance between exploration and exploitation and how to\ncontrol it.\n- Go over this [script](https://github.com/bayesian-optimization/BayesianOptimization/blob/master/examples/sklearn_example.py)\nfor examples of how to tune parameters of Machine Learning models using cross validation and bayesian optimization.\n- Explore the [domain reduction notebook](http://bayesian-optimization.github.io/BayesianOptimization/domain_reduction.html) to learn more about how search can be sped up by dynamically changing parameters' bounds.\n- Finally, take a look at this [script](https://github.com/bayesian-optimization/BayesianOptimization/blob/master/examples/async_optimization.py)\nfor ideas on how to implement bayesian optimization in a distributed fashion using this package.\n\n\n## How does it work?\n\nBayesian optimization works by constructing a posterior distribution of functions (gaussian process) that best describes the function you want to optimize. As the number of observations grows, the posterior distribution improves, and the algorithm becomes more certain of which regions in parameter space are worth exploring and which are not, as seen in the picture below.\n\n![BayesianOptimization in action](docsrc/static/bo_example.png)\n\nAs you iterate over and over, the algorithm balances its needs of exploration and exploitation taking into account what it knows about the target function. At each step a Gaussian Process is fitted to the known samples (points previously explored), and the posterior distribution, combined with a exploration strategy (such as UCB (Upper Confidence Bound), or EI (Expected Improvement)), are used to determine the next point that should be explored (see the gif below).\n\n![BayesianOptimization in action](docsrc/static/bayesian_optimization.gif)\n\nThis process is designed to minimize the number of steps required to find a combination of parameters that are close to the optimal combination. To do so, this method uses a proxy optimization problem (finding the maximum of the acquisition function) that, albeit still a hard problem, is cheaper (in the computational sense) and common tools can be employed. Therefore Bayesian Optimization is most adequate for situations where sampling the function to be optimized is a very expensive endeavor. See the references for a proper discussion of this method.\n\nThis project is under active development, if you find a bug, or anything that\nneeds correction, please let me know.\n\n\n## Basic tour of the Bayesian Optimization package\n\n### 1. Specifying the function to be optimized\n\nThis is a function optimization package, therefore the first and most important ingredient is, of course, the function to be optimized.\n\n**DISCLAIMER:** We know exactly how the output of the function below depends on its parameter. Obviously this is just an example, and you shouldn't expect to know it in a real scenario. However, it should be clear that you don't need to. All you need in order to use this package (and more generally, this technique) is a function `f` that takes a known set of parameters and outputs a real number.\n\n\n```python\ndef black_box_function(x, y):\n    \"\"\"Function with unknown internals we wish to maximize.\n\n    This is just serving as an example, for all intents and\n    purposes think of the internals of this function, i.e.: the process\n    which generates its output values, as unknown.\n    \"\"\"\n    return -x ** 2 - (y - 1) ** 2 + 1\n```\n\n### 2. Getting Started\n\nAll we need to get started is to instantiate a `BayesianOptimization` object specifying a function to be optimized `f`, and its parameters with their corresponding bounds, `pbounds`. This is a constrained optimization technique, so you must specify the minimum and maximum values that can be probed for each parameter in order for it to work\n\n\n```python\nfrom bayes_opt import BayesianOptimization\n\n# Bounded region of parameter space\npbounds = {'x': (2, 4), 'y': (-3, 3)}\n\noptimizer = BayesianOptimization(\n    f=black_box_function,\n    pbounds=pbounds,\n    random_state=1,\n)\n```\n\nThe BayesianOptimization object will work out of the box without much tuning needed. The main method you should be aware of is `maximize`, which does exactly what you think it does.\n\nThere are many parameters you can pass to maximize, nonetheless, the most important ones are:\n- `n_iter`: How many steps of bayesian optimization you want to perform. The more steps the more likely to find a good maximum you are.\n- `init_points`: How many steps of **random** exploration you want to perform. Random exploration can help by diversifying the exploration space.\n\n\n```python\noptimizer.maximize(\n    init_points=2,\n    n_iter=3,\n)\n```\n\n    |   iter    |  target   |     x     |     y     |\n    -------------------------------------------------\n    |  1        | -7.135    |  2.834    |  1.322    |\n    |  2        | -7.78     |  2.0      | -1.186    |\n    |  3        | -19.0     |  4.0      |  3.0      |\n    |  4        | -16.3     |  2.378    | -2.413    |\n    |  5        | -4.441    |  2.105    | -0.005822 |\n    =================================================\n\n\nThe best combination of parameters and target value found can be accessed via the property `optimizer.max`.\n\n\n```python\nprint(optimizer.max)\n\u003e\u003e\u003e {'target': -4.441293113411222, 'params': {'y': -0.005822117636089974, 'x': 2.104665051994087}}\n```\n\n\nWhile the list of all parameters probed and their corresponding target values is available via the property `optimizer.res`.\n\n\n```python\nfor i, res in enumerate(optimizer.res):\n    print(\"Iteration {}: \\n\\t{}\".format(i, res))\n\n\u003e\u003e\u003e Iteration 0:\n\u003e\u003e\u003e     {'target': -7.135455292718879, 'params': {'y': 1.3219469606529488, 'x': 2.8340440094051482}}\n\u003e\u003e\u003e Iteration 1:\n\u003e\u003e\u003e     {'target': -7.779531005607566, 'params': {'y': -1.1860045642089614, 'x': 2.0002287496346898}}\n\u003e\u003e\u003e Iteration 2:\n\u003e\u003e\u003e     {'target': -19.0, 'params': {'y': 3.0, 'x': 4.0}}\n\u003e\u003e\u003e Iteration 3:\n\u003e\u003e\u003e     {'target': -16.29839645063864, 'params': {'y': -2.412527795983739, 'x': 2.3776144540856503}}\n\u003e\u003e\u003e Iteration 4:\n\u003e\u003e\u003e     {'target': -4.441293113411222, 'params': {'y': -0.005822117636089974, 'x': 2.104665051994087}}\n```\n\n\n#### 2.1 Changing bounds\n\nDuring the optimization process you may realize the bounds chosen for some parameters are not adequate. For these situations you can invoke the method `set_bounds` to alter them. You can pass any combination of **existing** parameters and their associated new bounds.\n\n\n```python\noptimizer.set_bounds(new_bounds={\"x\": (-2, 3)})\n\noptimizer.maximize(\n    init_points=0,\n    n_iter=5,\n)\n```\n\n    |   iter    |  target   |     x     |     y     |\n    -------------------------------------------------\n    |  6        | -5.145    |  2.115    | -0.2924   |\n    |  7        | -5.379    |  2.337    |  0.04124  |\n    |  8        | -3.581    |  1.874    | -0.03428  |\n    |  9        | -2.624    |  1.702    |  0.1472   |\n    |  10       | -1.762    |  1.442    |  0.1735   |\n    =================================================\n\n#### 2.2 Sequential Domain Reduction\n\nSometimes the initial boundaries specified for a problem are too wide, and adding points to improve the response surface in regions of the solution domain is extraneous. Other times the cost function is very expensive to compute, and minimizing the number of calls is extremely beneficial.\n\nWhen it's worthwhile to converge on an optimal point quickly rather than try to find the optimal point, contracting the domain around the current optimal value as the search progresses can speed up the search progress considerably. Using the `SequentialDomainReductionTransformer` the bounds of the problem can be panned and zoomed dynamically in an attempt to improve convergence.\n\n![sequential domain reduction](docsrc/static/sdr.png)\n\nAn example of using the `SequentialDomainReductionTransformer` is shown in the [domain reduction notebook](http://bayesian-optimization.github.io/BayesianOptimization/domain_reduction.html). More information about this method can be found in the paper [\"On the robustness of a simple domain reduction scheme for simulation‐based optimization\"](http://www.truegrid.com/srsm_revised.pdf).\n\n### 3. Guiding the optimization\n\nIt is often the case that we have an idea of regions of the parameter space where the maximum of our function might lie. For these situations the `BayesianOptimization` object allows the user to specify points to be probed. By default these will be explored lazily (`lazy=True`), meaning these points will be evaluated only the next time you call `maximize`. This probing process happens before the gaussian process takes over.\n\nParameters can be passed as dictionaries or as an iterable.\n\n```python\noptimizer.probe(\n    params={\"x\": 0.5, \"y\": 0.7},\n    lazy=True,\n)\n\noptimizer.probe(\n    params=[-0.3, 0.1],\n    lazy=True,\n)\n\n# Will probe only the two points specified above\noptimizer.maximize(init_points=0, n_iter=0)\n```\n\n    |   iter    |  target   |     x     |     y     |\n    -------------------------------------------------\n    |  11       |  0.66     |  0.5      |  0.7      |\n    |  12       |  0.1      | -0.3      |  0.1      |\n    =================================================\n\n\n### 4. Saving, loading and restarting\n\nBy default you can follow the progress of your optimization by setting `verbose\u003e0` when instantiating the `BayesianOptimization` object. If you need more control over logging/alerting you will need to use an observer. For more information about observers checkout the advanced tour notebook. Here we will only see how to use the native `JSONLogger` object to save to and load progress from files.\n\n#### 4.1 Saving progress\n\n\n```python\nfrom bayes_opt.logger import JSONLogger\nfrom bayes_opt.event import Events\n```\n\nThe observer paradigm works by:\n1. Instantiating an observer object.\n2. Tying the observer object to a particular event fired by an optimizer.\n\nThe `BayesianOptimization` object fires a number of internal events during optimization, in particular, everytime it probes the function and obtains a new parameter-target combination it will fire an `Events.OPTIMIZATION_STEP` event, which our logger will listen to.\n\n**Caveat:** The logger will not look back at previously probed points.\n\n\n```python\nlogger = JSONLogger(path=\"./logs.log\")\noptimizer.subscribe(Events.OPTIMIZATION_STEP, logger)\n\n# Results will be saved in ./logs.log\noptimizer.maximize(\n    init_points=2,\n    n_iter=3,\n)\n```\n\nBy default the previous data in the json file is removed. If you want to keep working with the same logger, the `reset` parameter in `JSONLogger` should be set to False.\n\n#### 4.2 Loading progress\n\nNaturally, if you stored progress you will be able to load that onto a new instance of `BayesianOptimization`. The easiest way to do it is by invoking the `load_logs` function, from the `util` submodule.\n\n\n```python\nfrom bayes_opt.util import load_logs\n\n\nnew_optimizer = BayesianOptimization(\n    f=black_box_function,\n    pbounds={\"x\": (-2, 2), \"y\": (-2, 2)},\n    verbose=2,\n    random_state=7,\n)\n\n# New optimizer is loaded with previously seen points\nload_logs(new_optimizer, logs=[\"./logs.log\"]);\n```\n\n## Next Steps\n\nThis introduction covered the most basic functionality of the package. Checkout the [basic-tour](http://bayesian-optimization.github.io/BayesianOptimization/basic-tour.html) and [advanced-tour](http://bayesian-optimization.github.io/BayesianOptimization/advanced-tour.html), where you will find detailed explanations and other more advanced functionality. Also, browse the [examples](http://bayesian-optimization.github.io/BayesianOptimization/examples.html) for implementation tips and ideas.\n\n## Minutiae\n\n### Citation\n\nIf you used this package in your research, please cite it:\n\n```\n@Misc{,\n    author = {Fernando Nogueira},\n    title = {{Bayesian Optimization}: Open source constrained global optimization tool for {Python}},\n    year = {2014--},\n    url = \" https://github.com/bayesian-optimization/BayesianOptimization\"\n}\n```\nIf you used any of the advanced functionalities, please additionally cite the corresponding publication:\n\nFor the `SequentialDomainTransformer`:\n```\n@article{\n    author = {Stander, Nielen and Craig, Kenneth},\n    year = {2002},\n    month = {06},\n    pages = {},\n    title = {On the robustness of a simple domain reduction scheme for simulation-based optimization},\n    volume = {19},\n    journal = {International Journal for Computer-Aided Engineering and Software (Eng. Comput.)},\n    doi = {10.1108/02644400210430190}\n}\n```\n\nFor constrained optimization:\n```\n@inproceedings{gardner2014bayesian,\n    title={Bayesian optimization with inequality constraints.},\n    author={Gardner, Jacob R and Kusner, Matt J and Xu, Zhixiang Eddie and Weinberger, Kilian Q and Cunningham, John P},\n    booktitle={ICML},\n    volume={2014},\n    pages={937--945},\n    year={2014}\n}\n```\n\n### References:\n* http://papers.nips.cc/paper/4522-practical-bayesian-optimization-of-machine-learning-algorithms.pdf\n* http://arxiv.org/pdf/1012.2599v1.pdf\n* http://www.gaussianprocess.org/gpml/\n* https://www.youtube.com/watch?v=vz3D36VXefI\u0026index=10\u0026list=PLE6Wd9FR--EdyJ5lbFl8UuGjecvVw66F6\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbayesian-optimization%2FBayesianOptimization","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbayesian-optimization%2FBayesianOptimization","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbayesian-optimization%2FBayesianOptimization/lists"}