#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问题。具体参见:官方文档