【问题标题】:how to save a scikit-learn pipline with keras regressor inside to disk?如何将带有 keras 回归器的 scikit-learn 管道保存到磁盘?
【发布时间】:2016-10-25 08:32:38
【问题描述】:

我有一个带有 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: 超出最大递归深度

如何将管道保存到磁盘?

【问题讨论】:

标签: python machine-learning scikit-learn keras joblib


【解决方案1】:

Keras 与开箱即用的 pickle 不兼容。如果你愿意修补它,你可以修复它:https://github.com/tensorflow/tensorflow/pull/39609#issuecomment-683370566

您还可以使用 SciKeras 库,它可以为您完成此操作,它可以替代 KerasClassifierhttps://github.com/adriangb/scikeras

披露:我是 SciKeras 以及那个 PR 的作者。

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,因为没有直接的方法可以做到这一点。这是一个对我有用的hack。我将管道保存到两个文件中。第一个文件存储了 sklearn 管道的腌制对象,第二个文件用于存储 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”对象没有“保存”属性。你确定你实际上没有在做 pipeline.named_steps['estimator'].model.model.save('keras_model.h5') 吗?然而,在这种情况下,似乎必须再次将 KerasClassifier 对象包裹在加载的模型周围。
    • 是的,我非常确定。刚刚再次检查,它就像一个魅力:)(python 3.5.2,keras 2.0.8,sklearn 0.19.1)
    • 非常感谢。像魅力一样工作!它是如此简单,但没有人弄清楚。只需将管道步骤(Keras 除外)保存为 pickle/joblib 并将 keras 保存为 model.save。很好的答案。
    • 这是天赐之物。非常感谢!
    • 不要将您的 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
    猜你喜欢
    • 2012-05-22
    • 1970-01-01
    • 2021-01-12
    • 2017-07-13
    • 2020-07-11
    • 2021-11-23
    • 2017-06-18
    • 2015-08-14
    相关资源
    最近更新 更多