{"id":8256,"library":"keras-tuner","title":"KerasTuner","description":"KerasTuner is a hyperparameter optimization library for Keras, making it easy to find the best hyperparameters for your machine learning models. It supports various tuning algorithms like RandomSearch, Hyperband, and BayesianOptimization. The library is actively maintained and frequently updated, with recent versions adding support for Keras 3 (multi-backend) and improving distributed execution.","status":"active","version":"1.4.8","language":"en","source_language":"en","source_url":"https://github.com/keras-team/keras-tuner","tags":["keras","tensorflow","machine-learning","hyperparameter-tuning","deep-learning","optimization"],"install":[{"cmd":"pip install keras-tuner","lang":"bash","label":"Basic install"},{"cmd":"pip install keras-tuner[tensorflow]","lang":"bash","label":"Install with TensorFlow backend"}],"dependencies":[{"reason":"Required for model definition and training. KerasTuner 1.4.6+ supports Keras 3+ and maintains backward compatibility with Keras 2.","package":"keras","optional":false},{"reason":"A common backend for Keras models. Explicitly installing `keras-tuner[tensorflow]` ensures compatibility.","package":"tensorflow","optional":true},{"reason":"Added in v1.4.8; essential for distributed tuning communication.","package":"grpcio","optional":false},{"reason":"Added in v1.4.8; essential for distributed tuning communication.","package":"protobuf","optional":false}],"imports":[{"symbol":"HyperModel","correct":"from keras_tuner import HyperModel"},{"note":"While older versions might have exposed some tuners directly under `keras_tuner`, the recommended and consistent path is `keras_tuner.tuners`.","wrong":"from keras_tuner import RandomSearch","symbol":"RandomSearch","correct":"from keras_tuner.tuners import RandomSearch"},{"note":"While older versions might have exposed some tuners directly under `keras_tuner`, the recommended and consistent path is `keras_tuner.tuners`.","wrong":"from keras_tuner import BayesianOptimization","symbol":"BayesianOptimization","correct":"from keras_tuner.tuners import BayesianOptimization"},{"symbol":"Hyperband","correct":"from keras_tuner.tuners import Hyperband"}],"quickstart":{"code":"import keras\nimport keras_tuner as kt\nimport numpy as np\n\n# Define a HyperModel\nclass MyHyperModel(kt.HyperModel):\n    def build(self, hp):\n        model = keras.Sequential()\n        model.add(keras.layers.Flatten(input_shape=(28, 28)))\n        model.add(keras.layers.Dense(units=hp.Int('units', min_value=32, max_value=512, step=32),\n                                     activation='relu'))\n        model.add(keras.layers.Dense(10, activation='softmax'))\n        model.compile(optimizer=keras.optimizers.Adam(hp.Choice('learning_rate', values=[1e-2, 1e-3, 1e-4])),\n                      loss='sparse_categorical_crossentropy',\n                      metrics=['accuracy'])\n        return model\n\n# Load dummy data (Fashion MNIST)\n(x_train, y_train), (x_test, y_test) = keras.datasets.fashion_mnist.load_data()\nx_train = x_train[:10000].astype('float32') / 255.0\ny_train = y_train[:10000]\nx_val = x_test[:2000].astype('float32') / 255.0\ny_val = y_test[:2000]\n\n# Instantiate a tuner\ntuner = kt.RandomSearch(\n    MyHyperModel(),\n    objective='val_accuracy',\n    max_trials=3,\n    executions_per_trial=2,\n    directory='my_dir',\n    project_name='my_intro_to_kt'\n)\n\n# Search for the best hyperparameters\ntuner.search(x_train, y_train, epochs=2, validation_data=(x_val, y_val))\n\n# Get the best hyperparameters\nbest_hps = tuner.get_best_hyperparameters(num_trials=1)[0]\nprint(f\"Best units: {best_hps.get('units')}, best learning rate: {best_hps.get('learning_rate')}\")\n\n# Get the best model\nbest_model = tuner.get_best_models(num_models=1)[0]\nbest_model.evaluate(x_val, y_val)","lang":"python","description":"This quickstart demonstrates how to use KerasTuner with a `HyperModel` to search for optimal hyperparameters for a simple Keras model on the Fashion MNIST dataset. It defines a model with tunable dense layer units and learning rate, then uses `RandomSearch` to find the best configuration."},"warnings":[{"fix":"Update any imports of internal components from `keras_tuner.some_private_api` to `keras_tuner.src.some_private_api`. Public APIs remain at the top level (e.g., `keras_tuner.tuners.RandomSearch`).","message":"Private APIs (e.g., internal utility functions) were moved under `keras_tuner.src.*`. Direct imports from old private paths will fail.","severity":"breaking","affected_versions":">=1.4.0"},{"fix":"If using Keras 3, ensure you have `keras` installed and potentially set `KERAS_BACKEND` environment variable. If using Keras 2, ensure you have `tensorflow<2.16` and `keras<3.0`.","message":"KerasTuner v1.4.6+ introduced official support for Keras 3 (multi-backend), while still supporting Keras 2. Ensure your Keras environment is correctly configured if you use a specific backend (e.g., TensorFlow, PyTorch, JAX).","severity":"gotcha","affected_versions":">=1.4.6"},{"fix":"Upgrade to KerasTuner v1.4.7 or newer to benefit from fixes to distributed execution stability. Carefully manage the lifecycle of parallel tuning processes.","message":"Distributed tuning (especially when `project_name` is shared across multiple processes) can be sensitive to race conditions or premature chief shutdown, which have been incrementally fixed across versions. Issues like client waiting indefinitely or chief exiting early are possible.","severity":"gotcha","affected_versions":"<1.4.7"},{"fix":"Ensure you have compatible versions of `grpcio` and `protobuf` installed. A clean `pip install keras-tuner` will pull the correct versions. If conflicts arise, consider using a virtual environment.","message":"KerasTuner v1.4.8 added `grpcio` and `protobuf` as direct dependencies. If you have older or incompatible versions of these libraries installed, it might lead to conflicts or runtime errors.","severity":"gotcha","affected_versions":">=1.4.8"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"For tuner classes like `RandomSearch`, `Hyperband`, `BayesianOptimization`, import from `keras_tuner.tuners`. For `HyperModel`, import from `keras_tuner` directly. The `Tuner` class itself is an abstract base class not typically imported directly by users.","cause":"Attempting to import internal classes directly from `keras_tuner.engine.*` paths, which were either not intended for public use or had their exposure fixed in later versions.","error":"ImportError: cannot import name 'Tuner' from 'keras_tuner.engine.tuner'"},{"fix":"Upgrade TensorFlow to a more recent version (e.g., TensorFlow 2.3+). KerasTuner aims to support a broad range, but newer features might rely on newer Keras/TensorFlow capabilities.","cause":"This error typically occurs when using an older TensorFlow version (e.g., TensorFlow 2.0-2.2) with a newer KerasTuner version that expects `get_build_config` to be present on Keras models, which was added in later TensorFlow/Keras versions.","error":"AttributeError: 'KerasTensor' object has no attribute 'get_build_config'"},{"fix":"Review your imports. For public interfaces like `HyperParameters`, use `from keras_tuner import HyperParameters`. Avoid importing from `keras_tuner.engine` paths which are internal.","cause":"After KerasTuner v1.4.0, some internal module structures changed, potentially leading to 'ModuleNotFoundError' if specific internal paths were directly imported.","error":"ModuleNotFoundError: No module named 'keras_tuner.engine.hyperparameters'"}]}