问题:使用python 3.8环境下的keras加载python 3.6环境保存的模型文件时,出现错误
ValueError: bad marshal data (unknown type code)
原因:marshal是internal python object serialization(Python内部对象序列化)模块,这是不同python环境文件交换产生的错误。
解决方案:使用相同Python版本加载模型,或者从源码构建模型,而不是从模型结构文件。
扩展:产生该类问题的可能解决方法总结如下
-
统一Python环境。例如,The
Model
might have been built and saved inPython 2.x
and you might be usingPython 3.x
. Solution is to use the samePython Version
using which theModel
has beenBuilt
andSaved
. -
使用相同的框架环境。Use the same version of
Keras
(and, may be,tensorflow
), on which your Model wasBuilt
andSaved
. -
指定自定义对象。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})
-
从源码构建模型,而不是从模型文件。If you can recreate the
architecture
(i.e. you have the original code used to generate it), you can instantiate themodel
from that code and then usemodel.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 originalarchitecture
.
参考:
python - tensorflow load data: bad marshal data - Stack Overflow