Keras Tuner Legacy Imports

1.0.5 · active · verified Thu Apr 16

The `kt-legacy` library provides backward-compatible import names for Keras Tuner. It allows users to import Keras Tuner components using the `kerastuner` namespace, which was the original import path, instead of the current `keras_tuner` namespace. This is particularly useful for migrating or maintaining compatibility with older codebases that expect the `kerastuner` module.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to import and initialize a Keras Tuner `RandomSearch` tuner using the `kerastuner` legacy import provided by the `kt-legacy` package. It defines a simple hypermodel and initializes the tuner, ready for a hyperparameter search.

import keras
import kerastuner as kt

def build_model(hp):
    model = keras.Sequential([
        keras.layers.Flatten(input_shape=(28, 28)),
        keras.layers.Dense(
            units=hp.Int('units', min_value=32, max_value=512, step=32),
            activation='relu'
        ),
        keras.layers.Dense(10, activation='softmax')
    ])
    model.compile(
        optimizer=keras.optimizers.Adam(learning_rate=hp.Choice('learning_rate', values=[1e-2, 1e-3, 1e-4])),
        loss='sparse_categorical_crossentropy',
        metrics=['accuracy']
    )
    return model

# Example of using a tuner with the legacy import
tuner = kt.RandomSearch(
    hypermodel=build_model,
    objective='val_accuracy',
    max_trials=2, # For quick demonstration
    executions_per_trial=1,
    directory='my_dir', project_name='intro_to_kt_legacy'
)

# Note: To run search, you would typically need training data, e.g.,
# (img_train, label_train), (img_test, label_test) = keras.datasets.fashion_mnist.load_data()
# img_train = img_train.astype('float32') / 255.0
# label_train = label_train[:100] # Subset for quick example
# img_train = img_train[:100]
# tuner.search(img_train, label_train, epochs=2, validation_split=0.2)

print("Keras Tuner (legacy import) initialized successfully.")
# print(tuner.get_best_hyperparameters()[0].values)

view raw JSON →