決策樹案例


實現代碼:

 1 # -*- coding: utf-8 -*-
 2 """
 3 Created on Wed Aug 29 14:52:09 2018
 4 
 5 @author: zhen
 6 """
 7 import numpy as np
 8 from sklearn.tree import DecisionTreeRegressor
 9 import matplotlib.pyplot as plt
10 n = 100
11 x = np.random.rand(n) * 6 - 3  # 生成100個范圍在-3~3的數據
12 x.sort()  #排序
13 
14 y = np.sin(x) + np.random.rand(n) + 0.05
15 x = x.reshape(-1, 1)  #把數據轉成任意行一列類型
16 y = y.reshape(-1, 1)
17 
18 decision_tree_regressor = DecisionTreeRegressor(criterion='mse', max_depth=3)
19 decision_tree_regressor.fit(x, y)
20 
21 x_test = np.linspace(-3, 3, 50).reshape(-1, 1)  # 創建等差數列
22 y_hat = decision_tree_regressor.predict(x_test)
23 
24 plt.plot(x, y, "y^", label="actual")
25 plt.plot(x_test, y_hat, "b-", linewidth=2, label="predict")
26 
27 plt.legend(loc="upper left")
28 plt.grid()
29 plt.show()
30 
31 # 比較不同深度的決策樹
32 depth = [2, 4, 6, 8, 10]
33 color = 'rgbmy'
34 dec_tree_reg = DecisionTreeRegressor()
35 
36 plt.plot(x, y, "ko", label="actual")
37 x_test = np.linspace(-3, 3, 50).reshape(-1, 1)
38 for d, c in zip(depth, color):
39     dec_tree_reg.set_params(max_depth=d)
40     dec_tree_reg.fit(x, y)
41     y_hat = dec_tree_reg.predict(x_test)
42     plt.plot(x_test, y_hat, '-', color=c, linewidth=2, label="depth=%d" % d)
43     
44 plt.legend(loc="upper left")
45 plt.grid(b=True)
46 plt.show()

結果:

不同深度對預測的影響:

總結:

  決策樹分量算法有構造速度快、結構明顯、分類精度高等優點。
決策樹是以實例(Instance)為核心的歸納分類方法。
它從一組無序的、無特殊領域知識的數據集中提取出決策樹表現形式的分類規則,
包含了分支節點、葉子節點和分支結構。它采用自頂向下的遞歸方式構造樹狀結構,
在決策時分支節點進行基於屬性值的分類選擇,分支節點覆蓋了可能的分類結果,
最終分支節點連接了代表分類結果的葉子節點。
分類過程中經過的連接節點代表了一條分類模式,而這些分類模式的集合就組成了決策樹的框架。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM