RuntimeError:使用模型之前,必须先对其进行编译

时间:2019-10-04 17:03:14

标签: python-3.x keras compiler-errors model resnet

我尝试运行此代码,但即使在编译模型后也出现此错误:

  

RuntimeError:您必须先编译模型,然后再使用它。

我该如何解决?

model = ResNet50(include_top=True, weights='imagenet')
model = Model(input=model.input,output=model.layers[-1].output) 
model.summary()
model = Sequential()
sgd = optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='binary_crossentropy', optimizer=SGD(lr=0.01, momentum=0.9), metrics=   ['binary_accuracy'])
data_dir = "C:\\Users\\"
batch_size = 32
from keras.applications.resnet50 import preprocess_input
from keras.preprocessing.image import ImageDataGenerator
image_size = IMAGE_RESIZE
def append_ext(fn):
return fn+".jpg"
from os import listdir
from os.path import isfile, join
dir_path = os.path.dirname(os.path.realpath(__file__))
train_dir_path = dir_path + '\data'
onlyfiles = [f for f in listdir(dir_path) if isfile(join(dir_path, f))]

NUM_CLASSES = 2

from tensorflow.python.keras.callbacks import EarlyStopping, ModelCheckpoint

cb_early_stopper = EarlyStopping(monitor = 'val_loss', patience = EARLY_STOP_PATIENCE)
cb_checkpointer = ModelCheckpoint(filepath = '../working/best.hdf5', monitor = 'val_loss',       save_best_only = True, mode = 'auto')

from sklearn.grid_search import ParameterGrid
param_grid = {'epochs': [5, 10, 15], 'steps_per_epoch' : [10, 20, 50]}

grid = ParameterGrid(param_grid)

for params in grid:
    print(params)
from keras.optimizers import SGD
learning_rate = 0.1
sgd = SGD(learning_rate)
model.compile(loss='binary_crossentropy',optimizer=sgd,metrics=['binary_accuracy'])

fit_history = model.fit_generator(
    train_generator,
    steps_per_epoch=STEPS_PER_EPOCH_TRAINING,
    epochs = NUM_EPOCHS,
    validation_data=validation_generator,
    validation_steps=STEPS_PER_EPOCH_VALIDATION,
    callbacks=[cb_checkpointer, cb_early_stopper])
model.load_weights("../working/best.hdf5")

1 个答案:

答案 0 :(得分:0)

您似乎正在尝试在Sequential APIFunctional API之间编写混合代码。

不要:)

请注意,您的行model = Sequential()初始化了一个新模型(使用顺序API)并将其放置在model中。

您的新模型没有体系结构且未遵循(此时分配给model的模型已消失)。