sklearn 中模型保存的两种方法

一、 sklearn中提供了高效的模型持久化模块joblib,将模型保存至硬盘。
from sklearn.externals import joblib
#lr是一个LogisticRegression模型 joblib.dump(lr, 'lr.model') lr = joblib.load('lr.model')

链接:https://www.zhihu.com/question/27187105/answer/55895472

二、pickle
>>> from sklearn import svm >>> from sklearn import datasets >>> clf = svm.SVC() >>> iris = datasets.load_iris() >>> X, y = iris.data, iris.target >>> clf.fit(X, y) SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, decision_function_shape=None, degree=3, gamma='auto', kernel='rbf', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False) >>> import pickle >>> s = pickle.dumps(clf) >>> clf2 = pickle.loads(s) >>> clf2.predict(X[0:1]) array([0]) >>> y[0] 0


或者 :
>>> from sklearn.externals import joblib >>> joblib.dump(clf, 'filename.pkl') >>> clf = joblib.load('filename.pkl') 


两种保存Model的模块picklejoblib

使用 pickle 保存 

首先简单建立与训练一个SVCModel。

from sklearn import svm
from sklearn import datasets clf = svm.SVC() iris = datasets.load_iris() X, y = iris.data, iris.target clf.fit(X,y)

==========================================================================================================

使用pickle保存读取训练好的Model。 (若忘记什么是pickle,可以回顾13.8 pickle 保存数据视频。)

import pickle #pickle模块

#保存Model(注:save文件夹要预先建立,否则会报错)
with open('save/clf.pickle', 'wb') as f: pickle.dump(clf, f) #读取Model with open('save/clf.pickle', 'rb') as f: clf2 = pickle.load(f) #测试读取后的Model print(clf2.predict(X[0:1])) ==========================================================================================================

使用 joblib 保存 

joblibsklearn的外部模块。

from sklearn.externals import joblib #jbolib模块 #保存Model(注:save文件夹要预先建立,否则会报错) joblib.dump(clf, 'save/clf.pkl') #读取Model clf3 = joblib.load('save/clf.pkl') #测试读取后的Model print(clf3.predict(X[0:1])) # [0] 

最后可以知道joblib在使用上比较容易,读取速度也相对pickle快。

 

=====================================================================
链接:https://www.zhihu.com/question/27187105/answer/97334347

https://morvanzhou.github.io/tutorials/machine-learning/sklearn/3-5-save/

你可能感兴趣的:(sklearn 中模型保存的两种方法)