Hyperparameter Tuning with Keras Tuner _ Day 17

Best-epoch validation losses for three synthetic KerasTuner trials; the minimum is the selected trial.
Actual small synthetic workflow check, not MNIST accuracy or a general benchmark.

Define · search · validate

Hyperparameter tuning
with KerasTuner

Build a clear search space, protect the final test set, and understand what the tuner’s best result really means.

Complete original retained · Expanded 17 November 2026
Executed synthetic trials; historical MNIST training not reproduced.

Choose settings with evidence, not a lucky trial

Hyperparameter tuning compares training configurations under a defined budget. A trial chooses settings, trains a model and records a validation objective. The best observed trial is a useful candidate, but its score is not a guarantee of a globally optimal model or performance on new data.

Day 17 preserves the complete original guide, repeated explanations, code listings and both screenshots below. The expanded notes separate current practical corrections from historical text. No original passage has been summarized away. A small executed example demonstrates the tuner workflow without claiming to reproduce the original MNIST experiment.

DecisionWhat to specifyWhat to verify
Search spaceDepth, width, optimizer, learning rateRanges and conditional relevance
ObjectiveValidation loss or accuracyCorrect direction and available metric
BudgetTrials, epochs, executionsComparable resources and failure logs
SelectionBest observed validation resultKeep final test data untouched
RecoveryTrial files and checkpointFresh build is not trained weights

The main distinction is between model parameters, learned during training, and hyperparameters, selected by the experimenter or tuner. Gradient descent updates weights inside a trial. Random Search, Hyperband and Bayesian Optimization decide how to explore configurations outside that weight-training loop; this is not generally backpropagation through the integer choices of layer count or width.

Important corrections alongside the original

A fresh architecture is not a restored best model

The original section titled “Retrieve the Best Model” calls get_best_hyperparameters, then tuner.hypermodel.build(best_hps). That constructs a new, untrained model with the selected settings; the following fit is necessary to train it. In contrast, tuner.get_best_models loads the tuner’s best checkpointed weights. The added runtime check confirms that the freshly built model has zero optimizer iterations. Retraining is a distinct experiment and is not guaranteed to reproduce the selected validation score exactly.

The original MNIST “validation” data are the official test partition

The full historical code unpacks mnist.load_data() into variables named training and validation. The second returned partition is MNIST’s official test split. Searching against it uses that partition for selection, so its score can no longer be described as an untouched test estimate. Keep the original example as history, but use a separate validation subset from training data and hold back the official test set for a final evaluation. For time series, use a chronological split appropriate to the forecasting task rather than assuming a random split is valid.

Normalization must learn training statistics and travel with inference

The original custom HyperModel creates a Normalization layer in fit without adapting it. That does not learn the intended mean and variance. Current unadapted defaults can leave inputs unchanged. Its local-training-only design would become inconsistent for validation and inference once meaningful statistics were learned. The separate executable example adapts each model’s normalization using training data only and places it inside the model. Raw validation and test inputs then pass through the same stored transformation.

z = (x − μtrain) / √vtrain

An independent actual Keras check uses training inputs 2 and 4, giving mean 3 and variance 1. A validation input 10 therefore becomes 7. The same value is produced through a model containing that adapted layer. This is a two-point preprocessing check, not evidence of classifier accuracy. Near-zero variance needs numerical protection in the implementation; do not divide blindly by zero in hand-written preprocessing.

Read the preserved malformed listing as a historical source record

The long listing beginning with the literal [code class="language-python"] contains multiply escaped quote entities and ends with [/code]. It is retained verbatim and is not directly runnable Python. Fourteen other historical Python bodies parse after separately excluding notebook !pip shell lines. No claim is made that all original listings pass syntax or execute. The complete synthetic procedure below is a separate valid, executed example; the full historical MNIST training remains unexecuted in this pass.

Directory reuse, algorithms and interpretation

The original fixed directory/project names may resume a previous tuner run because overwrite defaults to False. Use a new project for a distinct experiment or intentionally resume a compatible existing one; do not erase valuable trials casually. The added smoke test uses a fresh temporary directory, so its overwrite=False does not collide with earlier runs.

Hyperband allocates training resources across candidates and can stop weak candidates early. Bayesian Optimization uses earlier trial outcomes to choose promising regions; neither guarantees that a tiny budget discovers the best possible model. Early stopping can reduce wasted work but does not eliminate overfitting to the validation set. The original TensorBoard callback code is retained, but a tuner dashboard and TensorBoard browser UI are not newly tested here.

Understand the search-space arithmetic

In the original space, n_hidden ranges from 0 through 8, which gives nine values. The width range 16 through 256 has default step 1, so it contains 241 integers, not just a few powers of two. With two optimizers the registered discrete assignments before learning rate are:

9 × (256 − 16 + 1) × 2 = 4,338

This is not 4,338 distinct architectures: when depth is zero, the width is unused. Learning rate is continuously sampled over a range, so there is no finite total Cartesian-product count without specifying a discretization. Conditional hyperparameters can avoid wasting search effort on settings that have no effect for a selected architecture.

√(10−4 × 10−2) = 10−3 = 0.001

That geometric midpoint explains why log sampling is useful for learning rates spanning orders of magnitude. Equal log distances multiply the value by the same factor. The arithmetic midpoint, 0.00505, answers a different question.

A simple nominal budget of five trials at ten epochs is at most 50 trial-epochs with one execution per trial, before failures, early stopping, resumes or an additional refit. Ten more epochs for a rebuilt final model make a nominal total of 60. Equal epoch counts still need not mean equal compute time when model sizes differ; these are bookkeeping bounds, not measured training times.

h* = arg minh in completed trials Lvalidation(h)

For an accuracy objective you instead maximize validation accuracy. The asterisk here means best among the completed trials, not proof of a global optimum. In the executed addition we minimize validation loss and independently check that the selected score equals the smallest recorded trial score.

Validation loss scores for the three completed synthetic KerasTuner trials; the minimum score marks the selected trial.
Actual recorded scores from the small synthetic run below. This is a workflow check, not MNIST accuracy or a general performance benchmark.

Executed: three small KerasTuner trials

This procedure creates 96 synthetic two-feature examples: 64 for training, 16 for validation and 16 held aside from search. It explores three of four possible width/learning-rate combinations for three epochs each. Normalization is adapted only to the training subset and included in every model. The selected checkpoint is loaded, and inference produces finite outputs of shape (16, 1) on raw held-aside inputs. No test-accuracy claim is made, and these labels are never supplied to the search objective.

Executed with TensorFlow 2.21.0, Keras 3.15.1 and KerasTuner 1.4.8. All three trials completed. The test compares the selected trial to the recorded minimum and confirms a newly built model starts at zero optimizer iterations. This small deterministic-seed exercise does not guarantee identical scores on every platform, prove statistical superiority or reproduce the historical MNIST run.

Run from a writable directory with a day17 subfolder for the result JSON, with the listed libraries installed. Trial artifacts are written into a fresh temporary directory. Notebook installation commands are separate from normal Python syntax.

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
os.environ['TF_NUM_INTEROP_THREADS']='1'
os.environ['TF_NUM_INTRAOP_THREADS']='1'
from pathlib import Path
import tempfile,json
import numpy as np
import tensorflow as tf
import keras
import keras_tuner as kt
keras.utils.set_random_seed(42)
rng=np.random.default_rng(42)
x=rng.normal(size=(96,2)).astype('float32')
y=(x[:,0]+x[:,1]>0).astype('float32')
x_train,x_valid,x_test=x[:64],x[64:80],x[80:]
y_train,y_valid,y_test=y[:64],y[64:80],y[80:]
options=tf.data.Options();options.threading.private_threadpool_size=1
def dataset(a,b):
    return tf.data.Dataset.from_tensor_slices((a,b)).batch(16).with_options(options)
train=dataset(x_train,y_train)
valid=dataset(x_valid,y_valid)
def build_model(hp):
    normalizer=keras.layers.Normalization()
    normalizer.adapt(x_train)
    inputs=keras.Input(shape=(2,))
    z=normalizer(inputs)
    z=keras.layers.Dense(hp.Choice('units',[4,8]),activation='relu')(z)
    outputs=keras.layers.Dense(1,activation='sigmoid')(z)
    model=keras.Model(inputs,outputs)
    model.compile(optimizer=keras.optimizers.Adam(hp.Choice('learning_rate',[0.01,0.05])),loss='binary_crossentropy',metrics=['accuracy'])
    return model
root=Path(tempfile.mkdtemp(prefix='day17-tuner-'))
tuner=kt.RandomSearch(build_model,objective='val_loss',max_trials=3,seed=42,directory=str(root),project_name='synthetic',overwrite=False)
tuner.search(train,validation_data=valid,epochs=3,verbose=0)
trials=list(tuner.oracle.trials.values())
assert len(trials)==3 and all(t.status=='COMPLETED' for t in trials)
best_trial=tuner.oracle.get_best_trials(1)[0]
assert np.isclose(best_trial.score,min(t.score for t in trials))
best_hps=tuner.get_best_hyperparameters(1)[0]
best_model=tuner.get_best_models(1)[0]
fresh_model=tuner.hypermodel.build(best_hps)
assert int(fresh_model.optimizer.iterations)==0
# Inputs are raw here: the adapted normalizer travels inside the model.
pred=best_model(x_test,training=False).numpy()
assert pred.shape==(16,1) and np.isfinite(pred).all()
np.testing.assert_allclose(best_model.layers[1].mean.numpy().reshape(-1),x_train.mean(axis=0),rtol=1e-5,atol=1e-6)
result={'tensorflow':tf.__version__,'keras':keras.__version__,'keras_tuner':kt.__version__,'trials':[{'id':t.trial_id,'score':float(t.score),'status':t.status,'values':t.hyperparameters.values}for t in trials],'best_trial_id':best_trial.trial_id,'best_values':best_hps.values,'best_score':float(best_trial.score),'fresh_optimizer_iterations':int(fresh_model.optimizer.iterations),'training_mean':x_train.mean(axis=0).tolist(),'stored_mean':best_model.layers[1].mean.numpy().reshape(-1).tolist(),'test_prediction_shape':list(pred.shape),'scope':'Synthetic96rows,64training/16validation/16test;3trials×3epochs,4possible combinations. Test labels never used by search; no test-accuracy benchmark claimed.'}
Path('day17/runtime-result.json').write_text(json.dumps(result,indent=2));print(json.dumps(result,indent=2))

Practice: read the trial status and objective before accepting a result. Try a different seed as a new experiment and compare the variability. If you later refit a chosen configuration on more data, decide its training duration without selecting against the final test results. Save the preprocessing and model together so an inference caller cannot accidentally omit normalization.

Primary references

References checked 17 November 2026. Equations use selectable HTML and local scrolling without adding a new math-rendering library. The original script/style strings and existing shortcode listing remain retained. The original two screenshots below are historical outputs, not newly reproduced results.

Complete original guide, code and screenshots

The original content follows in full, including repeated explanations and the malformed escaped listing. Read the separate notes above before running historical code. No original training accuracy has been newly reproduced or certified.

A Comprehensive Guide to Hyperparameter Tuning with Keras Tuner

Introduction

In the world of machine learning, the performance of your model can heavily depend on the choice of hyperparameters. Hyperparameter tuning, the process of finding the optimal settings for these parameters, can be time-consuming and complex. This guide will walk you through the essentials of hyperparameter tuning using Keras Tuner, helping you build more efficient and effective models.

Why Hyperparameter Tuning Matters

Hyperparameters are critical settings that can influence the performance of your machine learning models. These include the learning rate, the number of layers in a neural network, the number of neurons per layer, and many more. Finding the right combination of these settings can dramatically improve your model’s accuracy and efficiency.

Introducing Keras Tuner

Keras Tuner is an open-source library that provides a streamlined approach to hyperparameter tuning for Keras models. It supports various search algorithms, including random search, Hyperband, and Bayesian optimization. This tool not only saves time but also ensures a systematic exploration of the hyperparameter space.

Step-by-Step Guide to Using Keras Tuner

1. Define Your Model with Hyperparameters

Begin by defining a model-building function that includes hyperparameters:


import keras_tuner as kt
import tensorflow as tf

def build_model(hp):
    n_hidden = hp.Int("n_hidden", min_value=0, max_value=8, default=2)
    n_neurons = hp.Int("n_neurons", min_value=16, max_value=256)
    learning_rate = hp.Float("learning_rate", min_value=1e-4, max_value=1e-2, sampling="log")
    optimizer_choice = hp.Choice("optimizer", values=["sgd", "adam"])

    if optimizer_choice == "sgd":
        optimizer = tf.keras.optimizers.SGD(learning_rate=learning_rate)
    else:
        optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate)

    model = tf.keras.Sequential()
    model.add(tf.keras.layers.Flatten())
    for _ in range(n_hidden):
        model.add(tf.keras.layers.Dense(n_neurons, activation="relu"))
    model.add(tf.keras.layers.Dense(10, activation="softmax"))

    model.compile(loss="sparse_categorical_crossentropy",
                  optimizer=optimizer,
                  metrics=["accuracy"])
    return model

2. Choose a Tuning Strategy

Keras Tuner offers several strategies for hyperparameter search. One of the simplest is RandomSearch, but more advanced options like Hyperband are also available. Here’s how to set up a random search:


tuner = kt.RandomSearch(
    build_model,
    objective="val_accuracy",
    max_trials=5,
    directory="my_dir",
    project_name="intro_to_kt"
)

3. Run the Tuner

Once the tuner is set up, you can start the hyperparameter search. This involves specifying the training and validation data:


tuner.search(X_train, y_train, epochs=10, validation_data=(X_valid, y_valid))

4. Retrieve the Best Model

After the search is complete, you can retrieve the best model and its hyperparameters:


best_hps = tuner.get_best_hyperparameters(num_trials=1)[0]
model = tuner.hypermodel.build(best_hps)
model.fit(X_train, y_train, epochs=10, validation_data=(X_valid, y_valid))

Advanced Tuning with Custom Classes

For more complex scenarios, such as including custom preprocessing steps or additional tuning logic, you can create a custom hypermodel class:


class MyClassificationHyperModel(kt.HyperModel):
    def build(self, hp):
        return build_model(hp)

    def fit(self, hp, model, X, y, **kwargs):
        if hp.Boolean("normalize"):
            norm_layer = tf.keras.layers.Normalization()
            X = norm_layer(X)
        return model.fit(X, y, **kwargs)

hypermodel = MyClassificationHyperModel()
tuner = kt.Hyperband(
    hypermodel,
    objective="val_accuracy",
    max_epochs=10,
    directory="my_dir",
    project_name="hyperband"
)

Visualizing Results with TensorBoard

Keras Tuner integrates seamlessly with TensorBoard, providing visual insights into the tuning process. This includes tracking the performance of different hyperparameter combinations and visualizing learning curves.


import tensorflow as tf
from pathlib import Path

root_logdir = Path(tuner.project_dir) / "tensorboard"
tensorboard_cb = tf.keras.callbacks.TensorBoard(root_logdir)
early_stopping_cb = tf.keras.callbacks.EarlyStopping(patience=2)

tuner.search(
    X_train, y_train, 
    epochs=10, 
    validation_data=(X_valid, y_valid), 
    callbacks=[early_stopping_cb, tensorboard_cb]
)

Key Notes:

Hyperparameter tuning is a crucial step in building high-performing machine learning models. Keras Tuner simplifies this process, allowing you to efficiently explore a wide range of hyperparameter settings and find the optimal configuration for your models. By following the steps outlined in this guide, you can leverage Keras Tuner to enhance the accuracy and efficiency of your machine learning projects.

Let’s explain even deeper:

Now that we have showed you a quick overview of  how to use Keras Tuner, let’s dive deeper into what happens behind the scenes during the hyperparameter tuning process. 

 

 

1. Hyperparameter Space Definition

When you define the hyperparameter space, Keras Tuner uses this information to create a search space where each dimension corresponds to a hyperparameter. For example, the `hp.Int` and `hp.Float` functions define integer and float ranges, respectively. This search space is explored using different strategies.

2. Search Algorithms

Keras Tuner supports various search algorithms, each with different strategies for exploring the hyperparameter space:

  • Random Search: Samples hyperparameter values randomly. It is simple and effective but can be inefficient for high-dimensional spaces.
  • Hyperband: An efficient search strategy that combines random search with adaptive resource allocation. It allocates more resources to promising hyperparameter configurations and prunes less promising ones early.
  • Bayesian Optimization: Uses past trial results to model the performance surface and makes informed guesses about the next set of hyperparameters. It balances exploration and exploitation to find the best configuration efficiently.

3. Model Building and Training

For each set of hyperparameters sampled by the tuner, Keras Tuner builds a model using the `build_model` function. This model is then trained on the training data. The training process involves:

  • Forward Pass: Data passes through the network, and activations are computed at each layer.
  • Loss Computation: The loss function measures the difference between the predicted and actual values.
  • Backward Pass: Gradients are computed using backpropagation, and the optimizer updates the model weights to minimize the loss.

4. Performance Evaluation

After training the model on the training data, Keras Tuner evaluates its performance on the validation data. This involves:

  • Validation Metrics: Common metrics include accuracy, loss, precision, recall, and F1-score. The choice of metric depends on the problem type (e.g., classification or regression).
  • Early Stopping: A technique used to prevent overfitting by halting training when the model’s performance on the validation data stops improving.

5. Logging and Analysis

Keras Tuner logs the hyperparameter values and corresponding performance metrics for each trial. This data is stored in the specified directory and can be analyzed to understand the tuning process. Logging includes:

  • Hyperparameter Values: The specific values of each hyperparameter used in the trial.
  • Performance Metrics: The results of the evaluation on the validation set, such as accuracy or loss.
  • Intermediate Results: Information about the model’s performance at different stages of training.

6. Selecting the Best Hyperparameters

Once all trials are completed, Keras Tuner identifies the best set of hyperparameters based on the specified objective metric. This selection process involves:

  • Comparison: Evaluating the performance metrics of all trials to find the hyperparameter combination that yields the best results.
  • Retraining: Rebuilding and retraining the model using the best hyperparameters to ensure robust performance.

7. Advanced Tuning Techniques

For more complex scenarios, advanced tuning techniques can be employed:

  • Custom Hypermodels: Creating custom classes to define more complex model architectures and training procedures.
  • Conditional Hyperparameters: Defining hyperparameters that depend on the values of other hyperparameters, allowing for more flexible and dynamic tuning.

8. Mathematical Foundations

The mathematical foundation of hyperparameter tuning involves optimization techniques and statistical methods:

  • Gradient Descent: An optimization algorithm used to minimize the loss function by iteratively updating model parameters in the direction of the negative gradient.
  • Bayesian Optimization: A probabilistic model that predicts the performance of hyperparameters and guides the search towards the most promising regions of the search space.
  • Successive Halving: A resource allocation method used in Hyperband that allocates more resources to promising hyperparameter configurations and eliminates less promising ones early.

9. Potential Challenges and Considerations

While Keras Tuner simplifies hyperparameter tuning, there are challenges and considerations to keep in mind:

  • Computational Resources: Hyperparameter tuning can be computationally expensive, requiring significant processing power and time.
  • Overfitting: There’s a risk of overfitting to the validation set if not managed properly with techniques like early stopping.
  • Choice of Metric: The choice of objective metric significantly impacts the tuning process and results. Selecting the right metric for the problem is crucial.

10. Practical Applications

Hyperparameter tuning with Keras Tuner can be applied to various machine learning tasks, including:

  • Image Classification: Tuning convolutional neural networks (CNNs) for better accuracy and efficiency.
  • Natural Language Processing: Optimizing models for text classification, sentiment analysis, and language generation.
  • Time Series Forecasting: Improving the performance of models used for predicting future values in time series data.

Conclusion

Understanding what happens behind the scenes during hyperparameter tuning with Keras Tuner provides valuable insights into optimizing machine learning models. By leveraging various search algorithms, mathematical foundations, and advanced tuning techniques, Keras Tuner helps automate and streamline the process of finding the best hyperparameters, leading to improved model performance and efficiency.

Experiment with different tuning strategies and custom hypermodels to suit your specific needs and achieve the best results for your machine learning projects.

So let’s see the complete code from our today lesson:

[code class="language-python"]
# Install necessary packages
!pip install -q -U keras-tuner

import keras_tuner as kt
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
import matplotlib.pyplot as plt
import numpy as np

# Load and preprocess the MNIST dataset
(X_train, y_train), (X_valid, y_valid) = mnist.load_data()
X_train, X_valid = X_train / 255.0, X_valid / 255.0

# Define the model-building function
def build_model(hp):
    n_hidden = hp.Int("n_hidden", min_value=0, max_value=8, default=2)
    n_neurons = hp.Int("n_neurons", min_value=16, max_value=256)
    learning_rate = hp.Float("learning_rate", min_value=1e-4, max_value=1e-2, sampling="log")
    optimizer = hp.Choice("optimizer", values=["sgd", "adam"])

    if optimizer == "sgd":
        optimizer = tf.keras.optimizers.SGD(learning_rate=learning_rate)
    else:
        optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate)

    model = Sequential()
    model.add(Flatten(input_shape=(28, 28)))
    for _ in range(n_hidden):
        model.add(Dense(n_neurons, activation="relu"))
    model.add(Dense(10, activation="softmax"))

    model.compile(loss="sparse_categorical_crossentropy",
                  optimizer=optimizer,
                  metrics=["accuracy"])
    return model

# Initialize the tuner
tuner = kt.RandomSearch(
    build_model,
    objective="val_accuracy",
    max_trials=5,
    directory="my_dir",
    project_name="intro_to_kt"
)

# Run the hyperparameter search
tuner.search(X_train, y_train, epochs=10, validation_data=(X_valid, y_valid))

# Retrieve the best hyperparameters and build the best model
best_hps = tuner.get_best_hyperparameters(num_trials=1)[0]
model = tuner.hypermodel.build(best_hps)

# Train the best model
model.fit(X_train, y_train, epochs=10, validation_data=(X_valid, y_valid))

# Print the best hyperparameters
print(f"""
The hyperparameter search is complete. The optimal number of hidden layers is {best_hps.get('n_hidden')},
the optimal number of units in each layer is {best_hps.get('n_neurons')}, and the optimal learning rate
for the optimizer is {best_hps.get('learning_rate')}.
""")

# Make predictions on the validation set
predictions = model.predict(X_valid)

# Function to plot the results
def plot_images(predictions, true_labels, images, num_rows=3, num_cols=3):
    plt.figure(figsize=(10, 10))
    for i in range(num_rows * num_cols):
        plt.subplot(num_rows, num_cols, i + 1)
        plt.xticks([])
        plt.yticks([])
        plt.grid(False)
        plt.imshow(images[i], cmap=plt.cm.binary)
        predicted_label = np.argmax(predictions[i])
        true_label = true_labels[i]
        color = 'blue' if predicted_label == true_label else 'red'
        plt.xlabel(f"Pred: {predicted_label} (True: {true_label})", color=color)
    plt.show()

# Plot a sample of the predictions
plot_images(predictions, y_valid, X_valid)
[/code]






MNIST Model Explanation


Keras Tuner MNIST Example

Explanation:

Installation and Imports:
keras-tuner is installed and necessary libraries are imported.
matplotlib is imported for visualization purposes.

!pip install -q -U keras-tuner

import keras_tuner as kt
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
import matplotlib.pyplot as plt
import numpy as np

Data Preprocessing:
The MNIST dataset is loaded and normalized.

# Load and preprocess the MNIST dataset
(X_train, y_train), (X_valid, y_valid) = mnist.load_data()
X_train, X_valid = X_train / 255.0, X_valid / 255.0

Model Building:
The build_model function defines the architecture with tunable hyperparameters.

def build_model(hp):
    n_hidden = hp.Int("n_hidden", min_value=0, max_value=8, default=2)
    n_neurons = hp.Int("n_neurons", min_value=16, max_value=256)
    learning_rate = hp.Float("learning_rate", min_value=1e-4, max_value=1e-2, sampling="log")
    optimizer = hp.Choice("optimizer", values=["sgd", "adam"])

    if optimizer == "sgd":
        optimizer = tf.keras.optimizers.SGD(learning_rate=learning_rate)
    else:
        optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate)

    model = Sequential()
    model.add(Flatten(input_shape=(28, 28)))
    for _ in range(n_hidden):
        model.add(Dense(n_neurons, activation="relu"))
    model.add(Dense(10, activation="softmax"))

    model.compile(loss="sparse_categorical_crossentropy",
                  optimizer=optimizer,
                  metrics=["accuracy"])
    return model

Hyperparameter Tuning:
A RandomSearch tuner is initialized and used to find the best hyperparameters.

tuner = kt.RandomSearch(
    build_model,
    objective="val_accuracy",
    max_trials=5,
    directory="my_dir",
    project_name="intro_to_kt"
)

Running the Hyperparameter Search:
The tuner searches for the optimal hyperparameters by training multiple models.

tuner.search(X_train, y_train, epochs=10, validation_data=(X_valid, y_valid))

Training the Best Model:
The best model is built using the optimal hyperparameters and trained.

best_hps = tuner.get_best_hyperparameters(num_trials=1)[0]
model = tuner.hypermodel.build(best_hps)

# Train the best model
model.fit(X_train, y_train, epochs=10, validation_data=(X_valid, y_valid))

print(f"""
The hyperparameter search is complete. The optimal number of hidden layers is {best_hps.get('n_hidden')},
the optimal number of units in each layer is {best_hps.get('n_neurons')}, and the optimal learning rate
for the optimizer is {best_hps.get('learning_rate')}.
""")

Making Predictions:
The trained model is used to make predictions on the validation set.

predictions = model.predict(X_valid)

Visualization:
The plot_images function plots a sample of images from the validation set along with their true and predicted labels. The colors indicate whether the prediction is correct (blue) or incorrect (red).

def plot_images(predictions, true_labels, images, num_rows=3, num_cols=3):
    plt.figure(figsize=(10, 10))
    for i in range(num_rows * num_cols):
        plt.subplot(num_rows, num_cols, i + 1)
        plt.xticks([])
        plt.yticks([])
        plt.grid(False)
        plt.imshow(images[i], cmap=plt.cm.binary)
        predicted_label = np.argmax(predictions[i])
        true_label = true_labels[i]
        color = 'blue' if predicted_label == true_label else 'red'
        plt.xlabel(f"Pred: {predicted_label} (True: {true_label})", color=color)
    plt.show()

# Plot a sample of the predictions
plot_images(predictions, y_valid, X_valid)

Summary:
By running this code in Google Colab, you can visualize how the model classifies handwritten digits from the MNIST dataset. The hyperparameter tuning process uses Keras Tuner to find optimal model parameters, builds and trains the best model, and then visualizes the predictions with color-coded labels to indicate correct (blue) or incorrect (red) classifications.

By running this code in Google Colab, you can visualize how the model classifies the handwritten digits from the MNIST dataset.


Here is the results :

Historical Keras Tuner output screenshot 18312
Historical Keras Tuner output screenshot 18313

Questions about hyperparameter tuning

Does KerasTuner guarantee globally optimal hyperparameters?

No. It compares the trials completed within your chosen search space, objective and budget. Five random trials cannot guarantee a global optimum or future test performance.

Is hypermodel.build(best_hps) already trained?

No. It builds a fresh model with the chosen settings. Use get_best_models to retrieve a model from the tuner checkpoint, or explicitly train the newly built model.

Why keep a separate test set?

Validation results guide trial selection and can themselves be overfit. A final test set must remain outside that selection process if you want an independent evaluation.

Where should Normalization.adapt be called?

Learn normalization statistics from training data only. Put the adapted layer inside the model so validation and later raw inputs use the same transformation.

What does logarithmic learning-rate sampling mean?

Equal distances in log space represent multiplicative changes. Between 0.0001 and 0.01 the geometric midpoint is 0.001, not the arithmetic midpoint.

Was the full original MNIST tuning experiment reproduced?

No. The historical MNIST code and screenshots remain preserved, including the malformed escaped code listing with a visible warning. A separate three-trial synthetic KerasTuner experiment was executed and its limited scope is stated.

You Can Also Learn Deep Learning in 80 Days Inside the iOS App Continue this roadmap in a focused mobile study experience with offline access, flashcards, notes, and progress tracking.
Open on the App Store