ValueError
代码部分如下
# 训练模型
early_stopping = EarlyStopping(monitor='val_loss',patience=100) # 早停,500轮
checkpoint = ModelCheckpoint("./best_model2.hdf5",
monitor='val_loss',
save_weights_only=True,
verbose=1,
save_best_only=True,
period=1) # 保存最佳模型参数
model.fit(train_data_x, train_data_y, epochs=10000, batch_size=128, validation_split=0.2, callbacks=[early_stopping,checkpoint])
# 保存模型
model.save('./model_5w_1day.h5')
model = load_model('best_model2.hdf5')
scores= model.evaluate(test_data_x, test_data_y, verbose=0)
print("%s: %f" % (model.metrics_names[1], scores[1])) # 模型性能:1是loss,2是mse,3是acc
然后报错,提示不能加载只读模型
ValueError Traceback (most recent call last)
<ipython-input-31-04beb895ff41> in <module>()
1 # 评估模型
----> 2 model = load_model('best_model2.hdf5')
3 scores= model.evaluate(test_data_x, test_data_y, verbose=0)
4 print("%s: %f" % (model.metrics_names[1], scores[1])) # 模型性能:0是loss,1是mse,2是acc
5 pred_y = model.predict(test_data_x)
D:\Anaconda3\lib\site-packages\keras\engine\saving.py in load_model(filepath, custom_objects, compile)
417 f = h5dict(filepath, 'r')
418 try:
--> 419 model = _deserialize_model(f, custom_objects, compile)
420 finally:
421 if opened_new_file:
D:\Anaconda3\lib\site-packages\keras\engine\saving.py in _deserialize_model(f, custom_objects, compile)
219 return obj
220
--> 221 model_config = f['model_config']
222 if model_config is None:
223 raise ValueError('No model found in config.')
D:\Anaconda3\lib\site-packages\keras\utils\io_utils.py in __getitem__(self, attr)
300 else:
301 if self.read_only:
--> 302 raise ValueError('Cannot create group in read only mode.')
303 val = H5Dict(self.data.create_group(attr))
304 return val
ValueError: Cannot create group in read only mode.
最后找到原因:checkpoint保存模型时只保存了参数,而不是完整模型
checkpoint = ModelCheckpoint("./best_model2.hdf5",
monitor='val_loss',
save_weights_only=True, # 只保存了模型参数,并不是完整模型
verbose=1,
save_best_only=True,
period=1) # 保存最佳模型参数
修改成如下代码就正常了
checkpoint = ModelCheckpoint("./best_model2.hdf5",
monitor='val_loss',
save_weights_only=False,
verbose=1,
save_best_only=True,
period=1) # 保存最佳模型参数