liveBook · Manning

KerasTuner

As explained in Deep Learning with Python, Third Edition

A Keras-related library for automating hyperparameter search over model configurations.

KerasTuner automates the repetitive search for a high-performing Keras model configuration. Because hyperparameter choices are generally nondifferentiable, each candidate requires a separate training run, and small metric differences can be noisy. section 18.1.1

A small MNIST search

Replace fixed values such as units=32 with searchable choices such as hp.Int("units", 16, 64, step=16), and let hp.Choice select an optimizer. A model-building function receives hp, constructs and compiles the model, and returns it. A BayesianOptimization tuner can then search for the configuration that maximizes val_accuracy. section 18.1.1

Listing 18.1 A KerasTuner model-building function
import keras
from keras import layers

def build_model(hp):
    units = hp.Int(name="units", min_value=16, max_value=64, step=16) #1
    model = keras.Sequential(
        [
            layers.Dense(units, activation="relu"),
            layers.Dense(10, activation="softmax"),
        ]
    )
    optimizer = hp.Choice(name="optimizer", values=["rmsprop", "adam"])#2
    model.compile(
        optimizer=optimizer,
        loss="sparse_categorical_crossentropy",
        metrics=["accuracy"],
    )
    return model                                                       #3

Inspect the concrete model-building function that declares integer and categorical hyperparameters before compiling the Keras model. section 18.1.1

A practical KerasTuner workflow is:

  • Define the search space with hp.Int, hp.Choice, or similar hyperparameter ranges. section 18.1.1
  • Pass the model builder to a tuner such as RandomSearch, BayesianOptimization, or Hyperband. section 18.1.1
  • Set an objective, limit trials, and optionally repeat executions per trial to account for noisy training results. section 18.1.1
  • Call tuner.search with training and validation data, then retrieve the best hyperparameters or trained models. section 18.1.1
tuner = kt.BayesianOptimization(
    build_model,                                                       #1
    objective="val_accuracy",                                         #2
    max_trials=20,                                                     #3
    executions_per_trial=2,                                           #4
    directory="mnist_kt_test",                                        #5
    overwrite=True,                                                    #6
)

Inspect a complete BayesianOptimization configuration, including the validation objective, trial budget, repeated executions, and output directory. section 18.1.1

Treat the validation score as a tuning signal rather than a final guarantee: repeated optimization against one validation set can overfit that set. Retrain promising configurations with a suitable epoch count and evaluate on held-out test data. section 18.4 section 18.1.1

How Deep Learning with Python, Third Edition covers it

How deep it goes
Explains search spaces, model builders, tuners, objectives, trials, and result retrieval, but does not derive optimization theory.
Examples
Uses an MNIST multilayer perceptron that searches dense-layer units, optimizer choice, validation accuracy, training epochs, and final test performance.
What it assumes
Assumes familiarity with compiling and training Keras models, while teaching hyperparameter search-space declaration from the model-building stage.
What you can do after
Apply it via KerasTuner to define a search space, run trials, and select or retrain promising Keras models.
How it connects
Connects hyperparameter optimization with model building, Bayesian optimization, random search, Hyperband, validation, and ensemble learning.

Also explained in

Compare how 3 books explain KerasTuner →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Deep Learning with Python, Third Edition. The section links point to the parts of the book it draws on.