Keras:“使用之前必须编译模型"尽管使用了compile() [英] Keras: "must compile model before using it" despite compile() is used

查看:490
本文介绍了Keras:“使用之前必须编译模型"尽管使用了compile()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Keras中创建和训练CNN模型以对钞票进行分类.创建模型只能通过简单的教程很好地完成,但不能与我从此纸张. Keras输出:调用fit_generator()后的RuntimeError('You must compile your model before using it.').

I want to create and train a CNN model in Keras for classification of banknotes. Creating models works fine with simple tutorials but not with the architecture I adopt from this paper. Keras outputs: RuntimeError('You must compile your model before using it.') after fit_generator() is called.

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

I use the tensorflow backend if that is of relevance.

模型在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的流程如下:

As far as I understood it the process in Keras is as follows:

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

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

I tested if model.py is accessed before calling fit_generator() and it works properly. I'm out of ideas and wondering what I'm doing wrong especially since the same set-up works fine with a basic model/architecture.

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

Any help is highly appreciated! :)

推荐答案

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

Found my mistake - explanation for future reference.

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

The Error origniates back in compile() where the first if-statement says:

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=,并且一切正常.

So I specified input_shape= and input_format=in the first Conv2D layer and everything works fine.

这篇关于Keras:“使用之前必须编译模型"尽管使用了compile()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆