分类法 Classification - EX 4: Classifier Comparison

优质
小牛编辑
119浏览
2023-12-01

分类法/范例四: 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()