Using Optuna to Optimize TensorFlow Hyperparameters

Crissman Loomis
Optuna
4 min readApr 13, 2020

--

This post uses tensorflow v2.1 and optuna v1.1.0.

TensorFlow + Optuna!

Optuna is a hyperparameter optimization framework applicable to machine learning frameworks and black-box optimization solvers. TensorFlow is Google’s open source platform for machine learning, with a deep ecosystem of tools, libraries and community resources. Let’s see how they can work together!

Creating the Objective Function

Optuna is a black-box optimizer, which means it needs an objectivefunction, which returns a numerical value to evaluate the performance of the hyperparameters, and decide where to sample in upcoming trials.

In our example, we will be doing this for identifying MNIST characters from the Optuna GitHub pruning examples folder. In this case, the objective function looks like this:

Notice that the objective function is passed an Optuna specific argument of trial. This object is passed to the objective function to be used to specify which hyperparameters should be tuned. This returns the accuracy of the model as float(eval_results[“accuracy”]), which is used by Optuna as feedback on the performance of the trial.

Defining the hyperparameters to be tuned

Similar to how Tensorflow Eager execution, Optuna allows you to define the kinds and ranges of hyperparameters you want to tune directly within your code using the trial object. This saves the effort of learning specialized syntax for hyperparameters, and also means you can use normal Python code to loop through or define your hyperparameters.

Optuna supports a variety of hyperparameter settings, which can be used to optimize floats, integers, or discrete categorical values. Numerical values can be suggested from a logarithmic continuum as well. In our MNIST example, we optimize the hyperparameters here:

The number of layers to be tuned is given from trial.suggest_int(“n_layers”, 1, 3), which gives an integer value from 1 to 3, which will be labelled in Optuna as n_layers.

Hyperparameters that use float values can be defined by trial.suggest_uniform(“dropout_rate”, 0, 1), which would give a float value between 0 and 1.

For hyperparameters which should vary by orders of magnitude, such as learning rates, use something like trial.suggest_loguniform('learning_rate', 1e-5, 1000), which will vary the values from .00001 to 0.1.

Categorical selection from a list is possible with trial.suggest_categorical(‘optimizer’, [‘SGD’, ‘Adam’]).

Running the Trials

The default sampler in Optuna Tree-structured Parzen Estimater (TPE), which is a form of Bayesian Optimization. Optuna uses TPE to search more efficiently than a random search, by choosing points closer to previous good results.

To run the trials, create a study object, which sets the direction of optimization (maximize or minimize), along with other settings. Then, the study object run with study.optimize(objective, n_trials=25), to do one hundred trials, with a timeout of ten minutes.

Each trial is chosen after evaluating all the trials that have been previously done, using a sampler to make a smart guess where the best values hyperparameters can be found. Optuna provides Tree-structured Parzen Estimator (TPE) samplers, which is a kind of bayesian optimization, as the default sampler.

The best values from the trials can be accessed through study.best_trial, and other methods of viewing the trials, such as formatting in a dataframe, are available.

Pruning — Early Stopping of Poor Trials

Pruning trials is a form of early-stopping which terminates unpromising trials, so that computing time can be used for trials that show more potential. In order to do pruning, it’s necessary to open up the black-box of the Objective function some more to provide intermittent feedback on how the trial is going to Optuna, so it can compare the progress with the progress of other trials, and decide whether to stop the trial early, and provide a method to receive a method from Optuna when the trial should be terminated, and also allow the trial in session to terminate cleanly after recording the results. Fortunately, Optuna provides an integration for TensorFlow (TensorFlowPruningHook) pruning that provides all of these functions.

After defining the optuna_pruning_hook, it is passed as a hook to the estimator to allow TensorFlow to do the pruning. The metric argument of the TensorFlowPruningHook function references the TensorFlow early_stopping evalmetrics, such as accuracy or loss.

To the Future, and Beyond!

Plot Contour Visualization

For those interested, Optuna has many other features, including a visualizations, alternative samplers, optimizers, and pruning algorithms, as well as the ability to create user-defined versions as well. If you have more computing resources available, Optuna provides an easy interface for parallel trials to increase tuning speed.

Give Optuna a try!

Installation

Optuna Github

--

--