Path: blob/master/guides/keras_tuner/visualize_tuning.py
3293 views
"""1Title: Visualize the hyperparameter tuning process2Author: Haifeng Jin3Date created: 2021/06/254Last modified: 2021/06/055Description: Using TensorBoard to visualize the hyperparameter tuning process in KerasTuner.6Accelerator: GPU7"""89"""shell10pip install keras-tuner -q11"""1213"""14## Introduction1516KerasTuner prints the logs to screen including the values of the17hyperparameters in each trial for the user to monitor the progress. However,18reading the logs is not intuitive enough to sense the influences of19hyperparameters have on the results, Therefore, we provide a method to20visualize the hyperparameter values and the corresponding evaluation results21with interactive figures using TensorBoard.2223[TensorBoard](https://www.tensorflow.org/tensorboard) is a useful tool for24visualizing the machine learning experiments. It can monitor the losses and25metrics during the model training and visualize the model architectures.26Running KerasTuner with TensorBoard will give you additional features for27visualizing hyperparameter tuning results using its HParams plugin.28"""2930"""31We will use a simple example of tuning a model for the MNIST image32classification dataset to show how to use KerasTuner with TensorBoard.3334The first step is to download and format the data.35"""3637import numpy as np38import keras_tuner39import keras40from keras import layers4142(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()43# Normalize the pixel values to the range of [0, 1].44x_train = x_train.astype("float32") / 25545x_test = x_test.astype("float32") / 25546# Add the channel dimension to the images.47x_train = np.expand_dims(x_train, -1)48x_test = np.expand_dims(x_test, -1)49# Print the shapes of the data.50print(x_train.shape)51print(y_train.shape)52print(x_test.shape)53print(y_test.shape)5455"""56Then, we write a `build_model` function to build the model with hyperparameters57and return the model. The hyperparameters include the type of model to use58(multi-layer perceptron or convolutional neural network), the number of layers,59the number of units or filters, whether to use dropout.60"""616263def build_model(hp):64inputs = keras.Input(shape=(28, 28, 1))65# Model type can be MLP or CNN.66model_type = hp.Choice("model_type", ["mlp", "cnn"])67x = inputs68if model_type == "mlp":69x = layers.Flatten()(x)70# Number of layers of the MLP is a hyperparameter.71for i in range(hp.Int("mlp_layers", 1, 3)):72# Number of units of each layer are73# different hyperparameters with different names.74x = layers.Dense(75units=hp.Int(f"units_{i}", 32, 128, step=32),76activation="relu",77)(x)78else:79# Number of layers of the CNN is also a hyperparameter.80for i in range(hp.Int("cnn_layers", 1, 3)):81x = layers.Conv2D(82hp.Int(f"filters_{i}", 32, 128, step=32),83kernel_size=(3, 3),84activation="relu",85)(x)86x = layers.MaxPooling2D(pool_size=(2, 2))(x)87x = layers.Flatten()(x)8889# A hyperparamter for whether to use dropout layer.90if hp.Boolean("dropout"):91x = layers.Dropout(0.5)(x)9293# The last layer contains 10 units,94# which is the same as the number of classes.95outputs = layers.Dense(units=10, activation="softmax")(x)96model = keras.Model(inputs=inputs, outputs=outputs)9798# Compile the model.99model.compile(100loss="sparse_categorical_crossentropy",101metrics=["accuracy"],102optimizer="adam",103)104return model105106107"""108We can do a quick test of the models to check if it build successfully for both109CNN and MLP.110"""111112113# Initialize the `HyperParameters` and set the values.114hp = keras_tuner.HyperParameters()115hp.values["model_type"] = "cnn"116# Build the model using the `HyperParameters`.117model = build_model(hp)118# Test if the model runs with our data.119model(x_train[:100])120# Print a summary of the model.121model.summary()122123# Do the same for MLP model.124hp.values["model_type"] = "mlp"125model = build_model(hp)126model(x_train[:100])127model.summary()128129"""130Initialize the `RandomSearch` tuner with 10 trials and using validation131accuracy as the metric for selecting models.132"""133134tuner = keras_tuner.RandomSearch(135build_model,136max_trials=10,137# Do not resume the previous search in the same directory.138overwrite=True,139objective="val_accuracy",140# Set a directory to store the intermediate results.141directory="/tmp/tb",142)143144"""145Start the search by calling `tuner.search(...)`. To use TensorBoard, we need146to pass a `keras.callbacks.TensorBoard` instance to the callbacks.147"""148149tuner.search(150x_train,151y_train,152validation_split=0.2,153epochs=2,154# Use the TensorBoard callback.155# The logs will be write to "/tmp/tb_logs".156callbacks=[keras.callbacks.TensorBoard("/tmp/tb_logs")],157)158159"""160If running in Colab, the following two commands will show you the TensorBoard161inside Colab.162163`%load_ext tensorboard`164165`%tensorboard --logdir /tmp/tb_logs`166167You have access to all the common features of the TensorBoard. For example, you168can view the loss and metrics curves and visualize the computational graph of169the models in different trials.170171172173174In addition to these features, we also have a HParams tab, in which there are175three views. In the table view, you can view the 10 different trials in a176table with the different hyperparameter values and evaluation metrics.177178179180On the left side, you can specify the filters for certain hyperparameters. For181example, you can specify to only view the MLP models without the dropout layer182and with 1 to 2 dense layers.183184185186Besides the table view, it also provides two other views, parallel coordinates187view and scatter plot matrix view. They are just different visualization188methods for the same data. You can still use the panel on the left to filter189the results.190191In the parallel coordinates view, each colored line is a trial.192The axes are the hyperparameters and evaluation metrics.193194195196In the scatter plot matrix view, each dot is a trial. The plots are projections197of the trials on planes with different hyperparameter and metrics as the axes.198199200201"""202203204