我正在尝试在pycharm中创建CNN。当我运行代码时,控制台输出
RuntimeError: You must compile your model before using it.
这是我的代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-o
from keras.models import Sequential
from keras.layers import Dense, MaxPool2D, Flatten, Conv2D, Dropout
from keras.preprocessing import image
from keras.optimizers import adadelta
generator = image.ImageDataGenerator(
rescale=1./255,
featurewise_center=False,
samplewise_center=False,
featurewise_std_normalization=False,
samplewise_std_normalization=False,
zca_whitening=False,
rotation_range=10,
width_shift_range=0.1,
height_shift_range=0.1,
horizontal_flip=True,
vertical_flip=False,
)
dateset = generator.flow_from_directory(
shuffle=True,
batch_size=100,
target_size=(80, 80),
directory='/Users/username/Documents/Project AI/Date set/blood-cells/dataset2-master/images/TRAIN')
def get_model():
model = Sequential()
model.add(Conv2D(80, (3, 3), strides=(1, 1), activation='relu'))
model.add(Conv2D(64, (3, 3), strides=(1, 1), activation='relu',
input_shape=(80, 80, 3)))
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3), strides=(1, 1), activation='relu'))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(4, activation='softmax'))
model.compile(optimizer=adadelta(lr=0.001),
loss='categorical_crossentropy', metrics=['accuracy'])
return model
nn = get_model()
nn.fit_generator(dateset, steps_per_epoch=None, epochs=30, verbose=1)
这是pycharm Python控制台的输出:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_umd.py", line 197, in runfile
pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/Users/username/Documents/Project AI/Src/CNN.py", line 43, in <module>
nn.fit_generator(dateset, steps_per_epoch=None, epochs=30, verbose=1)
File "/Users/username/Documents/Project AI/venv/lib/python3.7/site-packages/keras/legacy/interfaces.py", line 91, in wrapper
return func(*args, **kwargs)
File "/Users/username/Documents/Project AI/venv/lib/python3.7/site-packages/keras/engine/training.py", line 1418, in fit_generator
initial_epoch=initial_epoch)
File "/Users/username/Documents/Project AI/venv/lib/python3.7/sitepackages/keras/engine/training_generator.py", line 40, in fit_generator
model._make_train_function()
File "/Users/yangzichen/Documents/Project AI/venv/lib/python3.7/site-packages/keras/engine/training.py", line 496, in _make_train_function
raise RuntimeError('You must compile your model before using it.')
RuntimeError: You must compile your model before using it.
答案 0 :(得分:0)
类似您面临此已知错误的缝隙: https://github.com/tensorflow/tensorflow/issues/18287
另一种可能的解决方案是在第一层而不是第二层中定义input_shape