Hyperparameter Tuning with KerasTuner

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Learning rate, width, depth, dropout and batch size change the result of training enormously and cannot be learned by gradient descent. KerasTuner is the Keras team’s library for searching over them: you describe a search space inside a model-building function, pick a search algorithm, and the tuner trains many trials, records the validation objective of each and gives back the best configuration. This page covers the model-building function, the four built-in tuners, objectives, HyperModel subclasses, conditional hyperparameters, callbacks and the standard workflow of searching and then retraining. The Keras building blocks used here are on Sequential and Functional Models, Optimizers and Learning-Rate Schedules and compile, fit, evaluate and predict; early stopping is on Callbacks.

It targets Python 3.13 and TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is upcoming), and was checked against the official documentation on 2026-10-30. Examples were run on Python 3.13 with TensorFlow 2.21, Keras 3.15 and KerasTuner 1.4.8 (CPU) on 2026-10-31, with the epoch counts reduced to keep the run short. The method of tuning, rather than the library, is the subject of the Deep Learning Tuning Playbook; the general idea of validation and overfitting is on Generalization and Regularization, and the scikit-learn grid and random searches are in scikit-learn hyperparameter search. Keras models can also be tuned through scikit-learn’s own search classes by using the estimator adapters described on Keras Multi-Backend.

Installation and import

pip install keras-tuner --upgrade
import keras
import keras_tuner as kt      # the import name uses an underscore

The package name on PyPI is keras-tuner and the module is keras_tuner. Older tutorials import kerastuner, the pre-Keras-3, TensorFlow-only name; that spelling is outdated. KerasTuner works with Keras 3 and therefore with any Keras backend for the model itself, but a few options (notably the distribution_strategy argument) are specific to TensorFlow.

The workflow

flowchart TD S["define build_model(hp) with hp.Int, hp.Choice, ..."] --> T["create a tuner: objective, max_trials, directory"] T --> R["tuner.search(x, y, validation_data=..., callbacks=...)"] R --> TR{"more trials?"} TR -- yes --> NEXT["oracle proposes hyperparameters, builds and trains a model"] NEXT --> LOG["record objective value in directory/project_name"] LOG --> TR TR -- no --> BEST["get_best_hyperparameters"] BEST --> FIT["rebuild with best hp and retrain on train + validation"] FIT --> EVAL["evaluate once on the test set"]

Each trial is an independent training run. The oracle (the search algorithm) chooses the hyperparameter values of the next trial from the results of earlier ones; the tuner builds the model with build_model, trains it by calling fit with the arguments you passed to search, and stores the outcome on disk.

Defining a search space

The search space is declared inline, by asking the hp object for a value. The first time a name is requested its range is registered; during the search hp returns the value chosen for the current trial.

def build_model(hp):
    model = keras.Sequential()
    model.add(keras.Input(shape=(784,)))
    for i in range(hp.Int("num_layers", 1, 3)):
        model.add(keras.layers.Dense(
            units=hp.Int(f"units_{i}", min_value=32, max_value=256, step=32),
            activation=hp.Choice("activation", ["relu", "tanh"]),
        ))
        if hp.Boolean("dropout"):
            model.add(keras.layers.Dropout(hp.Float("dropout_rate", 0.1, 0.5, step=0.1)))
    model.add(keras.layers.Dense(10, activation="softmax"))

    lr = hp.Float("learning_rate", min_value=1e-4, max_value=1e-2, sampling="log")
    model.compile(
        optimizer=keras.optimizers.Adam(learning_rate=lr),
        loss="sparse_categorical_crossentropy",
        metrics=["accuracy"],
    )
    return model

The hyperparameter methods are:

Method Meaning

hp.Int(name, min_value, max_value, step=None, sampling="linear", default=None)

Integer in a range; max_value is inclusive. With sampling="log" the step is a multiplier.

hp.Float(name, min_value, max_value, step=None, sampling="linear", default=None)

Real number in a range. Use sampling="log" for learning rates and regularisation strengths, which span orders of magnitude, or "reverse_log" when values close to the upper bound matter.

hp.Choice(name, values, ordered=None, default=None)

One value from a list. ordered defaults to true for numbers and must be false for other types.

hp.Boolean(name, default=False)

True or false, for switches such as dropout or batch normalization.

hp.Fixed(name, value)

A constant recorded in the trial but not searched, which keeps settings visible in the results.

All of them also accept parent_name and parent_values to make the parameter conditional. Two details cause mistakes:

  • Names are global to the model. Reusing hp.Int("units", ...) in a loop returns the same value for every iteration; build per-layer names (f"units_{i}") as above.

  • A very wide space with few trials simply samples poorly. Prefer a small number of influential parameters (learning rate first, then width and regularisation) over every knob at once, as the tuning playbook recommends.

Conditional hyperparameters

Some parameters only exist for some choices: the number of convolution filters means nothing for an MLP. A conditional_scope marks a parameter as active only when a parent takes given values; outside that, the call returns None and the parameter is ignored by the oracle.

def build_conditional_model(hp):
    model = keras.Sequential([keras.Input(shape=(32, 32, 3))])
    model_type = hp.Choice("model_type", ["mlp", "cnn"])

    with hp.conditional_scope("model_type", ["mlp"]):
        if model_type == "mlp":
            model.add(keras.layers.Flatten())
            model.add(keras.layers.Dense(hp.Int("mlp_units", 32, 256, step=32), activation="relu"))

    with hp.conditional_scope("model_type", ["cnn"]):
        if model_type == "cnn":
            model.add(keras.layers.Conv2D(hp.Int("filters", 16, 64, step=16), 3, activation="relu"))
            model.add(keras.layers.GlobalAveragePooling2D())

    model.add(keras.layers.Dense(10, activation="softmax"))
    model.compile("adam", "sparse_categorical_crossentropy", metrics=["accuracy"])
    return model

Python code inside the scope always executes; only the registration of the hyperparameter is conditional, which is why the if model_type == ... guards are still needed to decide what to build.

The built-in tuners

All tuners share the base constructor arguments below and differ in how the oracle picks trials. Pass the model function (or a HyperModel) as the first argument.

Argument Meaning

objective

What to optimise: a metric name such as "val_accuracy" (direction inferred for known metrics) or kt.Objective("val_f1", direction="max") for custom metrics. It must be a metric reported by fit, so a validation objective needs validation data.

max_trials

Maximum number of hyperparameter combinations to try (random, Bayesian and grid search).

executions_per_trial

Models trained per trial; their results are averaged, which reduces noise at a proportional cost.

directory, project_name

Where results are stored: directory/project_name. Reusing the same pair resumes the previous search.

overwrite

When true, delete the previous results and start again; when false (default) an existing project is reloaded.

seed

Seed of the search algorithm (not of the model training).

max_consecutive_failed_trials

How many failed builds or trainings in a row are tolerated before the search aborts.

distribution_strategy

A tf.distribute strategy used when building and training each trial (TensorFlow backend).

Table 1. Tuner choice
Tuner How it searches Use it when

kt.RandomSearch

Samples configurations uniformly from the space.

A strong baseline, especially when only a few parameters matter; embarrassingly parallel.

kt.BayesianOptimization

Fits a Gaussian process to past trials and proposes promising points (arguments such as num_initial_points, alpha, beta).

Each trial is expensive and the space is mostly continuous and low-dimensional.

kt.Hyperband

Trains many configurations for a few epochs and repeatedly keeps the best fraction for more epochs (max_epochs, factor, hyperband_iterations).

You can afford many cheap partial trainings; typically the best choice for deep networks.

kt.GridSearch

Walks every combination of a discretised space.

Very small spaces; the cost multiplies with every added parameter.

tuner = kt.Hyperband(
    build_model,
    objective="val_accuracy",
    max_epochs=20,
    factor=3,
    hyperband_iterations=1,
    directory="tuning",
    project_name="mnist_mlp",
    overwrite=True,
)
tuner.search_space_summary()

search_space_summary() prints every registered hyperparameter with its range, a useful sanity check before spending hours of compute. Hyperband chooses the number of epochs itself, up to max_epochs, so do not pass an epochs argument to search that conflicts with it; with the other tuners you pass epochs normally. Hyperband also requires the objective to improve over training, which makes it a good match for val_loss or val_accuracy.

search forwards its arguments to model.fit, so everything accepted by fit (data, validation_data, batch_size, callbacks, class_weight, epochs for non-Hyperband tuners) works here.

import keras
import keras_tuner as kt

(x, y), _ = keras.datasets.mnist.load_data()
x = x.reshape(-1, 784).astype("float32") / 255.0
x_train, x_val = x[:50000], x[50000:]
y_train, y_val = y[:50000], y[50000:]

stop_early = keras.callbacks.EarlyStopping(monitor="val_loss", patience=3)

tuner = kt.RandomSearch(
    build_model,
    objective="val_accuracy",
    max_trials=20,
    executions_per_trial=1,
    directory="tuning",
    project_name="mnist_random",
    overwrite=True,
)
tuner.search(
    x_train, y_train,
    epochs=15,
    validation_data=(x_val, y_val),
    callbacks=[stop_early],
)

tuner.results_summary(num_trials=5)
best_hp = tuner.get_best_hyperparameters(num_trials=1)[0]
print(best_hp.values)   # varies per run, e.g. {'num_layers': 1, 'units_0': 256, 'activation': 'relu', ...}
best_model = tuner.get_best_models(num_models=1)[0]

Notes:

  • Always give the tuner validation data (or validation_split) that is separate from your test set. Selecting the best of many trials on the test set leaks it into the model choice; evaluate on the test set once, after tuning. See Generalization and Regularization.

  • get_best_hyperparameters returns a list of HyperParameters objects, best first; get_best_models returns trained models, which KerasTuner reloads from the checkpoint it keeps per trial; that checkpoint holds the weights of the trial’s best epoch for the objective, not of its last epoch. For production prefer to retrain, as described below.

  • With a seeded oracle and an unseeded model, results are still noisy. Set the Keras random seed (see Tensors, Dtypes and Random Numbers) if you need comparisons to be repeatable, and use executions_per_trial greater than one when differences between trials are smaller than the noise.

Retraining the best model

The model returned by the search was trained on the training split only, for as many epochs as that trial happened to run. The standard finish is to find the best number of epochs, then rebuild with the best hyperparameters and train on the combined training and validation data:

import numpy as np

best_hp = tuner.get_best_hyperparameters(1)[0]

# 1. Find the best epoch count on the validation split
model = tuner.hypermodel.build(best_hp)
history = model.fit(x_train, y_train, epochs=50, validation_data=(x_val, y_val), verbose=0)
val_acc = history.history["val_accuracy"]
best_epoch = int(np.argmax(val_acc)) + 1

# 2. Retrain from scratch on all labelled data for that many epochs
final = tuner.hypermodel.build(best_hp)
final.fit(np.concatenate([x_train, x_val]), np.concatenate([y_train, y_val]), epochs=best_epoch, verbose=0)
final.save("final.keras")

The attribute tuner.hypermodel.build(hp) rebuilds a fresh model from a HyperParameters object. Saving as .keras is covered by Saving Keras Models.

HyperModel subclasses: tuning more than the architecture

A function returning a compiled model can only tune what happens in build. Batch size, number of epochs, data augmentation strength or the training procedure live in fit, so KerasTuner lets you subclass kt.HyperModel: build(self, hp) returns the model, and an optional fit(self, hp, model, *args, **kwargs) runs the training and receives the same hp.

class MyHyperModel(kt.HyperModel):
    def build(self, hp):
        model = keras.Sequential([
            keras.Input(shape=(784,)),
            keras.layers.Dense(hp.Int("units", 32, 512, step=32), activation="relu"),
            keras.layers.Dense(10, activation="softmax"),
        ])
        model.compile(
            optimizer=keras.optimizers.Adam(hp.Float("lr", 1e-4, 1e-2, sampling="log")),
            loss="sparse_categorical_crossentropy",
            metrics=["accuracy"],
        )
        return model

    def fit(self, hp, model, *args, **kwargs):
        return model.fit(
            *args,
            batch_size=hp.Choice("batch_size", [32, 64, 128]),
            **kwargs,
        )

tuner = kt.BayesianOptimization(
    MyHyperModel(),
    objective="val_accuracy",
    max_trials=15,
    directory="tuning",
    project_name="hypermodel_demo",
    overwrite=True,
)
tuner.search(x_train, y_train, epochs=10, validation_data=(x_val, y_val))

fit must return what model.fit returns (the History object), because the tuner reads the objective from it. If you need a custom loop instead of fit, KerasTuner also supports a subclassed kt.Tuner that overrides run_trial and reports results to the oracle, which pairs naturally with a hand-written training loop. For the simpler train_step customisation see Customizing fit() with train_step.

Custom objectives and callbacks

Any metric reported in the fit logs can be the objective. For a metric not built in, give the direction explicitly:

objective = kt.Objective("val_auc", direction="max")
# model.compile(..., metrics=[keras.metrics.AUC(name="auc")]) makes val_auc available
tuner = kt.RandomSearch(build_model, objective=objective, max_trials=10, directory="tuning", project_name="auc")

Several objectives can be combined with a list of kt.Objective objects. Useful callbacks to pass to search:

  • keras.callbacks.EarlyStopping to cut bad trials short; this makes each trial cheaper without changing which trial wins, as long as patience is not too small.

  • keras.callbacks.TensorBoard with a per-trial log directory to inspect curves; the tuner also provides an HParams view, see TensorBoard.

  • keras.callbacks.ModelCheckpoint if you want the best epoch of each trial rather than the last.

Scaling up and running in parallel

KerasTuner stores each trial under directory/project_name, so a search can be stopped and resumed by re-running with overwrite=False. For parallel searches, the documentation describes running several processes (workers) that share one chief oracle, configured through the environment variables KERASTUNER_TUNER_ID (chief for the oracle process, a unique name such as tuner0 for each worker), KERASTUNER_ORACLE_IP and KERASTUNER_ORACLE_PORT, set before launching each process. Parallel searches need several processes or machines and were not executed for this page. Each trial itself can use several GPUs by passing distribution_strategy, which follows the rules of Distributed Training. For larger-scale or non-Keras searches the general-purpose tools discussed in Experiment Tracking and MLOps and Optuna (see the scikit-learn page on tuning at scale) are alternatives.

Common mistakes

  • Importing kerastuner or calling a TF1-era API; use import keras_tuner.

  • Searching without validation data while the objective is val_*; the tuner cannot find the metric and fails.

  • Reusing hyperparameter names inside a loop, so every layer gets the same width.

  • Leaving overwrite=False after changing the model function: the tuner reloads old trials that were run with a different search space. Change project_name or set overwrite=True when the space changes.

  • Treating the returned best model as final: retrain on all data for the chosen epoch count, then test once.

  • Tuning on a tiny subset and expecting the optimum to transfer; learning-rate optima in particular shift with data size and batch size.

References