sklearn(scikit-learn)模型持久化有两种方式:
- Python的内置模块pickle
- scikit-learn内部的joblib
1. pickle 模型保存及加载
模型定义及训练:
from sklearn import svm
from sklearn import datasets
model_xgb = svm.SVC()
X, y= datasets.load_iris(return_X_y=True)
model_xgb.fit(X, y)
基于 pickle 实现模型保存及加载:
import pickle
with open('new_app_model_v1.pickle','wb') as fw:
pickle.dump(model_xgb,fw)
with open('new_app_model_v1.pickle','rb') as fr:
new_app_model_v1 = pickle.load(fr)
print (new_app_model_v1.predict_proba(X_test[0:1].values))
2. joblib 模型保存及加载
在大量数据的情况下,最好使用scikit-learn的的joblib代替python的pickle(dump&load),这在内部装有大型numpy数组的对象上效率更高。 总结起来,joblib更适合大数据量的模型,不过joblib只能往硬盘存储,不能往字符串存储。
from sklearn.externals import joblib
joblib.dump(model_xgb, 'new_app_model_v1.pkl')
print("Model dumped!")
model_columns = list(X_train.columns)
joblib.dump(model_columns, 'new_app_model_v1_columns.pkl')
print("Models columns dumped!")
new_app_model_v1 = joblib.load('new_app_model_v1.pkl')
print('Model loaded')
new_app_model_v1_columns = joblib.load('new_app_model_v1_columns.pkl')
print('Model columns loaded')
print (new_app_model_v1.predict_proba(X_test[0:1].values))
|