3

I built a simple lenet model:

def get_lenet():
    kernel_size = (5, 5)
    model = Sequential()  # each image is 28x28
    model.add(Conv2D(32, kernel_size, activation='relu'))  # now 24x24
    model.add(MaxPool2D())  # 12x12
    model.add(Conv2D(64, kernel_size, activation='relu'))  # 8x8
    model.add(MaxPool2D())  # 4x4
    model.add(Flatten())
    model.add(Dense(128, activation='relu'))
    model.add(Dense(10, activation='softmax'))
    return model

Compiling and training all go well, then I save the model:

model.save_weights('w.h5')
with open('model_architecture.json', 'w') as f:
    f.write(model.to_json())

Later, when trying to load

with open('model_architecture.json', 'r') as f:
    model = model_from_json(f.read())
model.load_weights('w.h5)

I get the following error:

ValueError: You are trying to load a weight file containing 4 layers into a model with 0 layers.

The same error arrises when using save_model. Does anyone have an idea?

  • did you try doing what was done in this SO Post's Answer https://stackoverflow.com/questions/45393429/keras-how-to-save-model-and-continue-training – rawwar Jun 15 '18 at 17:26
  • I have just encountered the same problem and solved it by declaring input dimensions of layers explicitly. I could not run your code, because I could not import Conv2D. However, you can try it by modifying your layers such as: model.add(Dense(10, activation=‘softmax’, input_dim=128)). Hope it will work for you, too. – simon_tulia Aug 06 '18 at 07:25

0 Answers0