學習了決策樹和隨機森林的相關理論知識,讓我們來動手實踐吧~ 還是從熟悉的鳶尾花數據入手
首先導入相關包和進行數據預處理,預處理方法可以見https://blog.csdn.net/qq_43468729/article/details/84678701
這裏就不重複寫了。
接着建立pipline模型
model = Pipeline([
('ss', StandardScaler()),
('DTC', DecisionTreeClassifier(criterion='entropy', max_depth=3))]) # 根據熵進行決策樹分割
model = model.fit(x_train, y_train)
y_test_hat = model.predict(x_test)
建立.dot文件 可以方便地看到決策樹的結構
# dot -Tpng -o 1.png 1.dot
f = open('.\\iris_tree.dot', 'w')
# 選擇決策樹的分類器
tree.export_graphviz(model.get_params('DTC')['DTC'], out_file=f)
畫圖:
N, M = 100, 100 # 橫縱各採樣多少個值
x1_min, x1_max = x[:, 0].min(), x[:, 0].max() # 第0列的範圍
x2_min, x2_max = x[:, 1].min(), x[:, 1].max() # 第1列的範圍
t1 = np.linspace(x1_min, x1_max, N)
t2 = np.linspace(x2_min, x2_max, M)
x1, x2 = np.meshgrid(t1, t2) # 生成網格採樣點
x_show = np.stack((x1.flat, x2.flat), axis=1) # 測試點
cm_light = mpl.colors.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF'])
cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b'])
y_show_hat = model.predict(x_show) # 預測值
y_show_hat = y_show_hat.reshape(x1.shape) # 使之與輸入的形狀相同
plt.figure(facecolor='w')# 圖片邊框顏色
plt.pcolormesh(x1, x2, y_show_hat, cmap=cm_light) # 預測值的顯示
plt.scatter(x_test[:, 0], x_test[:, 1], c=y_test.ravel(), edgecolors='k', s=100, cmap=cm_dark, marker='o') # 測試數據
plt.scatter(x[:, 0], x[:, 1], c=y.ravel(), edgecolors='k', s=40, cmap=cm_dark) # 全部數據
plt.xlabel(iris_feature[0], fontsize=15)
plt.ylabel(iris_feature[1], fontsize=15)
plt.xlim(x1_min, x1_max)
plt.ylim(x2_min, x2_max)
plt.grid(True)
plt.title(u'鳶尾花數據的決策樹分類', fontsize=17)
plt.show()
處理數據 計算錯誤率
y_test = y_test.reshape(-1) # 變成行向量
print (y_test_hat)
print (y_test)
result = (y_test_hat == y_test) # True則預測正確,False則預測錯誤
acc = np.mean(result)
print ('錯誤率: %.2f%%' % (100 * (1-acc)))
接着改變決策樹的深度 看看對錯誤率的影響 並畫出折線圖
depth = np.arange(1, 15)
err_list = []
for d in depth:
clf = DecisionTreeClassifier(criterion='entropy', max_depth=d) # 用熵下降最快準則
clf = clf.fit(x_train, y_train)
y_test_hat = clf.predict(x_test) # 測試數據
result = (y_test_hat == y_test) # True則預測正確,False則預測錯誤
err = 1 - np.mean(result)
err_list.append(err)
print (d, ' 錯誤率: %.2f%%' % (100 * err))
plt.figure(facecolor='w')
plt.plot(depth, err_list, 'ro-', lw=2)
plt.xlabel(u'決策樹深度', fontsize=15)
plt.ylabel(u'錯誤率', fontsize=15)
plt.title(u'決策樹深度與過擬合', fontsize=17)
plt.grid(True)
plt.show()
結果如下:
可以看到在深度達到3以後錯誤率反而上升了,這是因爲出現了過擬合,採用隨機森林可以解決這個問題,不久我會更新用隨機森林處理的實踐代碼~~