分类法 Classification - EX 3: Plot classification probability

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

分类法/范例三: Plot classification probability

这个范例的主要目的

  • 使用iris 鸢尾花资料集
  • 测试不同分类器对于涵盖特定范围之资料集,分类为那一种鸢尾花的机率
  • 例如:sepal length 为 4cm 而 sepal width 为 3cm时被分类为 versicolor的机率

(一)资料汇入及描述

  • 首先先汇入iris 鸢尾花资料集,使用iris = datasets.load_iris()将资料存入
  • 准备X (特征资料) 以及 y (目标资料),仅使用两个特征方便视觉呈现
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. from sklearn.linear_model import LogisticRegression
  4. from sklearn.svm import SVC
  5. from sklearn import datasets
  6. iris = datasets.load_iris()
  7. X = iris.data[:, 0:2] # 仅使用前两个特征,方便视觉化呈现
  8. y = iris.target
  9. n_features = X.shape[1]
  • iris为一个dict型别资料,我们可以用以下指令来看一下资料的内容。
  1. for key,value in iris.items() :
  2. try:
  3. print (key,value.shape)
  4. except:
  5. print (key)
显示说明
(‘target_names’, (3L,))共有三种鸢尾花 setosa, versicolor, virginica
(‘data’, (150L, 4L))有150笔资料,共四种特征
(‘target’, (150L,))这150笔资料各是那一种鸢尾花
DESCR资料之描述
feature_names四个特征代表的意义

(二) 分类器的选择

这个范例选择了四种分类器,存入一个dict资料中,分别为:

  1. L1 logistic
  2. L2 logistic (OvR)
  3. Linear SVC
  4. L2 logistic (Multinomial)

其中LogisticRegression 并不适合拿来做多目标的分类器,我们可以用结果图的分类机率来观察。

  1. C = 1.0
  2. # Create different classifiers. The logistic regression cannot do
  3. # multiclass out of the box.
  4. classifiers = {'L1 logistic': LogisticRegression(C=C, penalty='l1'),
  5. 'L2 logistic (OvR)': LogisticRegression(C=C, penalty='l2'),
  6. 'Linear SVC': SVC(kernel='linear', C=C, probability=True,
  7. random_state=0),
  8. 'L2 logistic (Multinomial)': LogisticRegression(
  9. C=C, solver='lbfgs', multi_class='multinomial'
  10. )}
  11. n_classifiers = len(classifiers)

而接下来为了产生一个包含绝大部份可能的测试矩阵,我们会用到以下指令。

  1. np.linspace(起始, 终止, 数量) 目的为产生等间隔之数据,例如print(np.linspace(1,3,3)) 的结果为 [ 1. 2. 3.],而print(np.linspace(1,3,5))的结果为 [ 1. 1.5 2. 2.5 3. ]
  2. np.meshgrid(xx,yy)则用来产生网格状座标。
  3. numpy.c_ 为numpy特殊物件,能协助将numpy 阵列连接起来,将程式简化后,我们用以下范例展示相关函式用法。
  1. xx, yy = np.meshgrid(np.linspace(1,3,3), np.linspace(4,6,3).T)
  2. Xfull = np.c_[xx.ravel(), yy.ravel()]
  3. print('xx= \n%s\n' % xx)
  4. print('yy= \n%s\n' % yy)
  5. print('xx.ravel()= %s\n' % xx.ravel())
  6. print('Xfull= \n%s' % Xfull)

结果显示如下,我们可以看出Xfull模拟出了一个类似特征矩阵X, 具备有9笔资料,这九笔资料重现了xx (3种数值变化)及yy(3种数值变化)的所有排列组合。

  1. xx=
  2. [[ 1. 2. 3.]
  3. [ 1. 2. 3.]
  4. [ 1. 2. 3.]]
  5. yy=
  6. [[ 4. 4. 4.]
  7. [ 5. 5. 5.]
  8. [ 6. 6. 6.]]
  9. xx.ravel()= [ 1. 2. 3. 1. 2. 3. 1. 2. 3.]
  10. Xfull=
  11. [[ 1. 4.]
  12. [ 2. 4.]
  13. [ 3. 4.]
  14. [ 1. 5.]
  15. [ 2. 5.]
  16. [ 3. 5.]
  17. [ 1. 6.]
  18. [ 2. 6.]
  19. [ 3. 6.]]

而下面这段程式码的主要用意,在产生一个网格矩阵,其中xx,yy分别代表着iris资料集的第一及第二个特征。xx 是3~9之间的100个连续数字,而yy是1~5之间的100个连续数字。用np.meshgrid(xx,yy)np.c_产生出Xfull特征矩阵,10,000笔资料包含了两个特征的所有排列组合。

  1. plt.figure(figsize=(3 * 2, n_classifiers * 2))
  2. plt.subplots_adjust(bottom=.2, top=.95)
  3. xx = np.linspace(3, 9, 100)
  4. yy = np.linspace(1, 5, 100).T
  5. xx, yy = np.meshgrid(xx, yy)
  6. Xfull = np.c_[xx.ravel(), yy.ravel()]

(三) 测试分类器以及画出机率分布图的选择

接下来的动作

  1. 用迴圈轮过所有的分类器,并计算显示分类成功率
  2. Xfull(10000x2矩阵)传入 classifier.predict_proba()得到probas(10000x3矩阵)。这裏的probas矩阵是10000种不同的特征排列组合所形成的数据,被分类到三种iris 鸢尾花的可能性。
  3. 利用reshape((100,100))将10000笔资料排列成二维矩阵,并将机率用影像的方式呈现出来
  1. #若在ipython notebook (Jupyter) 裏执行,则可以将下列这行的井号移除
  2. %matplotlib inline
  3. #原范例没有下列这行,这是为了让图形显示更漂亮而新增的
  4. fig = plt.figure(figsize=(12,12), dpi=300)
  5. for index, (name, classifier) in enumerate(classifiers.items()):
  6. #训练并计算分类成功率
  7. #然而此范例训练跟测试用相同资料集,并不符合实际状况。
  8. #建议採用cross_validation的方式才能较正确评估
  9. classifier.fit(X, y)
  10. y_pred = classifier.predict(X)
  11. classif_rate = np.mean(y_pred.ravel() == y.ravel()) * 100
  12. print("classif_rate for %s : %f " % (name, classif_rate))
  13. # View probabilities=
  14. probas = classifier.predict_proba(Xfull)
  15. n_classes = np.unique(y_pred).size
  16. for k in range(n_classes):
  17. plt.subplot(n_classifiers, n_classes, index * n_classes + k + 1)
  18. plt.title("Class %d" % k)
  19. if k == 0:
  20. plt.ylabel(name)
  21. imshow_handle = plt.imshow(probas[:, k].reshape((100, 100)),
  22. extent=(3, 9, 1, 5), origin='lower')
  23. plt.xticks(())
  24. plt.yticks(())
  25. idx = (y_pred == k)
  26. if idx.any():
  27. plt.scatter(X[idx, 0], X[idx, 1], marker='o', c='k')
  28. ax = plt.axes([0.15, 0.04, 0.7, 0.05])
  29. plt.title("Probability")
  30. plt.colorbar(imshow_handle, cax=ax, orientation='horizontal')
  31. plt.show()
  1. classif_rate for L2 logistic (OvR) : 76.666667
  2. classif_rate for L1 logistic : 79.333333
  3. classif_rate for Linear SVC : 82.000000
  4. classif_rate for L2 logistic (Multinomial) : 82.000000

png

(四)完整程式码

Python source code: plot_classification_probability.py

http://scikit-learn.org/stable/_downloads/plot_classification_probability.py

  1. print(__doc__)
  2. # Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
  3. # License: BSD 3 clause
  4. import matplotlib.pyplot as plt
  5. import numpy as np
  6. from sklearn.linear_model import LogisticRegression
  7. from sklearn.svm import SVC
  8. from sklearn import datasets
  9. iris = datasets.load_iris()
  10. X = iris.data[:, 0:2] # we only take the first two features for visualization
  11. y = iris.target
  12. n_features = X.shape[1]
  13. C = 1.0
  14. # Create different classifiers. The logistic regression cannot do
  15. # multiclass out of the box.
  16. classifiers = {'L1 logistic': LogisticRegression(C=C, penalty='l1'),
  17. 'L2 logistic (OvR)': LogisticRegression(C=C, penalty='l2'),
  18. 'Linear SVC': SVC(kernel='linear', C=C, probability=True,
  19. random_state=0),
  20. 'L2 logistic (Multinomial)': LogisticRegression(
  21. C=C, solver='lbfgs', multi_class='multinomial'
  22. )}
  23. n_classifiers = len(classifiers)
  24. plt.figure(figsize=(3 * 2, n_classifiers * 2))
  25. plt.subplots_adjust(bottom=.2, top=.95)
  26. xx = np.linspace(3, 9, 100)
  27. yy = np.linspace(1, 5, 100).T
  28. xx, yy = np.meshgrid(xx, yy)
  29. Xfull = np.c_[xx.ravel(), yy.ravel()]
  30. for index, (name, classifier) in enumerate(classifiers.items()):
  31. classifier.fit(X, y)
  32. y_pred = classifier.predict(X)
  33. classif_rate = np.mean(y_pred.ravel() == y.ravel()) * 100
  34. print("classif_rate for %s : %f " % (name, classif_rate))
  35. # View probabilities=
  36. probas = classifier.predict_proba(Xfull)
  37. n_classes = np.unique(y_pred).size
  38. for k in range(n_classes):
  39. plt.subplot(n_classifiers, n_classes, index * n_classes + k + 1)
  40. plt.title("Class %d" % k)
  41. if k == 0:
  42. plt.ylabel(name)
  43. imshow_handle = plt.imshow(probas[:, k].reshape((100, 100)),
  44. extent=(3, 9, 1, 5), origin='lower')
  45. plt.xticks(())
  46. plt.yticks(())
  47. idx = (y_pred == k)
  48. if idx.any():
  49. plt.scatter(X[idx, 0], X[idx, 1], marker='o', c='k')
  50. ax = plt.axes([0.15, 0.04, 0.7, 0.05])
  51. plt.title("Probability")
  52. plt.colorbar(imshow_handle, cax=ax, orientation='horizontal')
  53. plt.show()