【问题标题】:Model-building function in Keras Tuner did not return a valid Keras Model instanceKeras Tuner 中的模型构建函数未返回有效的 Keras 模型实例
【发布时间】:2020-05-31 22:21:35
【问题描述】:

我正在尝试在一个程序中按照 Krish naik Youtube 教程学习 CNN,但出现此错误:

RuntimeError: Model-building function did not return a valid Keras Model instance, found <keras.engine.sequential.Sequential object at 0x7fd882393b38>

我的代码如下

import keras.datasets
fashion=keras.datasets.fashion_mnist
(x_train,y_train),(x_test,y_test)=fashion.load_data()

x_train=x_train/255.00
x_test=x_test/255.00
x_train=x_train.reshape(x_train.shape[0],x_train.shape[1],x_train.shape[2],1)
x_test=x_test.reshape(x_test.shape[0],x_test.shape[1],x_test.shape[2],1)
from keras.models import Sequential
from keras.layers import Conv2D,Flatten,Dropout,Dense
from keras.optimizers import Adam
def build_knn(hp):
    models=Sequential()
    models.add(Conv2D(filters=hp.Int('conv2d_1',min_value=32,max_value=128,step=16),
                      kernel_size=hp.Choice('conv1_kernal',values=[3,5]),
                      activation='relu',
                      input_shape=(28,28,1)
                                    ))
    models.add(Conv2D(filters=hp.Int('conv2d_1',min_value=32,max_value=128,step=16),
                      kernel_size=hp.Choice('conv1_kernal',values=[3,5]),
                      activation='relu'
                                    ))
    models.add(Flatten())
    models.add(Dense(hp.Int('neural1',min_value=32,max_value=128,step=16),activation='relu'))
    models.add(Dense(10,activation='softmax'))
    models.compile(optimizer=Adam(hp.Choice('learning_rate',values=[1e-2,1e-3])),
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy']
                 )
    return models
from kerastuner import RandomSearch
from kerastuner.engine.hyperparameters import HyperParameters
tuner_search=RandomSearch(build_knn,objective='val_accuracy',max_trials=5,directory='jupyterfiles',project_name='krish_naik_fashion_mnist')

【问题讨论】:

    标签: python machine-learning keras deep-learning keras-tuner


    【解决方案1】:

    project site 中不是非常清楚,但确实提到 Keras Tuner 是(强调添加):

    Keras 的超参数调节器,特别是用于 TensorFlow 2.0 的 tf.keras

    换句话说,它适用于tf.keras,但不适用于您似乎在这里使用的独立版本的 Keras。

    确实,改编了上面链接的项目站点的基本示例,但将导入更改为使用独立的 Keras,会复制您报告的错误:

    !pip install -U keras-tuner
    
    import keras
    from keras import layers
    from kerastuner.tuners import RandomSearch
    
    def build_model(hp):
        model = keras.Sequential()
        model.add(layers.Dense(units=hp.Int('units',
                                            min_value=32,
                                            max_value=512,
                                            step=32),
                               activation='relu'))
        model.add(layers.Dense(10, activation='softmax'))
        model.compile(
            optimizer=keras.optimizers.Adam(
                hp.Choice('learning_rate',
                          values=[1e-2, 1e-3, 1e-4])),
            loss='sparse_categorical_crossentropy',
            metrics=['accuracy'])
        return model
    
    tuner = RandomSearch(
        build_model,
        objective='val_accuracy',
        max_trials=5,
        executions_per_trial=3,
        directory='my_dir',
        project_name='helloworld')
    

    结果:

    RuntimeError: Model-building function did not return a valid Keras Model instance, found <keras.engine.sequential.Sequential object at 0x7fd882393b38>
    

    但只需将导入更改为使用tf.keras,即:

    from tensorflow import keras
    from tensorflow.keras import layers
    from kerastuner.tuners import RandomSearch
    

    上面的代码运行正常,没有错误。

    因此,您应该将此处显示的导入更改为:

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

    你应该没问题(当然前提是你确实使用了 Tensorflow 2.0)。

    我刚刚打开了一个相关的Github issue,建议他们在可见位置明确包含此说明。

    【讨论】:

    • 感谢您的宝贵回复,我会尝试这种方式
    • @pysaundary 如果答案解决了您的问题,非常欢迎您接受它 - 请参阅What should I do when someone answers my question?
    • youtube.com/… 我按照该教程进行操作,他使用了您建议我的相同格式,但我认为我也可以通过上述方式做到这一点,但它不起作用
    • @pysaundary 所以,你在这里问了一个问题,你得到的答案既解释了又证明了为什么它不起作用,你觉得这很有帮助,但仍然拒绝接受,正如 What should I do when someone answers my question? 中所建议的那样.正如我所说,不欣赏,也不知道 SO 是如何工作的。
    猜你喜欢
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 2018-08-10
    相关资源
    最近更新 更多