liveBook · Manning

Hyperparameter tuning

As explained in Deep Learning with R, Third Edition

Hyperparameter tuning is the process of selecting model configuration values by evaluating alternative settings during development.

Hyperparameter tuning selects model configuration values by training and evaluating alternative settings. Unlike model parameters learned through backpropagation, hyperparameters include choices such as layer width, dropout rate, and optimizer. Initial choices are rarely optimal, so tuning provides a systematic way to improve them. section 18.1.1

For example, an MNIST classifier can search over hidden-layer widths and optimizers. The following R workflow uses KerasTuner with Keras and a JAX backend. section 18.1.1

library(keras3)
library(reticulate)
use_backend("jax")
py_require(c("keras-tuner", "scikit-learn"))

Load Keras and reticulate, select the backend, and request the required Python packages. 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
}

Define a model-building function. It lets the tuner choose 16, 32, 48, or 64 hidden units and either RMSprop or Adam. section 18.1.1

Import the tuner with `kt <- import("keras_tuner")`, then create a Bayesian optimization tuner. It seeks higher validation accuracy, allows up to 20 trials, and runs each trial twice. section 18.1.1

tuner <- kt$BayesianOptimization(
  build_model,  #1
  objective = "val_accuracy",  #2
  max_trials = 20L,  #3
  executions_per_trial = 2L, #4
  directory = "mnist_kt_test", #5
  overwrite = TRUE  #6
)

Configure the search objective, trial limit, repeated executions, and output directory. section 18.1.1

.[.[x_train_full, y_train_full], .[x_test, y_test]] <- dataset_mnist()  #1
x_train_full <- x_train_full |> array_reshape(c(-1, 28 * 28))  #1
x_train_full <- x_train_full / 255   #1
x_test <- x_test |> array_reshape(c(-1, 28 * 28))   #1
x_test <- x_test / 255   #1

num_val_samples <- 10000  #2
val_i <- seq_len(num_val_samples) #2
x_val <- x_train_full[val_i, ]  #2
x_train <- x_train_full[-val_i, ]  #2
y_val <- y_train_full[val_i] |> as.matrix()  #2
y_train <- y_train_full[-val_i] |> as.matrix()  #2

callbacks <- list(  #3
  callback_early_stopping(monitor = "val_loss", patience = 5)  #3
)

tuner$search(  #4
  x_train, y_train,
  batch_size = 128L,
  epochs = 100L,
  validation_data = list(x_val, y_val),
  callbacks = callbacks,
  verbose = 2L
)

Prepare MNIST, reserve 10,000 examples for validation, and run the search with early stopping on validation loss. section 18.1.1

Listing 18.3 Querying the best hyperparameter configurations
top_n <- 4L
best_hps <- tuner$get_best_hyperparameters(top_n)  #1

Retrieve the four highest-ranked hyperparameter configurations after the search. section 18.1.1

Each trial builds and trains a model with a candidate configuration, then measures validation performance. The search algorithm uses those results to choose further settings. Tuning can also be done manually: change a setting, retrain, evaluate on validation data, and repeat. section 18.1.1 section 6.2.5

Keep the test set out of the tuning loop. Repeatedly using validation feedback can itself lead to validation-set overfitting, making performance estimates less reliable. Once a configuration is satisfactory, train the final model on training and validation data and evaluate it on the test set. If test performance is much worse than validation performance, consider a more reliable protocol such as iterated K-fold validation. section 6.2.5

How Deep Learning with R, Third Edition covers it

How deep it goes
Explains iterative search and demonstrates Bayesian optimization with a model builder, validation split, early stopping, and ranked results.
Examples
Uses an MNIST classifier to compare hidden-layer widths and optimizers.
What you can do after
Apply it via KerasTuner to search candidate configurations and retrieve the best hyperparameters.
How it connects
Connects hyperparameter optimization with validation-set overfitting, regularization, Bayesian optimization, and model ensembling.

Also explained in

Compare how 19 books explain hyperparameter tuning →

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.