Simple Sequential model error : You must compile your model before using it

Simple Sequential model error : You must compile your model before using it

This error seems to go if i remove the Flatten() layer.

我正在尝试使用我的模型,但它给出了这个运行时错误: 使用前必须先编译模型。

我不明白哪里出了问题,我试过使用较少的 Dense 层,但它不起作用。

有人可以帮我解决这个问题吗? PLZ用代码解释一下。

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



train_directory = 'D:\D_data\Rock_Paper_Scissors\Train'
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_data\Rock_Paper_Scissors\Test'
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:\Users\Ankit\.spyder-py3\temp.py", line 33, in <module>
model.fit_generator(training_generator,epochs = 15,validation_data = validation_generator,verbose =1)

File "C:\Users\Ankit\anaconda3\lib\site-packages\keras\legacy\interfaces.py", line 91, in wrapper
return func(*args, **kwargs)

File "C:\Users\Ankit\anaconda3\lib\site-packages\keras\engine\training.py", line 1732, in fit_generator
initial_epoch=initial_epoch)

File "C:\Users\Ankit\anaconda3\lib\site-packages\keras\engine\training_generator.py", line 42, in fit_generator
model._make_train_function()

File "C:\Users\Ankit\anaconda3\lib\site-packages\keras\engine\training.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 层。