keras加载模型错误:“bad marshal data“

问题:使用python 3.8环境下的keras加载python 3.6环境保存的模型文件时,出现错误

ValueError: bad marshal data (unknown type code)

原因:marshal是internal python object serialization(Python内部对象序列化)模块,这是不同python环境文件交换产生的错误。

解决方案:使用相同Python版本加载模型,或者从源码构建模型,而不是从模型结构文件。

扩展:产生该类问题的可能解决方法总结如下

  1. 统一Python环境。例如,The Model might have been built and saved in Python 2.x and you might be using Python 3.x. Solution is to use the same Python Version using which the Model has been Built and Saved.

  2. 使用相同的框架环境。Use the same version of Keras (and, may be, tensorflow), on which your Model was Built and Saved.

  3. 指定自定义对象。The Saved Model might contain Custom Objects. If so, you need to load the Model using the code,

    new_model = tf.keras.models.load_model('model.h5', custom_objects={'CustomLayer': CustomLayer})

  4. 从源码构建模型,而不是从模型文件。If you can recreate the architecture (i.e. you have the original code used to generate it), you can instantiate the model from that code and then use model.load_weights('your_model_file.hdf5') to load in the weights. This isn't an option if you don't have the code used to create the original architecture.

参考:

python - tensorflow load data: bad marshal data - Stack Overflow

"bad marshal data" when loading model that was saved with python 2.7 into python 3.4. · Issue #7440 · keras-team/keras (github.com)

你可能感兴趣的:(泛coding,AI/ML/DL,keras,python,pycharm)