1. # 标准化数据模块
  2. from sklearn import preprocessing
  3. import numpy as np
  4. # 将资料分割成train与test的模块
  5. from sklearn.model_selection import train_test_split
  6. # 生成适合做classification资料的模块
  7. from sklearn.datasets.samples_generator import make_classification
  8. # Support Vector Machine中的Support Vector Classifier
  9. from sklearn.svm import SVC
  10. # 可视化数据的模块
  11. import matplotlib.pyplot as plt

使用 pickle 保存

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

  1. from sklearn import svm
  2. from sklearn import datasets
  3. clf = svm.SVC()
  4. iris = datasets.load_iris()
  5. X, y = iris.data, iris.target
  6. clf.fit(X,y)

使用pickle保存读取训练好的Model。

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

使用 joblib 保存

joblibsklearn的外部模块。

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

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