sklearn(scikit-learn)模型持久化有两种方式:
- Python的内置模块pickle
- scikit-learn内部的joblib
模型定义及训练:
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
#1.保存成Python支持的文件格式Pickle
#在当前目录下可以看到new_app_model_v1.pickle
with open('new_app_model_v1.pickle','wb') as fw:
pickle.dump(model_xgb,fw)
#加载svm.pickle
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!")
# 把训练集中的列名保存为pkl
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') # Load "model.pkl"
print('Model loaded')
new_app_model_v1_columns = joblib.load('new_app_model_v1_columns.pkl')
# Load "model_columns.pkl"
print('Model columns loaded')
print (new_app_model_v1.predict_proba(X_test[0:1].values))
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)