分類法/範例四: Classifier comparison

這個範例的主要目的

  • 比較各種分類器
  • 利用圖示法觀察各種分類器的分類邊界及區域

(一)引入函式並準備分類器

  • 將分類器引入之後存放入一個list
  • 這邊要注意 sklearn.discriminant_analysis 必需要 sklearn 0.17以上才能執行
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from matplotlib.colors import ListedColormap
  4. from sklearn.cross_validation import train_test_split
  5. from sklearn.preprocessing import StandardScaler
  6. from sklearn.datasets import make_moons, make_circles, make_classification
  7. from sklearn.neighbors import KNeighborsClassifier
  8. from sklearn.svm import SVC
  9. from sklearn.tree import DecisionTreeClassifier
  10. from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
  11. from sklearn.naive_bayes import GaussianNB
  12. from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
  13. from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
  14. h = .02 # step size in the mesh
  15. names = ["Nearest Neighbors", "Linear SVM", "RBF SVM", "Decision Tree",
  16. "Random Forest", "AdaBoost", "Naive Bayes", "Linear Discriminant Ana.",
  17. "Quadratic Discriminant Ana."]
  18. classifiers = [
  19. KNeighborsClassifier(3),
  20. SVC(kernel="linear", C=0.025),
  21. SVC(gamma=2, C=1),
  22. DecisionTreeClassifier(max_depth=5),
  23. RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1),
  24. AdaBoostClassifier(),
  25. GaussianNB(),
  26. LinearDiscriminantAnalysis(),
  27. QuadraticDiscriminantAnalysis()]

(二)準備測試資料

  • 利用make_classification產生分類資料,n_features=2表示共有兩個特徵, n_informative=2 代表有兩個類別
  • 所產生之 X: 100 x 2矩陣,y: 100 元素之向量,y的數值僅有0或是1用來代表兩種類別
  • 利用X += 2 * rng.uniform(size=X.shape)加入適度的雜訊後將(X,y)資料集命名為linear_separable
  • 最後利用make_moon()make_circles()產生空間中月亮形狀及圓形之數據分佈後,一併存入datasets變數
  1. X, y = make_classification(n_features=2, n_redundant=0, n_informative=2,
  2. random_state=1, n_clusters_per_class=1)
  3. rng = np.random.RandomState(2)
  4. X += 2 * rng.uniform(size=X.shape)
  5. linearly_separable = (X, y)
  6. datasets = [make_moons(noise=0.3, random_state=0),
  7. make_circles(noise=0.2, factor=0.5, random_state=1),
  8. linearly_separable
  9. ]

(三)測試分類器並作圖

接下來這段程式碼有兩個for 迴圈,外迴圈走過三個的dataset,內迴圈則走過所有的分類器。
為求簡要說明,我們將程式碼簡略如下:

  1. 外迴圈:資料迴圈。首先畫出資料分佈,接著將資料傳入分類器迴圈
    1. for ds in datasets:
    2. X, y = ds
    3. #調整特徵值大小使其在特定範圍
    4. X = StandardScaler().fit_transform(X)
    5. #利用train_test_split將資料分成訓練集以及測試集
    6. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.4)
    7. #產生資料網格來大範圍測試分類器,範例EX 3有詳述該用法
    8. xx, yy = np.meshgrid(..........省略)
    9. # 畫出訓練資料點
    10. ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright)
    11. # 畫出測試資料點,用alpha=0.6將測試資料點畫的"淡"一些
    12. ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright, alpha=0.6)
  2. 內迴圈:分類器迴圈。測試分類準確度並繪製分類邊界及區域

    1. for name, clf in zip(names, classifiers):
    2. clf.fit(X_train, y_train)
    3. score = clf.score(X_test, y_test)
    4. # Plot the decision boundary. For that, we will assign a color to each
    5. # point in the mesh [x_min, m_max]x[y_min, y_max].
    6. if hasattr(clf, "decision_function"):
    7. Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
    8. else:
    9. Z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]
    10. # Put the result into a color plot
    11. Z = Z.reshape(xx.shape)
    12. ax.contourf(xx, yy, Z, cmap=cm, alpha=.8)

    為了顯示方便,我將原始碼的內圈改為 for name, clf in zip(names[0:4], classifiers[0:4]):只跑過前四個分類器。

  1. %matplotlib inline
  2. figure = plt.figure(figsize=(30,20), dpi=300)
  3. i = 1
  4. # iterate over datasets
  5. for ds in datasets:
  6. # preprocess dataset, split into training and test part
  7. X, y = ds
  8. X = StandardScaler().fit_transform(X)
  9. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.4)
  10. x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
  11. y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
  12. xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
  13. np.arange(y_min, y_max, h))
  14. # just plot the dataset first
  15. cm = plt.cm.RdBu
  16. cm_bright = ListedColormap(['#FF0000', '#0000FF'])
  17. ax = plt.subplot(len(datasets), (len(classifiers) + 1)//2, i)
  18. # Plot the training points
  19. ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright)
  20. # and testing points
  21. ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright, alpha=0.6)
  22. ax.set_xlim(xx.min(), xx.max())
  23. ax.set_ylim(yy.min(), yy.max())
  24. ax.set_xticks(())
  25. ax.set_yticks(())
  26. i += 1
  27. # iterate over classifiers
  28. for name, clf in zip(names[0:4], classifiers[0:4]):
  29. ax = plt.subplot(len(datasets), (len(classifiers) + 1)//2, i)
  30. clf.fit(X_train, y_train)
  31. score = clf.score(X_test, y_test)
  32. # Plot the decision boundary. For that, we will assign a color to each
  33. # point in the mesh [x_min, m_max]x[y_min, y_max].
  34. if hasattr(clf, "decision_function"):
  35. Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
  36. else:
  37. Z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]
  38. # Put the result into a color plot
  39. Z = Z.reshape(xx.shape)
  40. ax.contourf(xx, yy, Z, cmap=cm, alpha=.8)
  41. # Plot also the training points
  42. ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright)
  43. # and testing points
  44. ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright,
  45. alpha=0.6)
  46. ax.set_xlim(xx.min(), xx.max())
  47. ax.set_ylim(yy.min(), yy.max())
  48. ax.set_xticks(())
  49. ax.set_yticks(())
  50. ax.set_title(name,fontsize=28)
  51. ax.text(xx.max() - .3, yy.min() + .3, ('%.2f' % score).lstrip('0'),
  52. size=30, horizontalalignment='right')
  53. i += 1
  54. figure.subplots_adjust(left=.02, right=.98)
  55. plt.show()

png

(四) 原始碼列表

Python source code: plot_classifier_comparison.py

http://scikit-learn.org/stable/auto_examples/classification/plot_classifier_comparison.html

  1. print(__doc__)
  2. # Code source: Gaël Varoquaux
  3. # Andreas Müller
  4. # Modified for documentation by Jaques Grobler
  5. # License: BSD 3 clause
  6. import numpy as np
  7. import matplotlib.pyplot as plt
  8. from matplotlib.colors import ListedColormap
  9. from sklearn.cross_validation import train_test_split
  10. from sklearn.preprocessing import StandardScaler
  11. from sklearn.datasets import make_moons, make_circles, make_classification
  12. from sklearn.neighbors import KNeighborsClassifier
  13. from sklearn.svm import SVC
  14. from sklearn.tree import DecisionTreeClassifier
  15. from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
  16. from sklearn.naive_bayes import GaussianNB
  17. from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
  18. from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
  19. h = .02 # step size in the mesh
  20. names = ["Nearest Neighbors", "Linear SVM", "RBF SVM", "Decision Tree",
  21. "Random Forest", "AdaBoost", "Naive Bayes", "Linear Discriminant Analysis",
  22. "Quadratic Discriminant Analysis"]
  23. classifiers = [
  24. KNeighborsClassifier(3),
  25. SVC(kernel="linear", C=0.025),
  26. SVC(gamma=2, C=1),
  27. DecisionTreeClassifier(max_depth=5),
  28. RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1),
  29. AdaBoostClassifier(),
  30. GaussianNB(),
  31. LinearDiscriminantAnalysis(),
  32. QuadraticDiscriminantAnalysis()]
  33. X, y = make_classification(n_features=2, n_redundant=0, n_informative=2,
  34. random_state=1, n_clusters_per_class=1)
  35. rng = np.random.RandomState(2)
  36. X += 2 * rng.uniform(size=X.shape)
  37. linearly_separable = (X, y)
  38. datasets = [make_moons(noise=0.3, random_state=0),
  39. make_circles(noise=0.2, factor=0.5, random_state=1),
  40. linearly_separable
  41. ]
  42. figure = plt.figure(figsize=(27, 9))
  43. i = 1
  44. # iterate over datasets
  45. for ds in datasets:
  46. # preprocess dataset, split into training and test part
  47. X, y = ds
  48. X = StandardScaler().fit_transform(X)
  49. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.4)
  50. x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
  51. y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
  52. xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
  53. np.arange(y_min, y_max, h))
  54. # just plot the dataset first
  55. cm = plt.cm.RdBu
  56. cm_bright = ListedColormap(['#FF0000', '#0000FF'])
  57. ax = plt.subplot(len(datasets), len(classifiers) + 1, i)
  58. # Plot the training points
  59. ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright)
  60. # and testing points
  61. ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright, alpha=0.6)
  62. ax.set_xlim(xx.min(), xx.max())
  63. ax.set_ylim(yy.min(), yy.max())
  64. ax.set_xticks(())
  65. ax.set_yticks(())
  66. i += 1
  67. # iterate over classifiers
  68. for name, clf in zip(names, classifiers):
  69. ax = plt.subplot(len(datasets), len(classifiers) + 1, i)
  70. clf.fit(X_train, y_train)
  71. score = clf.score(X_test, y_test)
  72. # Plot the decision boundary. For that, we will assign a color to each
  73. # point in the mesh [x_min, m_max]x[y_min, y_max].
  74. if hasattr(clf, "decision_function"):
  75. Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
  76. else:
  77. Z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]
  78. # Put the result into a color plot
  79. Z = Z.reshape(xx.shape)
  80. ax.contourf(xx, yy, Z, cmap=cm, alpha=.8)
  81. # Plot also the training points
  82. ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright)
  83. # and testing points
  84. ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright,
  85. alpha=0.6)
  86. ax.set_xlim(xx.min(), xx.max())
  87. ax.set_ylim(yy.min(), yy.max())
  88. ax.set_xticks(())
  89. ax.set_yticks(())
  90. ax.set_title(name)
  91. ax.text(xx.max() - .3, yy.min() + .3, ('%.2f' % score).lstrip('0'),
  92. size=15, horizontalalignment='right')
  93. i += 1
  94. figure.subplots_adjust(left=.02, right=.98)
  95. plt.show()