<jupyter_start><jupyter_text>Running Tune experiments with SkoptIn this tutorial we introduce Skopt, while running a simple Ray Tune experiment. Tune’s Search Algorithms integrate with Skopt and, as a result, allow you to seamlessly scale up a Skopt optimization process - without sacrificing performance.Scikit-Optimize, or skopt, is a simple and efficient library to optimize expensive and noisy black-box functions, e.g. large-scale ML experiments. It implements several methods for sequential model-based optimization. Noteably, skopt does not perform gradient-based optimization, and instead uses computationally cheap surrogate models toapproximate the expensive function. In this example we minimize a simple objective to briefly demonstrate the usage of Skopt with Ray Tune via `SkOptSearch`. 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 `scikit-opitmize==0.8.1` library is installed. To learn more, please refer to the [Scikit-Optimize website](https://scikit-optimize.github.io).<jupyter_code># !pip install ray[tune]
!pip install scikit-optimize==0.8.1
!pip install sklearn==0.18.2<jupyter_output><empty_output><jupyter_text>Click below to see all the imports we need for this example.You can also launch directly into a Binder instance to run this notebook yourself.Just click on the rocket symbol at the top of the navigation.<jupyter_code>import time
from typing import Dict, Optional, Any

import ray

import skopt
from ray import tune
from ray.tune.suggest import ConcurrencyLimiter
from ray.tune.suggest.skopt import SkOptSearch
ray.init(configure_logging=False)<jupyter_output><empty_output><jupyter_text>Let's start by defining a simple evaluation function. Again, an explicit math formula is queried here for demonstration, yet in practice this is typically a black-box function-- e.g. the performance results after training an ML model. We artificially sleep for a bit (`0.1` seconds) to simulate a long-running ML experiment. This setup assumes that we're running multiple `step`s of an experiment while tuning three hyperparameters, namely `width`, `height`, and `activation`.<jupyter_code>def evaluate(step, width, height, activation):
    time.sleep(0.1)
    activation_boost = 10 if activation=="relu" else 0
    return (0.1 + width * step / 100) ** (-1) + height * 0.1 + activation_boost<jupyter_output><empty_output><jupyter_text>Next, our `objective` function to be optimized takes a Tune `config`, evaluates the `score` of your experiment in a training loop,and uses `tune.report` to report the `score` back to Tune.<jupyter_code>def objective(config):
    for step in range(config["steps"]):
        score = evaluate(step, config["width"], config["height"], config["activation"])
        tune.report(iterations=step, mean_loss=score)<jupyter_output><empty_output><jupyter_text>Next we define a search space. The critical assumption is that the optimal hyperparamters 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.<jupyter_code>search_space = {
    "steps": 100,
    "width": tune.uniform(0, 20),
    "height": tune.uniform(-100, 100),
    "activation": tune.choice(["relu", "tanh"]),
}<jupyter_output><empty_output><jupyter_text>The search algorithm is instantiated from the `SkOptSearch` class. We also constrain the the number of concurrent trials to `4` with a `ConcurrencyLimiter`.<jupyter_code>algo = SkOptSearch()
algo = ConcurrencyLimiter(algo, max_concurrent=4)<jupyter_output><empty_output><jupyter_text>The number of samples is the number of hyperparameter combinations that will be tried out. This Tune run is set to `1000` samples.(you can decrease this if it takes too long on your machine).<jupyter_code>num_samples = 1000
# We override here for our smoke tests.
num_samples = 10<jupyter_output><empty_output><jupyter_text>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()`.<jupyter_code>analysis = tune.run(
    objective,
    search_alg=algo,
    metric="mean_loss",
    mode="min",
    name="skopt_exp",
    num_samples=num_samples,
    config=search_space
)<jupyter_output><empty_output><jupyter_text>We now have hyperparameters found to minimize the mean loss.<jupyter_code>print("Best hyperparameters found were: ", analysis.best_config)<jupyter_output><empty_output><jupyter_text>Providing an initial set of hyperparametersWhile defining the search algorithm, we may choose to provide an initial set of hyperparameters that we believe are especially promising or informative, andpass this information as a helpful starting point for the `SkOptSearch` object. We also can pass the known rewards for these initial params to save on unnecessary computation.<jupyter_code>initial_params = [
    {"width": 10, "height": 0, "activation": "relu"},
    {"width": 15, "height": -20, "activation": "tanh"}
]
known_rewards = [-189, -1144]<jupyter_output><empty_output><jupyter_text>Now the `search_alg` built using `SkOptSearch` takes `points_to_evaluate`.<jupyter_code>algo = SkOptSearch(points_to_evaluate=initial_params)
algo = ConcurrencyLimiter(algo, max_concurrent=4)<jupyter_output><empty_output><jupyter_text>And again run the experiment, this time with initial hyperparameter evaluations:<jupyter_code>analysis = tune.run(
    objective,
    search_alg=algo,
    metric="mean_loss",
    mode="min",
    name="skopt_exp_with_warmstart",
    num_samples=num_samples,
    config=search_space
)<jupyter_output><empty_output><jupyter_text>And we again show the ideal hyperparameters.<jupyter_code>print("Best hyperparameters found were: ", analysis.best_config)
ray.shutdown()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08604302151075538, 'fraction_numerical': 0.010672002668000667, 'mean_word_length': 5.918108419838523, 'pattern_counts': {'":': 10, '<': 53, '<?xml version=': 0, '>': 53, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '13', 'dir': 'jupyter-structured-clean-dedup', 'id': '61981', 'license': 'Apache-2.0', 'n_tokens_mistral': 1774, 'n_tokens_neox': 1690, 'n_words': 636, 'path': 'doc/source/tune/examples/skopt_example.ipynb', 'repo_name': 'myrill-labs/ray', 'size': '5997'}