简单顺序模型错误:在使用模型之前必须编译模型



如果我移除Flatten((层,这个错误似乎会发生。

我正在尝试使用我的模型,但它给出了以下运行时错误:你必须先编译你的模型,然后再使用它。

我不明白出了什么问题,我试过使用密度较小的层,但它不起作用。

有人能帮我吗?PLZ用代码解释。

from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Flatten

train_directory = 'D:D_dataRock_Paper_ScissorsTrain'
training_datgagen = ImageDataGenerator(rescale = 1./255)
training_generator = training_datgagen.flow_from_directory(
train_directory,
target_size = (150,150),
class_mode = 'categorical')
validation_directory = 'D:D_dataRock_Paper_ScissorsTest'
validation_datagen = ImageDataGenerator(rescale= 1./255)
validation_generator = validation_datagen.flow_from_directory(
validation_directory,
target_size = (150,150),
class_mode = 'categorical'
)
model = Sequential()
model.add(Flatten())
model.add(Dense(128, input_shape = (22500,)))
model.add(Dense(64, activation = 'relu'))
model.add(Dense(32, activation = 'relu'))
model.add(Dense(16, activation = 'relu'))
model.add(Dense(3, activation = 'softmax'))
model.compile(optimizer = 'adam', loss = 'categorical_crossentropy',metrics = ['accuracy'])

model.fit_generator(training_generator,epochs = 15,validation_data = validation_generator,verbose =1)

错误:

File "C:UsersAnkit.spyder-py3temp.py", line 33, in <module>
model.fit_generator(training_generator,epochs = 15,validation_data = validation_generator,verbose =1)
File "C:UsersAnkitanaconda3libsite-packageskeraslegacyinterfaces.py", line 91, in wrapper
return func(*args, **kwargs)
File "C:UsersAnkitanaconda3libsite-packageskerasenginetraining.py", line 1732, in fit_generator
initial_epoch=initial_epoch)
File "C:UsersAnkitanaconda3libsite-packageskerasenginetraining_generator.py", line 42, in fit_generator
model._make_train_function()
File "C:UsersAnkitanaconda3libsite-packageskerasenginetraining.py", line 303, in _make_train_function
raise RuntimeError('You must compile your model before using it.')
RuntimeError: You must compile your model before using it.

发生此错误是因为您的网络不一致,input_shape参数应该提供给网络中的第一层,但您将其提供给了第二层。

解决方案很简单,将正确的input_shape放在Flatten层中。

相关内容

  • 没有找到相关文章

最新更新