Attend the Women in ML Symposium on December 7 Register now

Introduction to the Keras Tuner

Stay organized with collections Save and categorize content based on your preferences.

View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook

Overview

The Keras Tuner is a library that helps you pick the optimal set of hyperparameters for your TensorFlow program. The process of selecting the right set of hyperparameters for your machine learning (ML) application is called hyperparameter tuning or hypertuning.

Hyperparameters are the variables that govern the training process and the topology of an ML model. These variables remain constant over the training process and directly impact the performance of your ML program. Hyperparameters are of two types:

  1. Model hyperparameters which influence model selection such as the number and width of hidden layers
  2. Algorithm hyperparameters which influence the speed and quality of the learning algorithm such as the learning rate for Stochastic Gradient Descent (SGD) and the number of nearest neighbors for a k Nearest Neighbors (KNN) classifier

In this tutorial, you will use the Keras Tuner to perform hypertuning for an image classification application.

Setup

import tensorflow as tf
from tensorflow import keras

Install and import the Keras Tuner.

pip install -q -U keras-tuner
import keras_tuner as kt

Download and prepare the dataset

In this tutorial, you will use the Keras Tuner to find the best hyperparameters for a machine learning model that classifies images of clothing from the Fashion MNIST dataset.

Load the data.

(img_train, label_train), (img_test, label_test) = keras.datasets.fashion_mnist.load_data()
# Normalize pixel values between 0 and 1
img_train = img_train.astype('float32') / 255.0
img_test = img_test.astype('float32') / 255.0

Define the model

When you build a model for hypertuning, you also define the hyperparameter search space in addition to the model architecture. The model you set up for hypertuning is called a hypermodel.

You can define a hypermodel through two approaches:

  • By using a model builder function
  • By subclassing the HyperModel class of the Keras Tuner API

You can also use two pre-defined HyperModel classes - HyperXception and HyperResNet for computer vision applications.

In this tutorial, you use a model builder function to define the image classification model. The model builder function returns a compiled model and uses hyperparameters you define inline to hypertune the model.

def model_builder(hp):
  model = keras.Sequential()
  model.add(keras.layers.Flatten(input_shape=(28, 28)))

  # Tune the number of units in the first Dense layer
  # Choose an optimal value between 32-512
  hp_units = hp.Int('units', min_value=32, max_value=512, step=32)
  model.add(keras.layers.Dense(units=hp_units, activation='relu'))
  model.add(keras.layers.Dense(10))

  # Tune the learning rate for the optimizer
  # Choose an optimal value from 0.01, 0.001, or 0.0001
  hp_learning_rate = hp.Choice('learning_rate', values=[1e-2, 1e-3, 1e-4])

  model.compile(optimizer=keras.optimizers.Adam(learning_rate=hp_learning_rate),
                loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
                metrics=['accuracy'])

  return model

Instantiate the tuner and perform hypertuning

Instantiate the tuner to perform the hypertuning. The Keras Tuner has four tuners available - RandomSearch, Hyperband, BayesianOptimization, and Sklearn. In this tutorial, you use the Hyperband tuner.

To instantiate the Hyperband tuner, you must specify the hypermodel, the objective to optimize and the maximum number of epochs to train (max_epochs).

tuner = kt.Hyperband(model_builder,
                     objective='val_accuracy',
                     max_epochs=10,
                     factor=3,
                     directory='my_dir',
                     project_name='intro_to_kt')

The Hyperband tuning algorithm uses adaptive resource allocation and early-stopping to quickly converge on a high-performing model. This is done using a sports championship style bracket. The algorithm trains a large number of models for a few epochs and carries forward only the top-performing half of models to the next round. Hyperband determines the number of models to train in a bracket by computing 1 + logfactor(max_epochs) and rounding it up to the nearest integer.

Create a callback to stop training early after reaching a certain value for the validation loss.

stop_early = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5)

Run the hyperparameter search. The arguments for the search method are the same as those used for tf.keras.model.fit in addition to the callback above.

tuner.search(img_train, label_train, epochs=50, validation_split=0.2, callbacks=[stop_early])

# Get the optimal hyperparameters
best_hps=tuner.get_best_hyperparameters(num_trials=1)[0]

print(f"""
The hyperparameter search is complete. The optimal number of units in the first densely-connected
layer is {best_hps.get('units')} and the optimal learning rate for the optimizer
is {best_hps.get('learning_rate')}.
""")
Trial 30 Complete [00h 00m 41s]
val_accuracy: 0.8865000009536743

Best val_accuracy So Far: 0.8865000009536743
Total elapsed time: 00h 08m 39s
INFO:tensorflow:Oracle triggered exit

The hyperparameter search is complete. The optimal number of units in the first densely-connected
layer is 416 and the optimal learning rate for the optimizer
is 0.001.

Train the model

Find the optimal number of epochs to train the model with the hyperparameters obtained from the search.

# Build the model with the optimal hyperparameters and train it on the data for 50 epochs
model = tuner.hypermodel.build(best_hps)
history = model.fit(img_train, label_train, epochs=50, validation_split=0.2)

val_acc_per_epoch = history.history['val_accuracy']
best_epoch = val_acc_per_epoch.index(max(val_acc_per_epoch)) + 1
print('Best epoch: %d' % (best_epoch,))
Epoch 1/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.4962 - accuracy: 0.8246 - val_loss: 0.4271 - val_accuracy: 0.8409
Epoch 2/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.3665 - accuracy: 0.8673 - val_loss: 0.3703 - val_accuracy: 0.8627
Epoch 3/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.3290 - accuracy: 0.8791 - val_loss: 0.3278 - val_accuracy: 0.8832
Epoch 4/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.3040 - accuracy: 0.8875 - val_loss: 0.3544 - val_accuracy: 0.8710
Epoch 5/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.2843 - accuracy: 0.8938 - val_loss: 0.3508 - val_accuracy: 0.8742
Epoch 6/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.2724 - accuracy: 0.8986 - val_loss: 0.3314 - val_accuracy: 0.8813
Epoch 7/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.2575 - accuracy: 0.9042 - val_loss: 0.3174 - val_accuracy: 0.8871
Epoch 8/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.2466 - accuracy: 0.9075 - val_loss: 0.3292 - val_accuracy: 0.8833
Epoch 9/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.2345 - accuracy: 0.9124 - val_loss: 0.3428 - val_accuracy: 0.8864
Epoch 10/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.2241 - accuracy: 0.9159 - val_loss: 0.3126 - val_accuracy: 0.8918
Epoch 11/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.2149 - accuracy: 0.9186 - val_loss: 0.3332 - val_accuracy: 0.8851
Epoch 12/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.2107 - accuracy: 0.9199 - val_loss: 0.3087 - val_accuracy: 0.8939
Epoch 13/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.2003 - accuracy: 0.9245 - val_loss: 0.3184 - val_accuracy: 0.8931
Epoch 14/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1934 - accuracy: 0.9272 - val_loss: 0.3197 - val_accuracy: 0.8946
Epoch 15/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1886 - accuracy: 0.9294 - val_loss: 0.3224 - val_accuracy: 0.8912
Epoch 16/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1784 - accuracy: 0.9339 - val_loss: 0.3417 - val_accuracy: 0.8921
Epoch 17/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1754 - accuracy: 0.9343 - val_loss: 0.3287 - val_accuracy: 0.8947
Epoch 18/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1683 - accuracy: 0.9363 - val_loss: 0.3427 - val_accuracy: 0.8926
Epoch 19/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1622 - accuracy: 0.9394 - val_loss: 0.3369 - val_accuracy: 0.8943
Epoch 20/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1570 - accuracy: 0.9410 - val_loss: 0.3449 - val_accuracy: 0.8907
Epoch 21/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1550 - accuracy: 0.9414 - val_loss: 0.3443 - val_accuracy: 0.8929
Epoch 22/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1501 - accuracy: 0.9442 - val_loss: 0.3449 - val_accuracy: 0.8979
Epoch 23/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1440 - accuracy: 0.9457 - val_loss: 0.3613 - val_accuracy: 0.8939
Epoch 24/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1382 - accuracy: 0.9484 - val_loss: 0.3676 - val_accuracy: 0.8894
Epoch 25/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1369 - accuracy: 0.9477 - val_loss: 0.3940 - val_accuracy: 0.8871
Epoch 26/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1305 - accuracy: 0.9512 - val_loss: 0.3630 - val_accuracy: 0.8935
Epoch 27/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1251 - accuracy: 0.9520 - val_loss: 0.4069 - val_accuracy: 0.8840
Epoch 28/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1263 - accuracy: 0.9520 - val_loss: 0.3820 - val_accuracy: 0.8928
Epoch 29/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1214 - accuracy: 0.9542 - val_loss: 0.3970 - val_accuracy: 0.8955
Epoch 30/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1174 - accuracy: 0.9554 - val_loss: 0.3996 - val_accuracy: 0.8895
Epoch 31/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1143 - accuracy: 0.9567 - val_loss: 0.4196 - val_accuracy: 0.8923
Epoch 32/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1132 - accuracy: 0.9574 - val_loss: 0.4209 - val_accuracy: 0.8902
Epoch 33/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1089 - accuracy: 0.9592 - val_loss: 0.4093 - val_accuracy: 0.8951
Epoch 34/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1085 - accuracy: 0.9597 - val_loss: 0.4049 - val_accuracy: 0.8988
Epoch 35/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1016 - accuracy: 0.9611 - val_loss: 0.4444 - val_accuracy: 0.8907
Epoch 36/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1035 - accuracy: 0.9613 - val_loss: 0.4821 - val_accuracy: 0.8899
Epoch 37/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1009 - accuracy: 0.9618 - val_loss: 0.4409 - val_accuracy: 0.8896
Epoch 38/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.0952 - accuracy: 0.9623 - val_loss: 0.4678 - val_accuracy: 0.8915
Epoch 39/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.0928 - accuracy: 0.9653 - val_loss: 0.4495 - val_accuracy: 0.8939
Epoch 40/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.0967 - accuracy: 0.9645 - val_loss: 0.4850 - val_accuracy: 0.8902
Epoch 41/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.0927 - accuracy: 0.9642 - val_loss: 0.4785 - val_accuracy: 0.8904
Epoch 42/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.0874 - accuracy: 0.9678 - val_loss: 0.4565 - val_accuracy: 0.8949
Epoch 43/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.0825 - accuracy: 0.9689 - val_loss: 0.5582 - val_accuracy: 0.8848
Epoch 44/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.0841 - accuracy: 0.9686 - val_loss: 0.5025 - val_accuracy: 0.8915
Epoch 45/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.0826 - accuracy: 0.9695 - val_loss: 0.5150 - val_accuracy: 0.8856
Epoch 46/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.0817 - accuracy: 0.9695 - val_loss: 0.5074 - val_accuracy: 0.8943
Epoch 47/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.0789 - accuracy: 0.9699 - val_loss: 0.5018 - val_accuracy: 0.8947
Epoch 48/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.0796 - accuracy: 0.9701 - val_loss: 0.5014 - val_accuracy: 0.8921
Epoch 49/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.0774 - accuracy: 0.9711 - val_loss: 0.4936 - val_accuracy: 0.8959
Epoch 50/50
1500/1500 [==============================] - 4s 3ms/step - loss: 0.0787 - accuracy: 0.9709 - val_loss: 0.5335 - val_accuracy: 0.8897
Best epoch: 34

Re-instantiate the hypermodel and train it with the optimal number of epochs from above.

hypermodel = tuner.hypermodel.build(best_hps)

# Retrain the model
hypermodel.fit(img_train, label_train, epochs=best_epoch, validation_split=0.2)
Epoch 1/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.4928 - accuracy: 0.8247 - val_loss: 0.4264 - val_accuracy: 0.8497
Epoch 2/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.3677 - accuracy: 0.8659 - val_loss: 0.3683 - val_accuracy: 0.8650
Epoch 3/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.3316 - accuracy: 0.8780 - val_loss: 0.3367 - val_accuracy: 0.8779
Epoch 4/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.3047 - accuracy: 0.8866 - val_loss: 0.3295 - val_accuracy: 0.8798
Epoch 5/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.2851 - accuracy: 0.8942 - val_loss: 0.3325 - val_accuracy: 0.8794
Epoch 6/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.2727 - accuracy: 0.8974 - val_loss: 0.3389 - val_accuracy: 0.8819
Epoch 7/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.2550 - accuracy: 0.9046 - val_loss: 0.3226 - val_accuracy: 0.8867
Epoch 8/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.2465 - accuracy: 0.9066 - val_loss: 0.3186 - val_accuracy: 0.8871
Epoch 9/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.2354 - accuracy: 0.9121 - val_loss: 0.3306 - val_accuracy: 0.8883
Epoch 10/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.2258 - accuracy: 0.9158 - val_loss: 0.3254 - val_accuracy: 0.8870
Epoch 11/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.2172 - accuracy: 0.9176 - val_loss: 0.3299 - val_accuracy: 0.8857
Epoch 12/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.2081 - accuracy: 0.9209 - val_loss: 0.3135 - val_accuracy: 0.8916
Epoch 13/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.2014 - accuracy: 0.9248 - val_loss: 0.3375 - val_accuracy: 0.8892
Epoch 14/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1930 - accuracy: 0.9275 - val_loss: 0.3354 - val_accuracy: 0.8912
Epoch 15/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1878 - accuracy: 0.9293 - val_loss: 0.3193 - val_accuracy: 0.8948
Epoch 16/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1808 - accuracy: 0.9321 - val_loss: 0.3391 - val_accuracy: 0.8901
Epoch 17/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1756 - accuracy: 0.9339 - val_loss: 0.3466 - val_accuracy: 0.8877
Epoch 18/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1709 - accuracy: 0.9349 - val_loss: 0.3345 - val_accuracy: 0.8910
Epoch 19/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1624 - accuracy: 0.9389 - val_loss: 0.3441 - val_accuracy: 0.8938
Epoch 20/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1564 - accuracy: 0.9415 - val_loss: 0.3611 - val_accuracy: 0.8885
Epoch 21/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1536 - accuracy: 0.9424 - val_loss: 0.3552 - val_accuracy: 0.8934
Epoch 22/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1470 - accuracy: 0.9455 - val_loss: 0.3595 - val_accuracy: 0.8952
Epoch 23/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1436 - accuracy: 0.9459 - val_loss: 0.3675 - val_accuracy: 0.8936
Epoch 24/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1402 - accuracy: 0.9468 - val_loss: 0.3706 - val_accuracy: 0.8922
Epoch 25/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1371 - accuracy: 0.9492 - val_loss: 0.3785 - val_accuracy: 0.8933
Epoch 26/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1297 - accuracy: 0.9509 - val_loss: 0.3624 - val_accuracy: 0.8942
Epoch 27/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1315 - accuracy: 0.9507 - val_loss: 0.3854 - val_accuracy: 0.8953
Epoch 28/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1247 - accuracy: 0.9523 - val_loss: 0.3988 - val_accuracy: 0.8900
Epoch 29/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1216 - accuracy: 0.9532 - val_loss: 0.4011 - val_accuracy: 0.8886
Epoch 30/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1189 - accuracy: 0.9554 - val_loss: 0.3949 - val_accuracy: 0.8907
Epoch 31/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1153 - accuracy: 0.9568 - val_loss: 0.3940 - val_accuracy: 0.8963
Epoch 32/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1112 - accuracy: 0.9575 - val_loss: 0.3962 - val_accuracy: 0.8947
Epoch 33/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1102 - accuracy: 0.9586 - val_loss: 0.4067 - val_accuracy: 0.8956
Epoch 34/34
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1050 - accuracy: 0.9605 - val_loss: 0.4112 - val_accuracy: 0.8926
<keras.callbacks.History at 0x7fc6b60ce2d0>

To finish this tutorial, evaluate the hypermodel on the test data.

eval_result = hypermodel.evaluate(img_test, label_test)
print("[test loss, test accuracy]:", eval_result)
313/313 [==============================] - 1s 2ms/step - loss: 0.4548 - accuracy: 0.8854
[test loss, test accuracy]: [0.4547567367553711, 0.8853999972343445]

The my_dir/intro_to_kt directory contains detailed logs and checkpoints for every trial (model configuration) run during the hyperparameter search. If you re-run the hyperparameter search, the Keras Tuner uses the existing state from these logs to resume the search. To disable this behavior, pass an additional overwrite=True argument while instantiating the tuner.

Summary

In this tutorial, you learned how to use the Keras Tuner to tune hyperparameters for a model. To learn more about the Keras Tuner, check out these additional resources:

Also check out the HParams Dashboard in TensorBoard to interactively tune your model hyperparameters.