RSVP for your your local TensorFlow Everywhere event today!

Introduction to the Keras Tuner

View on TensorFlow.org 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 kerastuner 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()
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-labels-idx1-ubyte.gz
32768/29515 [=================================] - 0s 0us/step
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-images-idx3-ubyte.gz
26427392/26421880 [==============================] - 0s 0us/step
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-labels-idx1-ubyte.gz
8192/5148 [===============================================] - 0s 0us/step
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-images-idx3-ubyte.gz
4423680/4422102 [==============================] - 0s 0us/step

# 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 28s]
val_accuracy: 0.8944166898727417

Best val_accuracy So Far: 0.8944166898727417
Total elapsed time: 00h 06m 04s
INFO:tensorflow:Oracle triggered exit

The hyperparameter search is complete. The optimal number of units in the first densely-connected
layer is 512 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 [==============================] - 3s 2ms/step - loss: 0.6147 - accuracy: 0.7839 - val_loss: 0.4014 - val_accuracy: 0.8539
Epoch 2/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.3753 - accuracy: 0.8655 - val_loss: 0.3886 - val_accuracy: 0.8607
Epoch 3/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.3298 - accuracy: 0.8782 - val_loss: 0.3729 - val_accuracy: 0.8648
Epoch 4/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.3069 - accuracy: 0.8860 - val_loss: 0.3373 - val_accuracy: 0.8801
Epoch 5/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.2812 - accuracy: 0.8933 - val_loss: 0.3202 - val_accuracy: 0.8818
Epoch 6/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.2664 - accuracy: 0.8997 - val_loss: 0.3141 - val_accuracy: 0.8860
Epoch 7/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.2533 - accuracy: 0.9065 - val_loss: 0.3128 - val_accuracy: 0.8892
Epoch 8/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.2371 - accuracy: 0.9128 - val_loss: 0.3160 - val_accuracy: 0.8869
Epoch 9/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.2314 - accuracy: 0.9126 - val_loss: 0.3332 - val_accuracy: 0.8851
Epoch 10/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.2191 - accuracy: 0.9193 - val_loss: 0.3214 - val_accuracy: 0.8888
Epoch 11/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.2098 - accuracy: 0.9196 - val_loss: 0.3183 - val_accuracy: 0.8910
Epoch 12/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.2031 - accuracy: 0.9228 - val_loss: 0.3313 - val_accuracy: 0.8890
Epoch 13/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.1941 - accuracy: 0.9270 - val_loss: 0.3168 - val_accuracy: 0.8978
Epoch 14/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.1863 - accuracy: 0.9287 - val_loss: 0.3478 - val_accuracy: 0.8848
Epoch 15/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.1802 - accuracy: 0.9330 - val_loss: 0.3293 - val_accuracy: 0.8917
Epoch 16/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.1731 - accuracy: 0.9347 - val_loss: 0.3107 - val_accuracy: 0.8964
Epoch 17/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.1677 - accuracy: 0.9380 - val_loss: 0.3352 - val_accuracy: 0.8948
Epoch 18/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.1641 - accuracy: 0.9391 - val_loss: 0.3322 - val_accuracy: 0.8956
Epoch 19/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.1557 - accuracy: 0.9412 - val_loss: 0.3569 - val_accuracy: 0.8872
Epoch 20/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.1563 - accuracy: 0.9416 - val_loss: 0.3801 - val_accuracy: 0.8880
Epoch 21/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.1521 - accuracy: 0.9416 - val_loss: 0.3584 - val_accuracy: 0.8926
Epoch 22/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.1456 - accuracy: 0.9456 - val_loss: 0.3616 - val_accuracy: 0.8913
Epoch 23/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.1372 - accuracy: 0.9503 - val_loss: 0.3891 - val_accuracy: 0.8910
Epoch 24/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.1355 - accuracy: 0.9502 - val_loss: 0.3693 - val_accuracy: 0.8928
Epoch 25/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.1313 - accuracy: 0.9505 - val_loss: 0.3668 - val_accuracy: 0.8902
Epoch 26/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.1304 - accuracy: 0.9509 - val_loss: 0.3967 - val_accuracy: 0.8947
Epoch 27/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.1230 - accuracy: 0.9526 - val_loss: 0.3865 - val_accuracy: 0.8936
Epoch 28/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.1193 - accuracy: 0.9553 - val_loss: 0.3736 - val_accuracy: 0.8949
Epoch 29/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.1181 - accuracy: 0.9545 - val_loss: 0.3967 - val_accuracy: 0.8893
Epoch 30/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.1102 - accuracy: 0.9597 - val_loss: 0.4002 - val_accuracy: 0.8932
Epoch 31/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.1067 - accuracy: 0.9591 - val_loss: 0.4335 - val_accuracy: 0.8901
Epoch 32/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.1090 - accuracy: 0.9573 - val_loss: 0.4269 - val_accuracy: 0.8873
Epoch 33/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.1030 - accuracy: 0.9614 - val_loss: 0.4296 - val_accuracy: 0.8967
Epoch 34/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.1009 - accuracy: 0.9628 - val_loss: 0.4441 - val_accuracy: 0.8929
Epoch 35/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.1014 - accuracy: 0.9613 - val_loss: 0.4328 - val_accuracy: 0.8938
Epoch 36/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.0919 - accuracy: 0.9663 - val_loss: 0.4594 - val_accuracy: 0.8921
Epoch 37/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.0943 - accuracy: 0.9622 - val_loss: 0.4475 - val_accuracy: 0.8932
Epoch 38/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.0934 - accuracy: 0.9644 - val_loss: 0.4752 - val_accuracy: 0.8881
Epoch 39/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.0916 - accuracy: 0.9654 - val_loss: 0.4608 - val_accuracy: 0.8952
Epoch 40/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.0895 - accuracy: 0.9660 - val_loss: 0.4657 - val_accuracy: 0.8931
Epoch 41/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.0847 - accuracy: 0.9682 - val_loss: 0.4825 - val_accuracy: 0.8963
Epoch 42/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.0863 - accuracy: 0.9674 - val_loss: 0.4713 - val_accuracy: 0.8969
Epoch 43/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.0752 - accuracy: 0.9719 - val_loss: 0.5424 - val_accuracy: 0.8921
Epoch 44/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.0835 - accuracy: 0.9681 - val_loss: 0.5176 - val_accuracy: 0.8925
Epoch 45/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.0820 - accuracy: 0.9689 - val_loss: 0.5032 - val_accuracy: 0.8967
Epoch 46/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.0744 - accuracy: 0.9711 - val_loss: 0.5074 - val_accuracy: 0.8966
Epoch 47/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.0749 - accuracy: 0.9716 - val_loss: 0.5197 - val_accuracy: 0.8945
Epoch 48/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.0716 - accuracy: 0.9721 - val_loss: 0.5163 - val_accuracy: 0.8939
Epoch 49/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.0760 - accuracy: 0.9726 - val_loss: 0.5215 - val_accuracy: 0.8957
Epoch 50/50
1500/1500 [==============================] - 3s 2ms/step - loss: 0.0728 - accuracy: 0.9728 - val_loss: 0.5511 - val_accuracy: 0.8934
Best epoch: 13

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_test, label_test, epochs=best_epoch)
Epoch 1/13
313/313 [==============================] - 1s 2ms/step - loss: 0.9074 - accuracy: 0.6859
Epoch 2/13
313/313 [==============================] - 1s 2ms/step - loss: 0.5113 - accuracy: 0.8173
Epoch 3/13
313/313 [==============================] - 1s 2ms/step - loss: 0.4458 - accuracy: 0.8333
Epoch 4/13
313/313 [==============================] - 1s 2ms/step - loss: 0.3891 - accuracy: 0.8620
Epoch 5/13
313/313 [==============================] - 1s 2ms/step - loss: 0.3666 - accuracy: 0.8620
Epoch 6/13
313/313 [==============================] - 1s 2ms/step - loss: 0.3559 - accuracy: 0.8717
Epoch 7/13
313/313 [==============================] - 1s 2ms/step - loss: 0.3366 - accuracy: 0.8733
Epoch 8/13
313/313 [==============================] - 1s 2ms/step - loss: 0.3138 - accuracy: 0.8820
Epoch 9/13
313/313 [==============================] - 1s 2ms/step - loss: 0.2926 - accuracy: 0.8904
Epoch 10/13
313/313 [==============================] - 1s 2ms/step - loss: 0.2771 - accuracy: 0.8947
Epoch 11/13
313/313 [==============================] - 1s 2ms/step - loss: 0.2601 - accuracy: 0.9022
Epoch 12/13
313/313 [==============================] - 1s 2ms/step - loss: 0.2391 - accuracy: 0.9140
Epoch 13/13
313/313 [==============================] - 1s 2ms/step - loss: 0.2434 - accuracy: 0.9069

<tensorflow.python.keras.callbacks.History at 0x7fcc08667be0>

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.2313 - accuracy: 0.9147
[test loss, test accuracy]: [0.23128622770309448, 0.9146999716758728]

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.