【问题标题】:Keras Tuner - Model-building function did not return a valid Keras Model instanceKeras Tuner - 模型构建函数未返回有效的 Keras 模型实例
【发布时间】:2021-09-11 16:37:36
【问题描述】:

我正在尝试使用 Keras Tuner 在超参数中搜索模型,但在运行代码时出现此错误:“RuntimeError: Model-building function does not return a valid Keras Model instance, found "

我在互联网上搜索过,但没有找到任何有用的东西,我也按照 Keras Tuner gitHub 页面 (https://github.com/keras-team/keras-tuner) 中的教程进行操作,但也没有用。

这是我的代码:

class MyHyperModel(HyperModel):

    def __init__(self, num_classes):
        self.num_classes = num_classes

    def build(self, hp):
        model=Sequential()
        model.add(Dense(units=hp.Int('units_0', 30, 900, step=30),
                        activation=hp.Choice('act_0', ['relu', 'tanh']),
                        input_dim=12))
        for i in range(hp.Int('layers', 3, 9)):
            model.add(Dense(units=hp.Int('units_' + str(i), 30, 900, step=30),
                            activation=hp.Choice('act_' + str(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


hypermodel = MyHyperModel(num_classes=6)

tuner = kt.tuners.bayesian.BayesianOptimization(
    hypermodel,
    objective='val_accuracy',
    max_trials=5,
    executions_per_trial=3,
    seed=(np.random.seed(1)),
    directory='Tests',
    project_name='test')

tuner.search_space_summary()

tuner.search(data[:200], labels[:200],
             verbose=2,
             epochs=3,
             validation_data=(data[200:], labels[200:]))

models = tuner.get_best_models(num_models=2).summary()
tuner.get_best_hyperparameters()[0].values
tuner.results_summary()

数据是一个包含 300 个向量的列表,包含 12 个值,标签上有 6 个类,这些类通过函数 tensorflow.convert_to_tensor() 转换为张量。

感谢您的帮助。

【问题讨论】:

    标签: python tensorflow keras


    【解决方案1】:

    如果从keras 导入模块成员,则必须从tensorflow.keras 导入而不是keras。例如,如果你写:

    from keras.models import Sequential
    from keras.layers import Dense, Activation, Dropout
    from keras.optimizers import Adam
    

    然后将它们更改为:

    from tensorflow.keras.models import Sequential
    from tensorflow.keras.layers import Dense, Activation, Dropout
    from tensorflow.keras.optimizers import Adam
    

    【讨论】:

      【解决方案2】:

      我知道出了什么问题,不是代码,我的模型在最后一层有 6 个神经元,我将损失用作“categorical_crossentropy”,但这仅在标签为 0 和 1 时有效,所以我已经将损失更改为“sparse_categorical_crossentropy”,将指标更改为“准确度”,它起作用了。 谢谢大家的回复,感谢大家的帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-25
        • 1970-01-01
        • 2019-11-24
        • 1970-01-01
        • 1970-01-01
        • 2018-12-14
        • 1970-01-01
        • 2021-03-02
        相关资源
        最近更新 更多