Python 如何腌制Keras模型?

Python 如何腌制Keras模型?,python,machine-learning,keras,pickle,Python,Machine Learning,Keras,Pickle,官方文件指出,“不建议使用pickle或cPickle保存Keras模型。” 然而,我对pickle-Keras模型的需求源于使用sklearn的RandomizedSearchCV(或任何其他超参数优化器)的超参数优化。必须将结果保存到文件中,因为这样可以在分离的会话等中远程执行脚本 基本上,我想: trial_search = RandomizedSearchCV( estimator=keras_model, ... ) pickle.dump( trial_search, open( "

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

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

基本上,我想:

trial_search = RandomizedSearchCV( estimator=keras_model, ... )
pickle.dump( trial_search, open( "trial_search.pickle", "wb" ) )
这就像一个符咒:


另外,由于我的
模型,我遇到了一些问题。由于循环引用,to_json()
引发了
TypeError('Not json Serializable:',obj)
,并且这个错误不知怎的被上面的代码吞没了,因此导致pickle函数永远运行

您可以使用可通过pip安装的deploy ml模块对Keras神经网络进行Pickle

pip install deploy-ml
使用deploy ml包装器对kera神经网络进行全面培训和部署,如下所示:

import pandas as pd
from deployml.keras import NeuralNetworkBase


# load data 
train = pd.read_csv('example_data.csv')

# define the moel 
NN = NeuralNetworkBase(hidden_layers = (7, 3),
                   first_layer=len(train.keys())-1, 
                   n_classes=len(train.keys())-1)

# define data for the model 
NN.data = train

# define the column in the data you're trying to predict
NN.outcome_pointer = 'paid'

# train the model, scale means that it's using a standard 
# scaler to scale the data
NN.train(scale=True, batch_size=100)

NN.show_learning_curve()

# display the recall and precision 
NN.evaluate_outcome()

# Pickle your model
NN.deploy_model(description='Keras NN',
            author="maxwell flitton", organisation='example',
            file_name='neural.sav')
pickle文件包含模型、测试中的度量、变量名列表及其输入顺序、使用的Keras和python版本,如果使用了scaler,它也将存储在文件中。文件是。通过以下方式加载和使用文件:

import pickle

# use pickle to load the model 
loaded_model = pickle.load(open("neural.sav", 'rb'))

# use the scaler to scale your data you want to input 
input_data = loaded_model['scaler'].transform([[1, 28, 0, 1, 30]])

# get the prediction 
loaded_model['model'].predict(input_data)[0][0]
我理解培训可能有点限制。Deploy ml支持为Sk learn导入您自己的模型,但它仍在为Keras提供这种支持。但是,我发现您可以创建一个deploy ml NeuralNetworkBase对象,在deploy ml之外定义自己的Keras神经网络,并将其分配给deploy ml model属性,这样就可以了:

 NN = NeuralNetworkBase(hidden_layers = (7, 3),
               first_layer=len(train.keys())-1, 
               n_classes=len(train.keys())-1)

NN.model = neural_network_you_defined_yourself

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

使用get\u weights和set\u weights分别保存和加载模型。 请查看此链接:


这个问题也适用于其他深度学习框架,如Tensorflow等。Keras建议使用。希基特。使用RandomizedSearchCV调整参数后,您只需使用
试用搜索。最佳估计值
获得最佳拟合模型,然后使用keras推荐的方法。你为什么要保存RandomizedSearchCV对象?因为你想保存搜索历史以及所有细节,例如,我想知道第二个最佳结果是什么样子,以及它使用了哪些参数。然后,不是完整的RandomizedSearchCV,您应该寻找保存
cv\u results\u
属性,该属性将是一个包含您需要的所有信息的dict。根据定义,如果不保存整个对象,您将丢失信息。例如,在以后的某个日期,我突然想比较第三个最佳模型和第五个最佳模型的权重。现在,我必须重新运行这些模型,而不是
pickle.load()
。难道我不能吗?另外,我不想被附加到
sklearn
,因为我想在以后使用其他hyperparam优化器。我在keras常见问题解答中看到了这一建议,但我想知道为什么
model.save()
比pickle更受欢迎,你能在回答中澄清这一点吗?使用model.save()保存的模型将与Keras的未来版本兼容,也可以导出到其他平台和实现(deeplearning4j、Apple CoreML等)。model.save()与python3有缺陷。每次我加载模型时,它都会为相同的输入预测不同的内容。
 NN = NeuralNetworkBase(hidden_layers = (7, 3),
               first_layer=len(train.keys())-1, 
               n_classes=len(train.keys())-1)

NN.model = neural_network_you_defined_yourself
#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()