Path: blob/master/guides/ipynb/keras_tuner/custom_tuner.ipynb
3283 views
Tune hyperparameters in your custom training loop
Authors: Tom O'Malley, Haifeng Jin
Date created: 2019/10/28
Last modified: 2022/01/12
Description: Use HyperModel.fit()
to tune training hyperparameters (such as batch size).
Introduction
The HyperModel
class in KerasTuner provides a convenient way to define your search space in a reusable object. You can override HyperModel.build()
to define and hypertune the model itself. To hypertune the training process (e.g. by selecting the proper batch size, number of training epochs, or data augmentation setup), you can override HyperModel.fit()
, where you can access:
The
hp
object, which is an instance ofkeras_tuner.HyperParameters
The model built by
HyperModel.build()
A basic example is shown in the "tune model training" section of Getting Started with KerasTuner.
Tuning the custom training loop
In this guide, we will subclass the HyperModel
class and write a custom training loop by overriding HyperModel.fit()
. For how to write a custom training loop with Keras, you can refer to the guide Writing a training loop from scratch.
First, we import the libraries we need, and we create datasets for training and validation. Here, we just use some random data for demonstration purposes.
Then, we subclass the HyperModel
class as MyHyperModel
. In MyHyperModel.build()
, we build a simple Keras model to do image classification for 10 different classes. MyHyperModel.fit()
accepts several arguments. Its signature is shown below:
The
hp
argument is for defining the hyperparameters.The
model
argument is the model returned byMyHyperModel.build()
.x
,y
, andvalidation_data
are all custom-defined arguments. We will pass our data to them by callingtuner.search(x=x, y=y, validation_data=(x_val, y_val))
later. You can define any number of them and give custom names.The
callbacks
argument was intended to be used withmodel.fit()
. KerasTuner put some helpful Keras callbacks in it, for example, the callback for checkpointing the model at its best epoch.
We will manually call the callbacks in the custom training loop. Before we can call them, we need to assign our model to them with the following code so that they have access to the model for checkpointing.
In this example, we only called the on_epoch_end()
method of the callbacks to help us checkpoint the model. You may also call other callback methods if needed. If you don't need to save the model, you don't need to use the callbacks.
In the custom training loop, we tune the batch size of the dataset as we wrap the NumPy data into a tf.data.Dataset
. Note that you can tune any preprocessing steps here as well. We also tune the learning rate of the optimizer.
We will use the validation loss as the evaluation metric for the model. To compute the mean validation loss, we will use keras.metrics.Mean()
, which averages the validation loss across the batches. We need to return the validation loss for the tuner to make a record.
Now, we can initialize the tuner. Here, we use Objective("my_metric", "min")
as our metric to be minimized. The objective name should be consistent with the one you use as the key in the logs
passed to the 'on_epoch_end()' method of the callbacks. The callbacks need to use this value in the logs
to find the best epoch to checkpoint the model.
We start the search by passing the arguments we defined in the signature of MyHyperModel.fit()
to tuner.search()
.
Finally, we can retrieve the results.
In summary, to tune the hyperparameters in your custom training loop, you just override HyperModel.fit()
to train the model and return the evaluation results. With the provided callbacks, you can easily save the trained models at their best epochs and load the best models later.
To find out more about the basics of KerasTuner, please see Getting Started with KerasTuner.