{"slug": "exploring-bayesian-optimization", "title": "Exploring Bayesian Optimization", "summary": "Bayesian optimization is a technique used to tune hyperparameters in machine learning algorithms by optimizing black-box functions. The article explains the process using a gold mining analogy, where the goal is to find the location of maximum gold content with minimal costly drilling. It contrasts this with active learning, which aims to accurately estimate the entire gold distribution, while Bayesian optimization focuses on efficiently locating the maximum value.", "body_md": "[Distill](/)\n\nBreaking Bayesian Optimization into small, sizeable chunks.\n\nMany modern machine learning algorithms have a large number of hyperparameters. To effectively use these algorithms, we need to pick good hyperparameter values. In this article, we talk about Bayesian Optimization, a suite of techniques often used to tune hyperparameters. More generally, Bayesian Optimization can be used to optimize any black-box function.\n\nLet us start with the example of gold mining. Our goal is to mine for gold in an unknown land\n\nLet us suppose that the gold distribution looks something like the function below. It is bi-modal, with a maximum value around . For now, let us not worry about the X-axis or the Y-axis units.\n\nInitially, we have no idea about the gold distribution. We can learn the gold distribution by drilling at different locations. However, this drilling is costly. Thus, we want to minimize the number of drillings required while still finding the location of maximum gold quickly.\n\nWe now discuss two common objectives for the gold mining problem.\n\n**Problem 1: Best Estimate of Gold Distribution (Active Learning)**\n\nIn this problem, we want to accurately estimate the gold distribution on the new land. We can not drill at every location due to the prohibitive cost. Instead, we should drill at locations providing **high information** about the gold distribution. This problem is akin to\n**\nActive Learning\n**.\n\n**Problem 2: Location of Maximum Gold (Bayesian Optimization)**\n\nIn this problem, we want to find the location of the maximum gold content. We, again, can not drill at every location. Instead, we should drill at locations showing **high promise** about the gold content. This problem is akin to\n**\nBayesian Optimization\n**.\n\nWe will soon see how these two problems are related, but not the same.\n\nFor many machine learning problems, unlabeled data is readily available. However, labeling (or querying) is often expensive. As an example, for a speech-to-text task, the annotation requires expert(s) to label words and sentences manually. Similarly, in our gold mining problem, drilling (akin to labeling) is expensive.\n\nActive learning minimizes labeling costs while maximizing modeling accuracy. While there are various methods in active learning literature, we look at **uncertainty reduction**. This method proposes labeling the point whose model uncertainty is the highest. Often, the variance acts as a measure of uncertainty.\n\nSince we only know the true value of our function at a few points, we need a *surrogate model* for the values our function takes elsewhere. This surrogate should be flexible enough to model the true function. Using a Gaussian Process (GP) is a common choice, both because of its flexibility and its ability to give us uncertainty estimates\n\nPlease find [this](https://youtu.be/EnXxO3BAgYk) amazing video from Javier González on Gaussian Processes.\n\nOur surrogate model starts with a prior of — in the case of gold, we pick a prior assuming that it’s smoothly distributed\n[Rasmussen and Williams 2004](http://www.gaussianprocess.org/gpml/) and [scikit-learn](https://scikit-learn.org/stable/modules/generated/sklearn.gaussian_process.kernels.Matern.html), for details regarding the Matern kernel.\n\nIn the above example, we started with uniform uncertainty. But after our first update, the posterior is certain near and uncertain away from it. We could just keep adding more training points and obtain a more certain estimate of .\n\nHowever, we want to minimize the number of evaluations. Thus, we should choose the next query point “smartly” using active learning. Although there are many ways to pick smart points, we will be picking the most uncertain one.\n\nThis gives us the following procedure for Active Learning:\n\nLet us now visualize this process and see how our posterior changes at every iteration (after each drilling).\n\nThe visualization shows that one can estimate the true distribution in a few iterations. Furthermore, the most uncertain positions are often the farthest points from the current evaluation points. At every iteration, active learning **explores** the domain to make the estimates better.\n\nIn the previous section, we picked points in order to determine an accurate model of the gold content. But what if our goal is simply to find the location of maximum gold content? Of course, we could do active learning to estimate the true function accurately and then find its maximum. But that seems pretty wasteful — why should we use evaluations improving our estimates of regions where the function expects low gold content when we only care about the maximum?\n\nThis is the core question in Bayesian Optimization: “Based on what we know so far, which point should we evaluate next?” Remember that evaluating each point is expensive, so we want to pick carefully! In the active learning case, we picked the most uncertain point, exploring the function. But in Bayesian Optimization, we need to balance exploring uncertain regions, which might unexpectedly have high gold content, against focusing on regions we already know have higher gold content (a kind of exploitation).\n\nWe make this decision with something called an acquisition function. Acquisition functions are heuristics for how desirable it is to evaluate a point, based on our present model[link](https://botorch.org/docs/acquisition).\n\nThis brings us to how Bayesian Optimization works. At every step, we determine what the best point to evaluate next is according to the acquisition function by optimizing it. We then update our model and repeat this process to determine the next point to evaluate.\n\nYou may be wondering what’s “Bayesian” about Bayesian Optimization if we’re just optimizing these acquisition functions. Well, at every step we maintain a model describing our estimates and uncertainty at each point, which we update according to Bayes’ rule\n\n## General Constraints |\n## Constraints in Gold Mining example |\n|---|---|\n| ’s feasible set is simple, e.g., box constraints. | Our domain in the gold mining problem is a single-dimensional box constraint: . |\n| is continuous but lacks special structure, e.g., concavity, that would make it easy to optimize. | Our true function is neither a convex nor a concave function, resulting in local optimums. |\n| is derivative-free: evaluations do not give gradient information. | Our evaluation (by drilling) of the amount of gold content at a location did not give us any gradient information. |\n| is expensive to evaluate: the number of times we can evaluate it is severely limited. | Drilling is costly. |\n| may be noisy. If noise is present, we will assume it is independent and normally distributed, with common but unknown variance. | We assume noiseless measurements in our modeling (though, it is easy to incorporate normally distributed noise for GP regression). |\n\nTo solve this problem, we will follow the following algorithm:\n\nAcquisition functions are crucial to Bayesian Optimization, and there are a wide variety of options[these](https://www.cse.wustl.edu/~garnett/cse515t/spring_2015/files/lecture_notes/12.pdf) slides from Washington University in St. Louis to know more about acquisition functions.\n\nThis acquisition function chooses the next query point as the one which has the highest *probability of improvement* over the current max . Mathematically, we write the selection of next point as follows,\n\nwhere,\n\nLooking closely, we are just finding the upper-tail probability (or the CDF) of the surrogate posterior. Moreover, if we are using a GP as a surrogate the expression above converts to,\n\nwhere,\n\nThe visualization below shows the calculation of . The orange line represents the current max (plus an ) or . The violet region shows the probability density at each point. The grey regions show the probability density below the current max. The “area” of the violet region at each point represents the “probability of improvement over current maximum”. The next point to evaluate via the PI criteria (shown in dashed blue line) is .\n\nPI uses to strike a balance between exploration and exploitation. Increasing results in querying locations with a larger as their probability density is spread.\n\nLet us now see the PI acquisition function in action. We start with .\n\nLooking at the graph above, we see that we reach the global maxima in a few iterations**exploits** regions with a high promise\n\nThe visualization above shows that increasing to 0.3, enables us to **explore** more. However, it seems that we are exploring more than required.\n\nWhat happens if we increase a bit more?\n\nWe see that we made things worse! Our model now uses , and we are unable to exploit when we land near the global maximum. Moreover, with high exploration, the setting becomes similar to active learning.\n\nOur quick experiments above help us conclude that controls the degree of exploration in the PI acquisition function.\n\nProbability of improvement only looked at *how likely* is an improvement, but, did not consider *how much* we can improve. The next criterion, called Expected Improvement (EI), does exactly that[this post](https://thuijskens.github.io/2016/12/29/bayesian-optimisation/) by Thomas Huijskens and [these slides](https://people.orie.cornell.edu/pfrazier/Presentations/2018.11.INFORMS.tutorial.pdf) by Peter Frazier\n\nIn this acquisition function, query point, , is selected according to the following equation.\n\nWhere, is the actual ground truth function, is the posterior mean of the surrogate at timestep, is the training data and is the actual position where takes the maximum value.\n\nIn essence, we are trying to select the point that minimizes the distance to the objective evaluated at the maximum. Unfortunately, we do not know the ground truth function, . Mockus\n\nwhere is the maximum value that has been encountered so far. This equation for GP surrogate is an analytical expression shown below.\n\nwhere indicates CDF and indicates pdf.\n\nFrom the above expression, we can see that *Expected Improvement* will be high when: i) the expected value of is high, or, ii) when the uncertainty around a point is high.\n\nLike the PI acquisition function, we can moderate the amount of exploration of the EI acquisition function by modifying .\n\nFor we come close to the global maxima in a few iterations.\n\nWe now increase to explore more.\n\nAs we expected, increasing the value to makes the acquisition function explore more. Compared to the earlier evaluations, we see less exploitation. We see that it evaluates only two points near the global maxima.\n\nLet us increase even more.\n\nIs this better than before? It turns out a yes and a no; we explored too much at and quickly reached near the global maxima. But unfortunately, we did not exploit to get more gains near the global maxima.\n\nWe have seen two closely related methods, The *Probability of Improvement* and the *Expected Improvement*.\n\nThe scatter plot above shows the policies’ acquisition functions evaluated on different points\n\nAnother common acquisition function is Thompson Sampling\n\nBelow we have an image showing three sampled functions from the learned surrogate posterior for our gold mining problem. The training data constituted the point and the corresponding functional value.\n\nWe can understand the intuition behind Thompson sampling by two observations:\n\nLocations with high uncertainty () will show a large variance in the functional values sampled from the surrogate posterior. Thus, there is a non-trivial probability that a sample can take high value in a highly uncertain region. Optimizing such samples can aid **exploration**.\n\nAs an example, the three samples (sample #1, #2, #3) show a high variance close to . Optimizing sample 3 will aid in exploration by evaluating .\n\nThe sampled functions must pass through the current max value, as there is no uncertainty at the evaluated locations. Thus, optimizing samples from the surrogate posterior will ensure **exploiting** behavior.\n\nAs an example of this behavior, we see that all the sampled functions above pass through the current max at . If were close to the global maxima, then we would be able to **exploit** and choose a better maximum.\n\nThe visualization above uses Thompson sampling for optimization. Again, we can reach the global optimum in relatively few iterations.\n\nWe have been using intelligent acquisition functions until now. We can create a random acquisition function by sampling randomly.\n\nThe visualization above shows that the performance of the random acquisition function is not that bad! However, if our optimization was more complex (more dimensions), then the random acquisition might perform poorly.\n\nLet us now summarize the core ideas associated with acquisition functions: i) they are heuristics for evaluating the utility of a point; ii) they are a function of the surrogate posterior; iii) they combine exploration and exploitation; and iv) they are inexpensive to evaluate.\n\nWe have seen various acquisition functions until now. One trivial way to come up with acquisition functions is to have a explore/exploit combination.\n\nOne such trivial acquisition function that combines the exploration/exploitation tradeoff is a linear combination of the mean and uncertainty of our surrogate model. The model mean signifies exploitation (of our model’s knowledge) and model uncertainty signifies exploration (due to our model’s lack of observations).\n\nThe intuition behind the UCB acquisition function is weighing of the importance between the surrogate’s mean vs. the surrogate’s uncertainty. The above is the hyperparameter that can control the preference between exploitation or exploration.\n\nWe can further form acquisition functions by combining the existing acquisition functions though the physical interpretability of such combinations might not be so straightforward. One reason we might want to combine two methods is to overcome the limitations of the individual methods.\n\nOne such combination can be a linear combination of PI and EI. We know PI focuses on the probability of improvement, whereas EI focuses on the expected improvement. Such a combination could help in having a tradeoff between the two based on the value of .\n\nBefore talking about GP-UCB, let us quickly talk about **regret**. Imagine if the maximum gold was units, and our optimization instead samples a location containing units, then our regret is\n. If we accumulate the regret over iterations, we get what is called ** cumulative regret. **\n\nGP-UCB’s\n\nWhere is the timestep.\n\nSrinivas et. al.\n\nWe now compare the performance of different acquisition functions on the gold mining problem[these](https://www.cs.ubc.ca/~nando/540-2013/lectures/l7.pdf) amazing\nslides from Nando De Freitas\n\nThe *random* strategy is initially comparable to or better than other acquisition functions*random* strategy grows slowly. In comparison, the other acquisition functions can find a good solution in a small number of iterations. In fact, most acquisition functions reach fairly close to the global maxima in as few as three iterations.\n\nBefore we talk about Bayesian optimization for hyperparameter tuning\n\nIn Ridge regression, the weight matrix is the parameter, and the regularization coefficient is the hyperparameter.\n\nIf we solve the above regression problem via gradient descent optimization, we further introduce another optimization parameter, the learning rate .\n\nThe most common use case of Bayesian Optimization is *hyperparameter tuning*: finding the best performing hyperparameters on machine learning models.\n\nWhen training a model is not expensive and time-consuming, we can do a grid search to find the optimum hyperparameters. However, grid search is not feasible if function evaluations are costly, as in the case of a large neural network that takes days to train. Further, grid search scales poorly in terms of the number of hyperparameters.\n\nWe turn to Bayesian Optimization to counter the expensive nature of evaluating our black-box function (accuracy).\n\nIn this example, we use an SVM to classify on sklearn’s moons dataset and use Bayesian Optimization to optimize SVM hyperparameters.\n\nLet us have a look at the dataset now, which has two classes and two features.\n\nLet us apply Bayesian Optimization to learn the best hyperparameters for this classification task**Note**: the surface plots you see for the Ground Truth Accuracies below were calculated for each possible hyperparameter for showcasing purposes only. We do not have these values in real applications.\n\nAbove we see a slider showing the work of the *Probability of Improvement* acquisition function in finding the best hyperparameters.\n\nAbove we see a slider showing the work of the *Expected Improvement* acquisition function in finding the best hyperparameters.\n\nBelow is a plot that compares the different acquisition functions. We ran the *random* acquisition function several times to average out its results.\n\nAll our acquisition beat the *random* acquisition function after seven iterations. We see the *random* method seemed to perform much better initially, but it could not reach the global optimum, whereas Bayesian Optimization was able to get fairly close. The initial subpar performance of Bayesian Optimization can be attributed to the initial exploration.\n\nUsing Bayesian Optimization in a Random Forest Classifier.\n\nWe will continue now to train a Random Forest on the moons dataset we had used previously to learn the Support Vector Machine model. The primary hyperparameters of Random Forests we would like to optimize our accuracy are the ** number** of\nDecision Trees we would like to have, the **maximum depth** for each of those decision trees.\n\nThe parameters of the Random Forest are the individual trained Decision Trees models.\n\nWe will be again using Gaussian Processes with Matern kernel to estimate and predict the accuracy function over the two hyperparameters.\n\nAbove is a typical Bayesian Optimization run with the *Probability of Improvement* acquisition function.\n\nAbove we see a run showing the work of the *Expected Improvement* acquisition function in optimizing the hyperparameters.\n\nNow using the *Gaussian Processes Upper Confidence Bound* acquisition function in optimizing the hyperparameters.\n\nLet us now use the Random acquisition function.\n\nThe optimization strategies seemed to struggle in this example. This can be attributed to the non-smooth ground truth. This shows that the effectiveness of Bayesian Optimization depends on the surrogate’s efficiency to model the actual black-box function. It is interesting to notice that the Bayesian Optimization framework still beats the *random* strategy using various acquisition functions.\n\nLet us take this example to get an idea of how to apply Bayesian Optimization to train neural networks. Here we will be using `scikit-optim`\n\n, which also provides us support for optimizing function with a search space of categorical, integral, and real variables. We will not be plotting the ground truth here, as it is extremely costly to do so. Below are some code snippets that show the ease of using Bayesian Optimization packages for hyperparameter tuning.\n\nThe code initially declares a search space for the optimization problem. We limit the search space to be the following:\n\nNow import `gp-minimize`\n\n**Note**: One will need to negate the accuracy values as we are using the minimizer function from `scikit-optim`\n\n.`scikit-optim`\n\nto perform the optimization. Below we show calling the optimizer using *Expected Improvement*, but of course we can select from a number of other acquisition functions.\n\nIn the graph above the y-axis denotes the best accuracy till then, and the x-axis denotes the evaluation number.\n\nLooking at the above example, we can see that incorporating Bayesian Optimization is not difficult and can save a lot of time. Optimizing to get an accuracy of nearly one in around seven iterations is impressive![Hvass Laboratories’ Tutorial Notebook](https://github.com/Hvass-Labs/TensorFlow-Tutorials/blob/master/19_Hyper-Parameters.ipynb) showcasing hyperparameter optimization in TensorFlow using `scikit-optim`\n\n.\n\nLet us get the numbers into perspective. If we had run this optimization using a grid search, it would have taken around iterations. Whereas Bayesian Optimization only took seven iterations. Each iteration took around fifteen minutes; this sets the time required for the grid search to complete around seventeen hours!\n\nIn this article, we looked at Bayesian Optimization for optimizing a black-box function. Bayesian Optimization is well suited when the function evaluations are expensive, making grid or exhaustive search impractical. We looked at the key components of Bayesian Optimization. First, we looked at the notion of using a surrogate function (with a prior over the space of objective functions) to model our black-box function. Next, we looked at the “Bayes” in Bayesian Optimization — the function evaluations are used as data to obtain the surrogate posterior. We look at acquisition functions, which are functions of the surrogate posterior and are optimized sequentially. This new sequential optimization is in-expensive and thus of utility of us. We also looked at a few acquisition functions and showed how these different functions balance exploration and exploitation. Finally, we looked at some practical examples of Bayesian Optimization for optimizing hyper-parameters for machine learning models.\n\nWe hope you had a good time reading the article and hope you are ready to **exploit** the power of Bayesian Optimization. In case you wish to **explore** more, please read the [Further Reading](#FurtherReading) section below. We also provide our [repository](https://github.com/distillpub/post--bayesian-optimization) to reproduce the entire article.\n\nHaving read all the way through, you might have been sold on the idea about the time you can save by asking Bayesian Optimizer to find the best hyperparameters for your fantastic model. There are a plethora of Bayesian Optimization libraries available. We have linked a few below. Do check them out.\n\nThis article was made possible with inputs from numerous people. Firstly, we would like to thank all the Distill reviewers for their punctilious and actionable feedback. These fantastic reviews immensely helped strengthen our article. We further express our gratitude towards the Distill Editors, who were extremely kind and helped us navigate various steps to publish our work. We would also like to thank [Dr. Sahil Garg](https://sgarg87.github.io/) for his feedback on the flow of the article. We would like to acknowledge the help we received from [Writing Studio](http://initiatives.iitgn.ac.in/writingstudio/wp/) to improve the script of our article. Lastly, we sincerely thank [Christopher Olah](https://colah.github.io/). His inputs, suggestions, multiple rounds of iterations made this article substantially better.\n\nUsing gradient information when it is available.\n\nTo have a quick view of differences between Bayesian Optimization and Gradient Descent, one can look at [this](https://stats.stackexchange.com/q/161936) amazing answer at StackOverflow.\n\nWe talked about optimizing a black-box function here. If we are to perform over multiple objectives, how do these acquisition functions scale? There has been fantastic work in this domain too! We try to deal with these cases by having multi-objective acquisition functions. Have a look at [this excellent](https://gpflowopt.readthedocs.io/en/latest/notebooks/multiobjective.html) notebook for an example using `gpflowopt`\n\n.\n\nOne of the more interesting uses of hyperparameters optimization can be attributed to searching the space of neural network architecture for finding the architectures that give us maximal predictive performance. One might also want to consider nonobjective optimizations as some of the other objectives like memory consumption, model size, or inference time also matter in practical scenarios.\n\nWhen the datasets are extremely large, human experts tend to test hyperparameters on smaller subsets of the dataset and iteratively improve the accuracy for their models. There has been work in Bayesian Optimization, taking into account these approaches\n\nThere also has been work on Bayesian Optimization, where one explores with a certain level of “safety”, meaning the evaluated values should lie above a certain security threshold functional value\n\nWe have been using GP in our Bayesian Optimization for getting predictions, but we can have any other predictor or mean and variance in our Bayesian Optimization.\n\nOne can look at [this](http://aad.informatik.uni-freiburg.de/~hutter/ML3.pdf) slide deck by Frank Hutter discussing some limitations of a GP-based Bayesian Optimization over a Random Forest based Bayesian Optimization.\n\nThere has been work on even using deep neural networks in Bayesian Optimization\n\nThings to take care when using Bayesian Optimization.\n\nWhile working on the blog, we once scaled the accuracy from the range to . This change broke havoc as the Gaussian Processes we were using had certain hyperparameters, which needed to be scaled with the accuracy to maintain scale invariance. We wanted to point this out as it might be helpful for the readers who would like to start using on Bayesian Optimization.\n\nWe need to take care while using Bayesian Optimization. Bayesian Optimization based on Gaussian Processes Regression is highly sensitive to the kernel used. For example, if you are using [Matern](https://scikit-learn.org/stable/modules/generated/sklearn.gaussian_process.kernels.Matern.html) kernel, we are implicitly assuming that the function we are trying to optimize is first order differentiable.\n\nSearching for the hyperparameters, and the choice of the acquisition function to use in Bayesian Optimization are interesting problems in themselves. There has been amazing work done, looking at this problem. As mentioned previously in the post, there has\nbeen work done in strategies using multiple acquisition function\n\nA nice list of tips and tricks one should have a look at if you aim to use Bayesian Optimization in your workflow is from this fantastic post by Thomas on [Bayesian\nOptimization with sklearn](https://thuijskens.github.io/2016/12/29/bayesian-optimisation/).\n\nBayesian Optimization applications.\n\nBayesian Optimization has been applied to Optimal Sensor Set selection for predictive accuracy\n\nPeter Frazier in his [talk](https://www.youtube.com/watch?v=c4KKvyWW_Xk) mentioned that Uber uses Bayesian Optimization for tuning algorithms via backtesting.\n\nFacebook\n\nNetflix and [Yelp](https://engineeringblog.yelp.com/2014/10/using-moe-the-metric-optimization-engine-to-optimize-an-ab-testing-experiment-framework.html) use Metrics Optimization software like [Metrics Optimization Engine (MOE)](http://github.com/Yelp/MOE) which take advantage of Parallel Bayesian Optimization\n\nIf you see mistakes or want to suggest changes, please [create an issue on GitHub](https://github.com/distillpub/post--bayesian-optimization/issues/new).\n\nDiagrams and text are licensed under Creative Commons Attribution [CC-BY 4.0](https://creativecommons.org/licenses/by/4.0/) with the [source available on GitHub](https://github.com/distillpub/post--bayesian-optimization), unless noted otherwise. The figures that have been reused from other sources don’t fall under this license and can be recognized by a note in their caption: “Figure from …”.\n\nFor attribution in academic contexts, please cite this work as\n\n```\nAgnihotri & Batra, \"Exploring Bayesian Optimization\", Distill, 2020.\n```\n\nBibTeX citation\n\n```\n@article{agnihotri2020exploring,\n  author = {Agnihotri, Apoorv and Batra, Nipun},\n  title = {Exploring Bayesian Optimization},\n  journal = {Distill},\n  year = {2020},\n  note = {https://distill.pub/2020/bayesian-optimization},\n  doi = {10.23915/distill.00026}\n}\n```\n\n", "url": "https://wpnews.pro/news/exploring-bayesian-optimization", "canonical_source": "https://distill.pub/2020/bayesian-optimization", "published_at": "2020-05-05 20:00:00+00:00", "updated_at": "2026-05-19 23:18:35.700825+00:00", "lang": "en", "topics": ["machine-learning", "research", "data", "artificial-intelligence"], "entities": [], "alternates": {"html": "https://wpnews.pro/news/exploring-bayesian-optimization", "markdown": "https://wpnews.pro/news/exploring-bayesian-optimization.md", "text": "https://wpnews.pro/news/exploring-bayesian-optimization.txt", "jsonld": "https://wpnews.pro/news/exploring-bayesian-optimization.jsonld"}}