如何加载现有的 Keras 模型?

问题描述 投票:0回答:1

我一直在尝试从这里加载 Keras 模型:https://github.com/gitshanks/fer2013(包括 .json 和 .h5),以便在潜水前用现有的面部识别模型测试我的部分代码在训练一。我已经搜索了不同的方法来做到这一点,但我无法加载它。我想知道它是否与模型保存和加载时不同版本的 Keras 有关。

我尝试了在谷歌和这里找到的两种不同的东西,但我无法加载它。

from tensorflow.keras.models import model_from_json
json_file = open('fer.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
# load weights into new model
loaded_model.load_weights("fer.h5")
print("Loaded model from disk")


错误:



raceback (most recent call last):

  Cell In[31], line 6
    loaded_model = model_from_json(loaded_model_json)

  File ~\AppData\Roaming\Python\Python38\site-packages\keras\saving\legacy\model_config.py:109 in model_from_json
    return deserialize_from_json(json_string, custom_objects=custom_objects)

  File ~\AppData\Roaming\Python\Python38\site-packages\keras\layers\serialization.py:270 in deserialize_from_json
    config = json_utils.decode_and_deserialize(

  File ~\AppData\Roaming\Python\Python38\site-packages\keras\saving\legacy\saved_model\json_utils.py:78 in decode_and_deserialize
    return json.loads(

  File ~\anaconda3\lib\json\__init__.py:370 in loads
    return cls(**kw).decode(s)

  File ~\anaconda3\lib\json\decoder.py:337 in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())

  File ~\anaconda3\lib\json\decoder.py:355 in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None

JSONDecodeError: Expecting value
from tensorflow.keras.models import load_model
new_model = load_model('fer.h5')
new_model.summary()

最后一个成功加载了我之前创建并使用 model.save() 保存的模型。

错误:

Traceback (most recent call last):

  Cell In[32], line 2
    new_model = load_model('fer.h5')

  File ~\AppData\Roaming\Python\Python38\site-packages\keras\utils\traceback_utils.py:70 in error_handler
    raise e.with_traceback(filtered_tb) from None

  File ~\AppData\Roaming\Python\Python38\site-packages\h5py\_hl\files.py:567 in __init__
    fid = make_fid(name, mode, userblock_size, fapl, fcpl, swmr=swmr)

  File ~\AppData\Roaming\Python\Python38\site-packages\h5py\_hl\files.py:231 in make_fid
    fid = h5f.open(name, flags, fapl=fapl)

  File h5py\_objects.pyx:54 in h5py._objects.with_phil.wrapper

  File h5py\_objects.pyx:55 in h5py._objects.with_phil.wrapper

  File h5py\h5f.pyx:106 in h5py.h5f.open

OSError: Unable to open file (file signature not found)

tensorflow keras deep-learning
1个回答
0
投票

你提供的代码对我有用,我也可以使用

loaded_model.summary()
看到模型。在您的情况下,模型很可能保存在当前工作目录以外的目录中。因此 Traceback 以
JSONDecodeError: Expecting value
OSError: Unable to open file (file signature not found)
响应。

可能的解决方法包括在您的

json_file = open('fer.json', 'r')
中包含整个路径,例如:
json_file = open('/home/dev/Downloads/fer.json', 'r')
.

否则,您可以使用以下方法检查当前目录:

import os
print(os.getcwd())

并将下载的模型复制到当前工作目录。

稍后您可以使用

loaded_model.summary()
查看您的网络架构。

© www.soinside.com 2019 - 2024. All rights reserved.