Keras:"即使使用了compile(),在使用模型之前必须编译模型"

7
我希望您使用Keras创建和训练一个卷积神经网络模型,用于对纸币进行分类。使用简单的教程可以很好地创建模型,但使用我从这篇论文中采用的结构时出现了问题。在调用fit_generator()后,Keras输出:RuntimeError('You must compile your model before using it.')
如果您使用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'])

start_train.py开始使用model

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. (如果需要,在编译后可以使用 evaluate() 和 summary() 进行评估)
  4. 拟合模型
  5. 评估模型。
我测试了一下在调用 fit_generator() 之前是否可以访问 model.py,结果正常。我不知道自己做错了什么,尤其是因为相同的设置对于基本模型/架构而言运行良好。
非常感谢您提供的任何帮助! :)

如果您在start_train.py脚本中运行model.compile(),它是否无法正常工作? - sdcbr
不,同样的错误。 - very_interesting
4个回答

12

发现了我的错误——为以后参考做出解释。

错误源于 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

所以我在第一个Conv2D层中指定了input_shape=input_format=,一切都正常运作。


只是为了添加一个具体的例子。要消除错误,需要在第一个conv2d层中添加input_shape。 新模型 = Sequential() new_model.add(Conv2D(32,(3,3),activation='relu',padding='same',input_shape=(32,32,3))) - Tanmay Patil

6
如果有人遇到相同的错误代码,这里也许有一种解决方法。我正在使用生成器时,尽管一切正常,但仍然出现了“必须编译”的错误。在启动fit_generator之前,我通过对单个批次进行model.fit(x,y)来修复它,然后一切正常运行。我不知道这是否能帮助任何人,但是就是这样!

我也曾经因为使用生成器(就像你一样)而遇到了同样的问题,你的解决方法真是太棒了。顺便说一句,希望他们在下一个版本中修复这个问题。 - talha06

0

你可以在一个小数据集上运行评估,那样就可以解决它了。


-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']))

你的代码不能直接运行,解释你的解决方案为什么可行会是受欢迎的。 - Astariul

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接