What are Hyperparameters?
Parameters (weights) are learned during training. Hyperparameters are the choices you make before training: number of layers, neurons, dropout rate, learning rate, batch size. Trying them by hand is slow, so we automate the search.
Install
bash
pip install keras-tuner
Step 1: Write a Model Builder
The builder function receives a hp object. You ask it for values, and the tuner tries different ones.
python
import keras
from keras import layers
import keras_tuner as kt
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(layers.Dense(
units=hp.Int(f"units_{i}", min_value=32, max_value=256, step=32),
activation="relu"))
model.add(layers.Dropout(hp.Float(f"dropout_{i}", 0.0, 0.5, step=0.1)))
model.add(layers.Dense(10, activation="softmax"))
lr = hp.Choice("learning_rate", [1e-2, 1e-3, 1e-4])
model.compile(optimizer=keras.optimizers.Adam(lr),
loss="sparse_categorical_crossentropy", metrics=["accuracy"])
return model
| Method | Use |
hp.Int | Whole numbers, like units or layers |
hp.Float | Decimal numbers, like dropout |
hp.Choice | A list of options |
hp.Boolean | True or False |
Step 2: Run the Search
python
(x_train, y_train), _ = keras.datasets.mnist.load_data()
x_train = x_train.reshape(-1, 784).astype("float32") / 255.0
tuner = kt.RandomSearch(
build_model,
objective="val_accuracy",
max_trials=10, # try 10 different combinations
directory="tuning",
project_name="mnist",
)
tuner.search(x_train, y_train, epochs=5, validation_split=0.2)
Step 3: Get the Best Model
python
best_hp = tuner.get_best_hyperparameters(1)[0]
print(best_hp.values)
best_model = tuner.get_best_models(1)[0]
best_model.summary()
Hyperband: Smarter and Faster
Hyperband starts many models with a small number of epochs and gives more time only to the promising ones.
python
tuner = kt.Hyperband(
build_model,
objective="val_accuracy",
max_epochs=15,
factor=3,
directory="tuning",
project_name="mnist_hb",
)
tuner.search(x_train, y_train, validation_split=0.2,
callbacks=[keras.callbacks.EarlyStopping(patience=2)])
| Tuner | How it works |
| RandomSearch | Tries random combinations, simple and effective |
| Hyperband | Stops bad trials early to save time |
| BayesianOptimization | Uses previous results to pick better next trials |
Tip: Tune the learning rate first. It is the hyperparameter with the biggest effect. Keep the search space small and always use a validation set.
Conclusion
KerasTuner replaces guesswork with a systematic search. Define the search space once and let the computer find a strong configuration.
Quick Summary: Write build_model(hp), choose a tuner, call search() and fetch the best model.