决策树对鸢尾花数据的处理实践

学习了决策树和随机森林的相关理论知识,让我们来动手实践吧~ 还是从熟悉的鸢尾花数据入手
首先导入相关包和进行数据预处理,预处理方法可以见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以后错误率反而上升了,这是因为出现了过拟合,采用随机森林可以解决这个问题,不久我会更新用随机森林处理的实践代码~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章