ray/doc/source/tune/examples/bayesopt_example.ipynb
Brett Göhre 9e0a59d94a
[docs] search algorithm notebook examples (#23924)
Co-authored-by: brettskymind <brett@pathmind.com>
Co-authored-by: Max Pumperla <max.pumperla@googlemail.com>
2022-04-25 11:10:58 -07:00

264 lines
7.4 KiB
Text
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{
"cells": [
{
"cell_type": "markdown",
"id": "db54cdf9",
"metadata": {},
"source": [
"# Running Tune experiments with BayesOpt\n",
"\n",
"In this tutorial we introduce BayesOpt, while running a simple Ray Tune experiment. Tunes Search Algorithms integrate with BayesOpt and, as a result, allow you to seamlessly scale up a BayesOpt optimization process - without sacrificing performance.\n",
"\n",
"BayesOpt is a constrained global optimization package utilizing Bayesian inference on gaussian processes, where the emphasis is on finding the maximum value of an unknown function in as few iterations as possible. BayesOpt's techniques are particularly suited for optimization of high cost functions, situations where the balance between exploration and exploitation is important. Therefore BayesOpt falls in the domain of \"derivative-free\" and \"black-box\" optimization. In this example we minimize a simple objective to briefly demonstrate the usage of BayesOpt with Ray Tune via `BayesOptSearch`, including conditional search spaces. It's useful to keep in mind that despite the emphasis on machine learning experiments, Ray Tune optimizes any implicit or explicit objective. Here we assume `bayesian-optimization==1.2.0` library is installed. To learn more, please refer to [BayesOpt website](https://github.com/fmfn/BayesianOptimization)."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7ed16354",
"metadata": {
"tags": [
"remove-cell"
]
},
"outputs": [],
"source": [
"# !pip install ray[tune]\n",
"!pip install bayesian-optimization==1.2.0"
]
},
{
"cell_type": "markdown",
"id": "2236f834",
"metadata": {},
"source": [
"Click below to see all the imports we need for this example.\n",
"You can also launch directly into a Binder instance to run this notebook yourself.\n",
"Just click on the rocket symbol at the top of the navigation."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6d36c78b",
"metadata": {
"tags": [
"hide-input"
]
},
"outputs": [],
"source": [
"import time\n",
"\n",
"import ray\n",
"from ray import tune\n",
"from ray.tune.suggest import ConcurrencyLimiter\n",
"from ray.tune.suggest.bayesopt import BayesOptSearch"
]
},
{
"cell_type": "markdown",
"id": "6257a3a8",
"metadata": {},
"source": [
"Let's start by defining a simple evaluation function.\n",
"We artificially sleep for a bit (`0.1` seconds) to simulate a long-running ML experiment.\n",
"This setup assumes that we're running multiple `step`s of an experiment and try to tune two hyperparameters,\n",
"namely `width` and `height`."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "646c75a9",
"metadata": {},
"outputs": [],
"source": [
"def evaluate(step, width, height):\n",
" time.sleep(0.1)\n",
" return (0.1 + width * step / 100) ** (-1) + height * 0.1"
]
},
{
"cell_type": "markdown",
"id": "d89b7fdc",
"metadata": {},
"source": [
"Next, our ``objective`` function takes a Tune ``config``, evaluates the `score` of your experiment in a training loop,\n",
"and uses `tune.report` to report the `score` back to Tune."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e9adf637",
"metadata": {},
"outputs": [],
"source": [
"def objective(config):\n",
" for step in range(config[\"steps\"]):\n",
" score = evaluate(step, config[\"width\"], config[\"height\"])\n",
" tune.report(iterations=step, mean_loss=score)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bc634b1d",
"metadata": {
"lines_to_next_cell": 0,
"tags": [
"remove-cell"
]
},
"outputs": [],
"source": [
"ray.init(configure_logging=False)"
]
},
{
"cell_type": "markdown",
"id": "0b9a2c4d",
"metadata": {},
"source": [
"Now we define the search algorithm built from `BayesOptSearch`, constrained to a maximum of `4` concurrent trials with a `ConcurrencyLimiter`."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6f1d2fe7",
"metadata": {},
"outputs": [],
"source": [
"algo = BayesOptSearch(utility_kwargs={\"kind\": \"ucb\", \"kappa\": 2.5, \"xi\": 0.0})\n",
"algo = ConcurrencyLimiter(algo, max_concurrent=4)"
]
},
{
"cell_type": "markdown",
"id": "27963e39",
"metadata": {},
"source": [
"The number of samples is the number of hyperparameter combinations that will be tried out. This Tune run is set to `1000` samples.\n",
"(you can decrease this if it takes too long on your machine)."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d777201c",
"metadata": {},
"outputs": [],
"source": [
"num_samples = 1000"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bb5f39a6",
"metadata": {
"tags": [
"remove-cell"
]
},
"outputs": [],
"source": [
"# If 1000 samples take too long, you can reduce this number.\n",
"# We override this number here for our smoke tests.\n",
"num_samples = 10"
]
},
{
"cell_type": "markdown",
"id": "752523c8",
"metadata": {},
"source": [
"Next we define a search space. The critical assumption is that the optimal hyperparameters live within this space. Yet, if the space is very large, then those hyperparameters may be difficult to find in a short amount of time."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "116f8757",
"metadata": {},
"outputs": [],
"source": [
"search_space = {\n",
" \"steps\": 100,\n",
" \"width\": tune.uniform(0, 20),\n",
" \"height\": tune.uniform(-100, 100),\n",
"}"
]
},
{
"cell_type": "markdown",
"id": "1754bf85",
"metadata": {},
"source": [
"Finally, we run the experiment to `\"min\"`imize the \"mean_loss\" of the `objective` by searching `search_config` via `algo`, `num_samples` times. This previous sentence is fully characterizes the search problem we aim to solve. With this in mind, notice how efficient it is to execute `tune.run()`."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5c44a0c5",
"metadata": {},
"outputs": [],
"source": [
"analysis = tune.run(\n",
" objective,\n",
" search_alg=algo,\n",
" metric=\"mean_loss\",\n",
" mode=\"min\",\n",
" name=\"bayesopt_exp\",\n",
" num_samples=num_samples,\n",
" config=search_space,\n",
")"
]
},
{
"cell_type": "markdown",
"id": "477f099b",
"metadata": {},
"source": [
"Here are the hyperparamters found to minimize the mean loss of the defined objective."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3488aefa",
"metadata": {},
"outputs": [],
"source": [
"print(\"Best hyperparameters found were: \", analysis.best_config)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2936353a",
"metadata": {
"tags": [
"remove-cell"
]
},
"outputs": [],
"source": [
"ray.shutdown()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"orphan": true
},
"nbformat": 4,
"nbformat_minor": 5
}