如何腌制干酪模型?

2024-06-16 08:55:20 发布

您现在位置:Python中文网/ 问答频道 /正文

官方文件指出,“不建议使用pickle或cPickle来保存Keras模型。”

然而,我对pickling Keras模型的需求源于使用sklearn的RandomizedSearchCV(或任何其他超参数优化器)的超参数优化。必须将结果保存到文件中,因为这样脚本就可以在分离的会话中远程执行

基本上,我想:

trial_search = RandomizedSearchCV( estimator=keras_model, ... )
pickle.dump( trial_search, open( "trial_search.pickle", "wb" ) )

Tags: 文件模型脚本search参数远程官方sklearn
3条回答

这就像一个符咒http://zachmoshe.com/2017/04/03/pickling-keras-models.html

import types
import tempfile
import keras.models

def make_keras_picklable():
    def __getstate__(self):
        model_str = ""
        with tempfile.NamedTemporaryFile(suffix='.hdf5', delete=True) as fd:
            keras.models.save_model(self, fd.name, overwrite=True)
            model_str = fd.read()
        d = { 'model_str': model_str }
        return d

    def __setstate__(self, state):
        with tempfile.NamedTemporaryFile(suffix='.hdf5', delete=True) as fd:
            fd.write(state['model_str'])
            fd.flush()
            model = keras.models.load_model(fd.name)
        self.__dict__ = model.__dict__


    cls = keras.models.Model
    cls.__getstate__ = __getstate__
    cls.__setstate__ = __setstate__

make_keras_picklable()

另外,我有一些问题,由于循环引用引起的model.to_json()问题,这个错误不知怎么被上面的代码所吞噬,从而导致pickle函数永远运行。

到目前为止,Keras模型是可以腌制的。但我们仍然建议使用model.save()将模型保存到磁盘。

使用“获取权重”和“设置权重”分别保存和加载模型。

看看这个链接:Unable to save DataFrame to HDF5 ("object header message is too large")

#for heavy model architectures, .h5 file is unsupported.
weigh= model.get_weights();    pklfile= "D:/modelweights.pkl"
try:
    fpkl= open(pklfile, 'wb')    #Python 3     
    pickle.dump(weigh, fpkl, protocol= pickle.HIGHEST_PROTOCOL)
    fpkl.close()
except:
    fpkl= open(pklfile, 'w')    #Python 2      
    pickle.dump(weigh, fpkl, protocol= pickle.HIGHEST_PROTOCOL)
    fpkl.close()

相关问题 更多 >