如何将包含Keras回归器的scikit-learn管道保存到磁盘?

我有一个包含Keras回归器的scikit-learn管道:

estimators = [    ('standardize', StandardScaler()),    ('mlp', KerasRegressor(build_fn=baseline_model, nb_epoch=5, batch_size=1000, verbose=1))    ]pipeline = Pipeline(estimators)

在训练管道后,我尝试使用joblib将其保存到磁盘…

joblib.dump(pipeline, filename , compress=9)

但我遇到了一个错误:

RuntimeError: 超过了最大递归深度

你会如何将管道保存到磁盘?


回答:

我遇到了同样的问题,因为没有直接的方法可以做到这一点。这里有一个对我有用的技巧。我将管道保存到了两个文件中。第一个文件存储了sklearn管道的pickle对象,第二个文件用于存储Keras模型:

...from keras.models import load_modelfrom sklearn.externals import joblib...pipeline = Pipeline([    ('scaler', StandardScaler()),    ('estimator', KerasRegressor(build_model))])pipeline.fit(X_train, y_train)# 首先保存Keras模型:pipeline.named_steps['estimator'].model.save('keras_model.h5')# 这个技巧允许我们保存sklearn管道:pipeline.named_steps['estimator'].model = None# 最后,保存管道:joblib.dump(pipeline, 'sklearn_pipeline.pkl')del pipeline

以下是如何重新加载模型的方法:

# 首先加载管道:pipeline = joblib.load('sklearn_pipeline.pkl')# 然后,加载Keras模型:pipeline.named_steps['estimator'].model = load_model('keras_model.h5')y_pred = pipeline.predict(X_test)

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注