加载自己保存训练模型OSError: Unable to open file (unable to open file: name = ‘./model/LeNet_model‘, errno = 2

加载自定义模型出错

昨天,我在复现LeNet网络,训练都没有什么问题,我觉得可以保存模型,可就是在读取出现了错误。
保存:

model.save_weights('./model/LeNet_model')

生成文件:
在这里插入图片描述
读取:

model=load_model('./model/LeNet_model')

错误显示:

Traceback (most recent call last):
  File "D:/py_project/open_cv/LeNet.py", line 34, in 
    model=load_model('./model/LeNet_model')
  File "D:\py_project\venv\lib\site-packages\keras\engine\saving.py", line 492, in load_wrapper
    return load_function(*args, **kwargs)
  File "D:\py_project\venv\lib\site-packages\keras\engine\saving.py", line 583, in load_model
    with H5Dict(filepath, mode='r') as h5dict:
  File "D:\py_project\venv\lib\site-packages\keras\utils\io_utils.py", line 191, in __init__
    self.data = h5py.File(path, mode=mode)
  File "D:\py_project\venv\lib\site-packages\h5py\_hl\files.py", line 408, in __init__
    swmr=swmr)
  File "D:\py_project\venv\lib\site-packages\h5py\_hl\files.py", line 173, in make_fid
    fid = h5f.open(name, flags, fapl=fapl)
  File "h5py\_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
  File "h5py\_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
  File "h5py\h5f.pyx", line 88, in h5py.h5f.open
OSError: Unable to open file (unable to open file: name = './model/LeNet_model', errno = 2, error message = 'No such file or directory', flags = 0, o_flags = 0)

说得就是文件没有找到,于是我换了一种方法
使用了tf.saved.model

tf.saved.model.save(model,'LeNet_model')#保存模型
model=tf.saved_model.load('LeNet_model')#加载模型
sparse_categorical_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()
y_pred=model(test_data)
sparse_categorical_accuracy.update_state(y_true=test_labels,y_pred=y_pred)
print('The test of accuracy:',sparse_categorical_accuracy.result().numpy())

结果:
在这里插入图片描述

注意
model没有evaluate方法,我用了tf.keras.metrics.SparseCategoricalAccuracy(),对了,我这里构建模型是用Sequential(),如果是用使用继承 tf.keras.Model 类建立构建的是获取相应的预测值有差别的,如下:

y_pred=model(test_data)#用Sequential构建
y_pred=model.cell(test_data)#使用继承 tf.keras.Model 类

你可能感兴趣的:(深度学习,tensorflow)