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

21

我有一个包含kerasRegressor的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: maximum recursion depth exceeded

您如何将管道保存到磁盘上?


你可以看一下 dill。也许它能够解决问题。https://pypi.python.org/pypi/dill - Moritz
你只需要增加最大递归深度的值:https://dev59.com/X3A75IYBdhLWcg3wYYBQ - user1808924
2个回答

33

我曾经也面临着同样的问题,因为没有直接的方法来解决这个问题。下面是一个对我有用的方法。我将我的管道保存到两个文件中。第一个文件存储了sklearn管道的pickle对象,第二个文件用于存储Keras模型:

...
from keras.models import load_model
from sklearn.externals import joblib

...

pipeline = Pipeline([
    ('scaler', StandardScaler()),
    ('estimator', KerasRegressor(build_model))
])

pipeline.fit(X_train, y_train)

# Save the Keras model first:
pipeline.named_steps['estimator'].model.save('keras_model.h5')

# This hack allows us to save the sklearn pipeline:
pipeline.named_steps['estimator'].model = None

# Finally, save the pipeline:
joblib.dump(pipeline, 'sklearn_pipeline.pkl')

del pipeline

以下是如何重新加载模型的步骤:

# Load the pipeline first:
pipeline = joblib.load('sklearn_pipeline.pkl')

# Then, load the Keras model:
pipeline.named_steps['estimator'].model = load_model('keras_model.h5')

y_pred = pipeline.predict(X_test)

我尝试使用KerasClassifier这种方法,但是出现了错误:“'KerasClassifier'对象没有属性'save'”。你确定你实际上没有执行pipeline.named_steps['estimator'].model.model.save('keras_model.h5')吗? 如果是这样的话,似乎需要再次将KerasClassifier对象包装在加载的模型周围。 - JohnnyQ
1
是的,我非常确定。刚刚再次检查,它完美地工作了 :) (Python 3.5.2,Keras 2.0.8,sklearn 0.19.1) - constt
非常感谢。像魔法一样好用!它非常简单,但却没有人想到过。只需将管道步骤(除了Keras的步骤)保存为pickle/joblib文件,而将Keras保存为model.save即可。这是一个很棒的答案。 - Pranzell
这真是太棒了。非常感谢!! - Asher11
请勿将您的build_model函数定义为本地/嵌套函数,否则您将会收到PicklingError: Can't pickle <function outer_func_name.<locals>.build_model at 0xdeadbeef>: it's not found as module_name.outer_func_name.<locals>.build_model错误提示。 - EasonL

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接