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

Jul*_*opp 3 python runtime-error sequential keras tensorflow

我想在Keras中创建和训练CNN模型以对钞票进行分类。使用简单的教程创建模型可以很好地工作,但不适用于本文采用的体系结构。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'])
Run Code Online (Sandbox Code Playgroud)

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,
Run Code Online (Sandbox Code Playgroud)

据我了解,在Keras中的过程如下:

  1. 定义模型
  2. 编译模型
  3. (如果需要,在编译后现在可以使用validate()和summary())
  4. 拟合模型
  5. 评估模型。

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

任何帮助深表感谢!:)

Jul*_*opp 8

发现我的错误-说明以供将来参考。

该错误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
Run Code Online (Sandbox Code Playgroud)

因此,我在第一层进行了指定input_shape=,并且一切正常。input_format=Conv2D


小智 5

如果有人最终遇到相同的错误代码,这里可能是一种解决方法。所以我使用了一个生成器,即使一切都很好,但还是收到了“必须编译”的错误。在启动我的 fit_generator 之前,我能够通过在单个批次上执行 model.fit(x,y) 来修复它,之后一切正常。我不知道这是否对任何人有帮助,但是是的!