liveBook · Manning

KerasTuner

As explained in Deep Learning with R, Third Edition

KerasTuner is a library for defining, running, and evaluating hyperparameter searches for Keras models.

KerasTuner automates hyperparameter optimization for Keras models by replacing fixed values such as units = 32 with searchable ranges. Those ranges form a search space, while a tuner evaluates candidate configurations against an objective. section 18.1.1

Listing 18.1 KerasTuner model-building function
build_model <- function(hp, num_classes = 10) {
  units  <- hp$Int(  #1
    name = "units",  #1
    min_value = 16L,  #1
    max_value = 64L,  #1
    step = 16L)  #1
  model  <- keras_model_sequential() |> #1
    layer_dense(units, activation = "relu") |>
    layer_dense(num_classes, activation = "softmax")

  optimizer <- hp$Choice(name = "optimizer", #2
                         values = c("rmsprop", "adam")) 
  model |> compile(optimizer = optimizer,
                   loss = "sparse_categorical_crossentropy",
                   metrics = "accuracy")
  model  #3
}

Build a compiled model from an hp argument, sampling integer units and optimizer choices before returning the model. section 18.1.1

A tuning workflow defines the builder, creates a tuner such as BayesianOptimization, selects an objective such as validation accuracy, and limits trials and repeated executions. Search then trains candidates with validation data and optional early stopping. section 18.1.1

MNIST multilayer perceptron search

Flatten MNIST images, scale pixels, reserve validation data, and search a dense classifier over units from 16 to 64 and either RMSprop or Adam. Query the best hyperparameter configurations or trained models, then retrain selected configurations and evaluate them on the test set. section 18.1.1

For a more modular design, subclass kt$HyperModel and implement build; R can express this Python-style subclass with %py_class%. section 18.1.1

How Deep Learning with R, Third Edition covers it

How deep it goes
Defines search spaces, model builders, tuners, objectives, trials, validation, early stopping, and final model selection.
Examples
Uses an MNIST dense classifier whose units and optimizer vary across trials, with validation accuracy guiding selection.
What it assumes
Assumes familiarity with compiled Keras models, fitting, validation data, callbacks, and basic R-to-Python interoperability.
What you can do after
Apply it via KerasTuner to define searches, run trials, retrieve top configurations, retrain models, and evaluate them on test data.
How it connects
Connects hyperparameter optimization, Keras models, Bayesian optimization, validation data, early stopping, and validation-set overfitting.

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 R, Third Edition. The section links point to the parts of the book it draws on.