You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Keras Tuner调参时遇模型实例无效RuntimeError问题求助

Fixing "Model-building function did not return a valid Keras Model instance" Error in Keras Tuner

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 Dense layer uses units_0 and act_0
  • Then your loop starts at i=0, creating another units_0 and act_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 data and labels are correctly formatted: Ensure labels are one-hot encoded (since you're using categorical_crossentropy). If they're integer labels, switch to sparse_categorical_crossentropy instead.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 21:03:16