1. 程式人生 > >sklearn(九):Model persistence

sklearn(九):Model persistence

#way1  利用pickle.dump()將訓練好的分類器序列化(轉為二進位制),利用 pickle.loads()反序列化;
>>> from sklearn import svm
>>> from sklearn import datasets
>>> clf = svm.SVC(gamma='scale')
>>> 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='ovr', degree=3, gamma='scale', 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 # In the specific case of scikit-learn, it may be better to use joblib’s replacement of pickle (joblib.dump & joblib.load), which is more efficient on objects that carry large numpy arrays internally as
is often the case for fitted scikit-learn estimators, but can only pickle to the disk and not to a string #way2 joblib.dump() joblib.load() >>> from sklearn.externals import joblib >>> joblib.dump(clf, 'filename.joblib') #儲存模型 >>> clf = joblib.load('filename.joblib') #下載模型

在使用上述函式下載模型時,存在一些security 和 maintainability問題。具體參見:官方文件