SpEm1822
SpEm1822

Reputation: 51

RuntimeError: You must compile your model before using it

I try to run this code but I have this error, even after compiling my model:

RuntimeError: You must compile your model before using it.

How can I fix this?

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")

Upvotes: 0

Views: 372

Answers (1)

Lafayette
Lafayette

Reputation: 618

It looks like you are trying to write a hybrid between Sequential API and Functional API.

Don't :)

Be advised that your line model = Sequential() initializes a new model (using the Sequential API) and places it in model.

Your new model has no architecture and is not complied (the model you assigned to model is gone by this point).

Upvotes: 0

Related Questions