Keras Tuner. RecursionError: maximum recursion depth exceeded

Конфигурация:

Platform: linux
Python: 3.12.8
Pandas: 2.2.3
Numpy: 2.0.2
Matplotlib: 3.10.0
Seaborn: 0.13.2
Scikit-learn: 1.6.0
Tensorflow: 2.18.0
Keras: 3.7.0
Keras_tuner: 1.4.7

Код:

def build_model_Dense_Autoencoder(hp):
    # Tuning your model using Keras Tuner
    # Tune the number of units in the first Dense layer
    # Choose an optimal value between QTY_PARAMETRS-effect_Data_train.shape[1]
       
    hp_units = hp.Int("units", min_value=QTY_PARAMETRS, max_value=effect_Data_train.shape[1], step=1)            

    # Создаем нашу модель
    input_tensor_size = effect_Data_train.shape[1]
    input_tensor = Input(shape=(input_tensor_size,))
    x = layers.Dense(input_tensor_size, activation=ACTIVATION)(input_tensor)
    x = layers.Dense(hp_units, activation=ACTIVATION)(x)
    x = layers.Dense(QTY_PARAMETRS-1, activation=ACTIVATION)(x)
    output_tensor = layers.Dense(QTY_PARAMETRS, activation=ACTIVATION)(x)

    model = keras.Model(input_tensor, output_tensor)
    model.compile(loss='mae', metrics=['accuracy']) # С mse заметно хуже...

    model.summary()

    return model

# Создаю тюнер...
tuner = kt.RandomSearch(hypermodel=build_model_Dense_Autoencoder,
                        objective='val_accuracy',
                        max_trials=3,
                        executions_per_trial=1,
                        overwrite=True,
                        directory=my_path_data_dir+'/'+model_name,
                        project_name=model_name)

# Заказываю поиск...
tuner.search(effect_Data_train,
             effect_Data_train.iloc[:,:QTY_PARAMETRS],
             epochs=10,
             validation_split=0.25,
             callbacks=callbacks_list,
             verbose=VERBOSE)

Получаю ошибку внутри keras.tuner. Все обновил, код запустил в отдельной ячейке... Ничего не меняется... Картинку с ошибкой привел для демонстрации. Чего там внутри Keras творится описать не могу.

Ошибка

RecursionError: maximum recursion depth exceeded

Подскажите, плиз. Устал уже...

Добрый вечер. Прошу прощения за не полностью оформленный вопрос. Callback - абсолютно стандартный...

callbacks_list = [
                 keras.callbacks.EarlyStopping(
                 #monitor='val_accuracy',
                 monitor='accuracy',
                 patience=20
                 ),
                 keras.callbacks.ModelCheckpoint(
                 #filepath=my_path_data_dir+'/'+current_parametr_name+'_'+current_model_name+'.h5',        
                 filepath=my_path_data_dir+'/'+current_parametr_name+'_'+current_model_name+'.keras',        
                 #monitor='val_accuracy',
                 monitor='accuracy',
                 save_best_only=True
                 ),
             keras.callbacks.ReduceLROnPlateau(
                 #monitor='val_accuracy',
                 monitor='accuracy',
                 factor=0.1,
                 patience=10        
                 ),
             keras.callbacks.TensorBoard(
                 log_dir=my_path_data_dir,
                 histogram_freq=1,
                 embeddings_freq=1,
                 write_graph=True,
                 write_images=True
                 )
 ] 

Дополнительно промоделировал пример из keras_tuner...

import platform
import os
from sys import platform as pltf

import numpy as np

import tensorflow as tf
import keras
from keras import layers
import keras_tuner

print('*** Versions:***')
print('Platform:', pltf)
print('Python:', platform.python_version())
#print('Tensorflow:', tf.__version__)
print('Keras:', keras.__version__)
print('Keras_tuner:', keras_tuner.__version__)

tf.config.list_physical_devices('GPU')
# import tensorflow as tf
print("Num GPUs Available: ", len(tf.config.list_physical_devices('GPU')))

my_path_data_dir='~/Temp'
# Allocator (GPU_0_bfc) ran out of memory trying to allocate 894.30MiB (rounded to 937744640)requested by op _EagerConst
#If the cause is memory fragmentation maybe the environment variable 
TF_GPU_ALLOCATOR='cuda_malloc_async' # will improve the situation. 

XLA_PYTHON_CLIENT_PREALLOCATE=False
TF_FORCE_UNIFIED_MEMORY=True
XLA_CLIENT_MEM_FRACTION=3,2

# Была ошибка...
# Attempting to perform BLAS operation using StreamExecutor without BLAS support...
# Интернет рекомендовал ограничить память...

gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
    for gpu in gpus:
        # Конфигурация доступных GPU так, чтобы память на них выделялась участками в зависимости от потребностей
        tf.config.experimental.set_memory_growth(gpu, True)
    try:
        tf.config.experimental.set_virtual_device_configuration(
        #gpus[0],[tf.config.experimental.VirtualDeviceConfiguration(memory_limit=5120)])
        gpus[0],[tf.config.experimental.VirtualDeviceConfiguration(memory_limit=73728)]) # 65536+8192
    except RuntimeError as e:
        print(e)

def build_model(hp):
    model = keras.Sequential()
    model.add(layers.Flatten())
    # Tune the number of layers.
    for i in range(hp.Int("num_layers", 1, 3)):
        model.add(
            layers.Dense(
                # Tune number of units separately.
                units=hp.Int(f"units_{i}", min_value=32, max_value=512, step=32),
                activation=hp.Choice("activation", ["relu", "tanh"]),
            )
        )
    if hp.Boolean("dropout"):
        model.add(layers.Dropout(rate=0.25))
    model.add(layers.Dense(10, activation="softmax"))
    learning_rate = hp.Float("lr", min_value=1e-4, max_value=1e-2, sampling="log")
    model.compile(
        optimizer=keras.optimizers.Adam(learning_rate=learning_rate),
        loss="categorical_crossentropy",
        metrics=["accuracy"],
    )
    return model


build_model(keras_tuner.HyperParameters())

tuner = keras_tuner.RandomSearch(
    hypermodel=build_model,
    #hypermodel=build_model(kt.HyperParameters()),
    #hypermodel=f,
    objective="val_accuracy",
    max_trials=3,
    executions_per_trial=2,
    overwrite=True,
    directory=my_path_data_dir,
    project_name="helloworld",
)

tuner.search_space_summary()

(x, y), (x_test, y_test) = keras.datasets.mnist.load_data()

x_train = x[:-10000]
x_val = x[-10000:]
y_train = y[:-10000]
y_val = y[-10000:]

x_train = np.expand_dims(x_train, -1).astype("float32") / 255.0
x_val = np.expand_dims(x_val, -1).astype("float32") / 255.0
x_test = np.expand_dims(x_test, -1).astype("float32") / 255.0

num_classes = 10
y_train = keras.utils.to_categorical(y_train, num_classes)
y_val = keras.utils.to_categorical(y_val, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

tuner.search(x_train, y_train, epochs=2, validation_data=(x_val, y_val))

Код работает, когда память GPU свободна! Если этот пример (из документации!) я вставлю в свой проект, уже после расчетов моих моделей, то выдает ошибку CUDA_ERROR_OUT_OF_MEMORY и затем всяческий бардак с превышением рекурсивных вызовов...

Сейчас размышляю... Как освободить память GPU? Советов много, но все не очень понятно. Либо разделить проект на 2 ноутбука. В первом генерировать модели, во втором их настраивать.

Спасибо.


Ответы (1 шт):

Автор решения: Grey O

Разобрался.

  1. Память ни при чем.

  2. Причина - несоответствие версий Keras, Tensorflow, KerasTuner.

  3. Надо после всех import вставить определение следующей переменной окружения:

    os.environ["TF_USE_LEGACY_KERAS"] = "0" # Без этого признака вызывается Keras 2! А мне надо Keras 3 и соответствующий KerasTuner & Tensorflow!
    
    print(os.environ["TF_USE_LEGACY_KERAS"])
    
  4. https://tensorflow.google.cn/agents/tutorials/2_environments_tutorial

  5. Спасибо всем неравнодушным за помощь.

→ Ссылка