我在同样的问题上苦苦挣扎,因为没有直接的方法可以做到这一点。这是一个对我有用的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)