sk11_save.py 887 B

12345678910111213141516171819202122232425262728293031323334
  1. # View more python tutorials on my Youtube and Youku channel!!!
  2. # Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
  3. # Youku video tutorial: http://i.youku.com/pythontutorial
  4. """
  5. Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
  6. """
  7. from __future__ import print_function
  8. from sklearn import svm
  9. from sklearn import datasets
  10. clf = svm.SVC()
  11. iris = datasets.load_iris()
  12. X, y = iris.data, iris.target
  13. clf.fit(X, y)
  14. # method 1: pickle
  15. import pickle
  16. # save
  17. with open('save/clf.pickle', 'wb') as f:
  18. pickle.dump(clf, f)
  19. # restore
  20. with open('save/clf.pickle', 'rb') as f:
  21. clf2 = pickle.load(f)
  22. print(clf2.predict(X[0:1]))
  23. # method 2: joblib
  24. from sklearn.externals import joblib
  25. # Save
  26. joblib.dump(clf, 'save/clf.pkl')
  27. # restore
  28. clf3 = joblib.load('save/clf.pkl')
  29. print(clf3.predict(X[0:1]))