使用Keras Tuner调参时遇模型实例无效RuntimeError问题求助
Let's break down the issues in your code and fix them step by step:
1. Duplicate Hyperparameter Names (Critical Issue)
Looking at your build method, you're reusing hyperparameter names which causes conflicts:
- The first
Denselayer usesunits_0andact_0 - Then your loop starts at
i=0, creating anotherunits_0andact_0
This confuses Keras Tuner and can lead to invalid model construction. Let's rename the input layer's hyperparameters to avoid duplication:
def build(self, hp): model=Sequential() # Rename input layer params to avoid conflict with loop model.add(Dense( units=hp.Int('units_input', 30, 900, step=30), activation=hp.Choice('act_input', ['relu', 'tanh']), input_dim=12 )) # Start loop index from 1 to prevent duplicate names num_layers = hp.Int('layers', 3, 9) for i in range(1, num_layers + 1): model.add(Dense( units=hp.Int(f'units_{i}', 30, 900, step=30), activation=hp.Choice(f'act_{i}', ['relu', 'tanh']) )) model.add(Dense(6, activation='softmax')) model.compile( loss='categorical_crossentropy', optimizer=hp.Choice('optimizer', ['adam', 'sgd']), metrics=['categorical_accuracy'] ) return model
2. Import Consistency (Avoid tf.keras vs keras Conflicts)
Keras Tuner is designed to work with tensorflow.keras, not the standalone Keras library. Ensure all your imports come from tensorflow.keras:
from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense import keras_tuner as kt import numpy as np import tensorflow as tf
Mixing standalone keras and tensorflow.keras can cause the tuner to fail recognizing your Sequential model as a valid Keras instance.
3. Fix the Seed Parameter
Your seed=(np.random.seed(1)) is incorrect because np.random.seed() returns None. Instead, set seeds explicitly:
# Fix random seeds at the start of your script np.random.seed(1) tf.random.set_seed(1) # Then initialize the tuner with seed=1 tuner = kt.tuners.bayesian.BayesianOptimization( hypermodel, objective='val_accuracy', max_trials=5, executions_per_trial=3, seed=1, # Directly use integer seed directory='Tests', project_name='test' )
4. Correct the get_best_models Usage
Your line models = tuner.get_best_models(num_models=2).summary() will throw an error because get_best_models returns a list of models, not a single model. Modify it to:
models = tuner.get_best_models(num_models=2) # Print summary for each best model for idx, model in enumerate(models): print(f"Best Model {idx+1} Summary:") model.summary()
Additional Checks
- Verify your
dataandlabelsare correctly formatted: Ensurelabelsare one-hot encoded (since you're usingcategorical_crossentropy). If they're integer labels, switch tosparse_categorical_crossentropyinstead. - Update Keras Tuner and TensorFlow to their latest compatible versions to avoid version mismatch bugs.
Try applying these fixes, and your hyperparameter search should run without the "invalid model instance" error.
内容的提问来源于stack exchange,提问作者Bolverkr

