決策樹/範例三: Plot the decision surface of a decision tree on the iris dataset

http://scikit-learn.org/stable/auto_examples/tree/plot_iris.html#sphx-glr-auto-examples-tree-plot-iris-py

此範例利用決策樹分類器將資料集進行分類,找出各類別的分類邊界。以鳶尾花資料集當作範例,每次取兩個特徵做訓練,個別繪製不同品種的鳶尾花特徵的分布範圍。對於每對的鳶尾花特徵,決策樹學習推斷出簡單的分類規則,構成決策邊界。

範例目的:

  1. 資料集:iris 鳶尾花資料集
  2. 特徵:鳶尾花特徵
  3. 預測目標:是哪一種鳶尾花
  4. 機器學習方法:decision tree 決策樹

(一)引入函式庫及內建測試資料庫

  • from sklearn.datasets import load_iris將鳶尾花資料庫存入,iris為一個dict型別資料。
  • 每筆資料中有4個特徵,一次取2個特徵,共有6種排列方式。
  • X (特徵資料) 以及 y (目標資料)。
  • DecisionTreeClassifier 建立決策樹分類器。
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from sklearn.datasets import load_iris
  4. from sklearn.tree import DecisionTreeClassifier
  5. iris = load_iris()
  6. for pairidx, pair in enumerate([[0, 1], [0, 2], [0, 3],
  7. [1, 2], [1, 3], [2, 3]]):
  8. X = iris.data[:, pair]
  9. y = iris.target

(二)建立Decision Tree分類器

建立模型及分類器訓練

  • DecisionTreeClassifier():決策樹分類器。
  • fit(特徵資料, 目標資料):利用特徵資料及目標資料對分類器進行訓練。
  1. clf = DecisionTreeClassifier().fit(X, y)

(三)繪製決策邊界及訓練點

  • np.meshgrid:利用特徵之最大最小值,建立預測用網格 xx, yy
  • clf.predict:預估分類結果。
  • plt.contourf:繪製決策邊界。
  • plt.scatter(X,y):將X、y以點的方式繪製於平面上,c為數據點的顏色,label為圖例。
  1. plt.subplot(2, 3, pairidx + 1)
  2. x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
  3. y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
  4. xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step),
  5. np.arange(y_min, y_max, plot_step))
  6. Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) #np.c_ 串接兩個list,np.ravel將矩陣變為一維
  7. Z = Z.reshape(xx.shape)
  8. cs = plt.contourf(xx, yy, Z, cmap=plt.cm.Paired)
  9. plt.xlabel(iris.feature_names[pair[0]])
  10. plt.ylabel(iris.feature_names[pair[1]])
  11. plt.axis("tight")
  12. for i, color in zip(range(n_classes), plot_colors):
  13. idx = np.where(y == i)
  14. plt.scatter(X[idx, 0], X[idx, 1], c=color, label=iris.target_names[i],
  15. cmap=plt.cm.Paired)
  16. plt.axis("tight")

Ex 3: Plot the decision surface of a decision tree on the iris dataset - 图1

(四)完整程式碼

  1. print(__doc__)
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. from sklearn.datasets import load_iris
  5. from sklearn.tree import DecisionTreeClassifier
  6. # Parameters
  7. n_classes = 3
  8. plot_colors = "bry"
  9. plot_step = 0.02
  10. # Load data
  11. iris = load_iris()
  12. for pairidx, pair in enumerate([[0, 1], [0, 2], [0, 3],
  13. [1, 2], [1, 3], [2, 3]]):
  14. # We only take the two corresponding features
  15. X = iris.data[:, pair]
  16. y = iris.target
  17. # Train
  18. clf = DecisionTreeClassifier().fit(X, y)
  19. # Plot the decision boundary
  20. plt.subplot(2, 3, pairidx + 1)
  21. x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
  22. y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
  23. xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step),
  24. np.arange(y_min, y_max, plot_step))
  25. Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) #np.c_ 串接兩個list,np.ravel將矩陣變為一維
  26. Z = Z.reshape(xx.shape)
  27. cs = plt.contourf(xx, yy, Z, cmap=plt.cm.Paired)
  28. plt.xlabel(iris.feature_names[pair[0]])
  29. plt.ylabel(iris.feature_names[pair[1]])
  30. plt.axis("tight")
  31. # Plot the training points
  32. for i, color in zip(range(n_classes), plot_colors):
  33. idx = np.where(y == i)
  34. plt.scatter(X[idx, 0], X[idx, 1], c=color, label=iris.target_names[i],
  35. cmap=plt.cm.Paired)
  36. plt.axis("tight")
  37. plt.suptitle("Decision surface of a decision tree using paired features")
  38. plt.legend()
  39. plt.show()