保存和加载Keras始终具有0层错误模型

时间:2019-06-07 04:13:45

标签: python tensorflow keras

我正在使用Keras Sequential训练模型,并尝试保存然后再次加载以预测结果。但是我总是得到0层错误模型。有我的代码:

我的模特:

model = Sequential()
model.add(InputLayer(input_shape=[64, 64, 1]))
model.add(Conv2D(filters=32, kernel_size=5, strides=1, padding='same',
                 activation='relu'))
model.add(MaxPool2D(pool_size=5, padding='same'))

model.add(Conv2D(filters=50, kernel_size=5, strides=1, padding='same',
                 activation='relu'))
model.add(MaxPool2D(pool_size=5, padding='same'))

model.add(Conv2D(filters=80, kernel_size=5, strides=1, padding='same',
                 activation='relu'))
model.add(MaxPool2D(pool_size=5, padding='same'))

model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dropout(rate=0.5))
model.add(Dense(5, activation='softmax'))
optimizer = Adam(lr=1e-3)

model.compile(optimizer=optimizer, loss='categorical_crossentropy',
              metrics=['accuracy'])
model.fit(x=tr_img_data, y=tr_lbl_data, epochs=50, batch_size=100)
model.summary()
  1. 使用模型重量保存:
model_json = model.to_json()
with open("model.json", "w") as json_file:
    json_file.write(model_json)

model.save_weights("model.h5")

加载:

def loadModel(jsonStr, weightStr):
    json_file = open(jsonStr, 'r')
    loaded_nnet = json_file.read()
    json_file.close()

    serve_model = tf.keras.models.model_from_json(loaded_nnet)
    serve_model.load_weights(weightStr)

    optimizer = Adam(lr=1e-3)

    serve_model.compile(optimizer=optimizer, loss='categorical_crossentropy',
              metrics=['accuracy'])
    return serve_model

model = loadModel('model.json', 'model.h5')
  1. 尝试保存所有H5型号
model.save('model.h5')

#load model
load_model = load_model('model.h5')

总会出现错误: ValueError:您正在尝试将包含5层的权重文件加载到0层的模型中

0 个答案:

没有答案