sk10_cross_validation3.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. # View more python learning tutorial 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.learning_curve import validation_curve
  9. from sklearn.datasets import load_digits
  10. from sklearn.svm import SVC
  11. import matplotlib.pyplot as plt
  12. import numpy as np
  13. digits = load_digits()
  14. X = digits.data
  15. y = digits.target
  16. param_range = np.logspace(-6, -2.3, 5)
  17. train_loss, test_loss = validation_curve(
  18. SVC(), X, y, param_name='gamma', param_range=param_range, cv=10,
  19. scoring='mean_squared_error')
  20. train_loss_mean = -np.mean(train_loss, axis=1)
  21. test_loss_mean = -np.mean(test_loss, axis=1)
  22. plt.plot(param_range, train_loss_mean, 'o-', color="r",
  23. label="Training")
  24. plt.plot(param_range, test_loss_mean, 'o-', color="g",
  25. label="Cross-validation")
  26. plt.xlabel("gamma")
  27. plt.ylabel("Loss")
  28. plt.legend(loc="best")
  29. plt.show()