Keras:尽管使用了compile(),但“必须在使用模型之前先对其进行编译”

时间:2018-08-10 18:20:51

标签: python tensorflow keras runtime-error sequential

我想在Keras中创建和训练CNN模型以对钞票进行分类。创建模型仅需简单的教程,但不能与我从本paper中采用的体系结构一起使用。 Keras输出:调用RuntimeError('You must compile your model before using it.')之后的fit_generator()

如果合适的话,我会使用tensorflow后端。


模型在model.py中定义:

from keras.layers import ...
model = Sequential() 
model.add(some_layer)

... #according to the paper

model.add(some_layer)
model.add(Dense(#output_classes, activation='softmax') #last layer

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

然后从model中使用start_train.py

from model import model as m

#some ImageGenerator stuff as input

m.fit_generator( #training on train_data
        train_pics,
        steps_per_epoch=#steps,
        epochs=#epochs,
        validation_data=test_pics,

据我所知,在Keras中的过程如下:

  1. 定义模型
  2. 编译模型
  3. (如果希望在编译后现在可以使用评估()和summary())
  4. 健身模式
  5. 评估模型。

我测试了在调用model.py之前是否访问了fit_generator(),它是否正常工作。我没有主意,想知道我在做错什么,特别是因为相同的设置可以在基本模型/体系结构中很好地工作。

我们非常感谢您的帮助! :)

4 个答案:

答案 0 :(得分:3)

发现我的错误-解释以供将来参考。

错误在compile()中重新出现,其中第一个if语句显示:

if not self.built:
    # Model is not compilable because
    # it does not know its number of inputs
    # and outputs, nor their shapes and names.
    # We will compile after the first
    # time the model gets called on training data.
return

因此,我在第一input_shape=层中指定了input_format=Conv2D,一切正常。

答案 1 :(得分:1)

如果有人最终得到相同的错误代码,那么这里可能是一种解决方法。因此,我使用了一个生成器,即使一切都很好,也遇到了“必须编译”错误。我能够通过在启动fit_generator之前对一个批处理执行model.fit(x,y)来修复它,然后一切正常。我不知道这对您有帮助吗?

答案 2 :(得分:0)

您可以在一个很小的集合上运行评估,这将解决该问题。

答案 3 :(得分:-1)

尝试一下:

from keras.optimizers import Adam
opt = keras.optimizers.Adam(use your own learning rate)
model.compile(optimizer=opt, loss="categorical_crossentropy", metrics=model.compile(optimizer=opt, loss="categorical_crossentropy", metrics=['accuracy']))