决策树算法实践

1. 决策树实现步骤

  1. 导包操作
import numpy as np
import os
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12
import warnings
warnings.filterwarnings('ignore')
  1. 加载数据集

    导入燕尾花的数据集和决策树模型,并且加载数据集进行训练

from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier

iris = load_iris()
X = iris.data[:,2:]
y = iris.target

tree_clf = DecisionTreeClassifier(max_depth=2)
tree_clf.fit(X,y)
  1. 导出决策树模型
# 以DOT格式导出决策树
from sklearn.tree import export_graphviz

export_graphviz(
    tree_clf,
    out_file="iris_tree.dot",
    feature_names=iris.feature_names[2:],
    class_names=iris.target_names,
    rounded=True,
    filled=True
)
  1. 使用graphviz包中的dot命令行工具将此**.dot**文件转换为各种格式,如PDF或PNG QMDownload\ChromeDownload\iris tree.dot -o E:\QMDownload\ChromeDownload\iris_tree.png
    机器学习-决策树算法-02-LMLPHP

  2. 加载树模型到Jupyter

# 把图片加载到jupyter
from IPython.display import Image
Image(filename='E:\QMDownload\ChromeDownload\iris_tree.png',width = 350,height = 350)
  1. 效果展示
    机器学习-决策树算法-02-LMLPHP

2. 绘制决策边界

  1. 绘制图形
from matplotlib.colors import ListedColormap


def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):
    x1s = np.linspace(axes[0], axes[1], 100)
    x2s = np.linspace(axes[2], axes[3], 100)
    x1, x2 = np.meshgrid(x1s, x2s)
    X_new = np.c_[x1.ravel(), x2.ravel()]
    y_pred = clf.predict(X_new).reshape(x1.shape)
    custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
    plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
    if not iris:
        custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
        plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
    if plot_training:
        plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", label="Iris-Setosa")
        plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", label="Iris-Versicolor")
        plt.plot(X[:, 0][y==2], X[:, 1][y==2], "g^", label="Iris-Virginica")
        plt.axis(axes)
    if iris:
        plt.xlabel("Petal length", fontsize=14)
        plt.ylabel("Petal width", fontsize=14)
    else:
        plt.xlabel(r"$x_1$", fontsize=18)
        plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
    if legend:
        plt.legend(loc="lower right", fontsize=14)

        
plt.figure(figsize=(8, 4))
plot_decision_boundary(tree_clf, X, y)
plt.plot([2.45, 2.45], [0, 3], "k-", linewidth=2)
plt.plot([2.45, 7.5], [1.75, 1.75], "k--", linewidth=2)
plt.plot([4.95, 4.95], [0, 1.75], "k:", linewidth=2)
plt.plot([4.85, 4.85], [1.75, 3], "k:", linewidth=2)
plt.text(1.40, 1.0, "Depth=0", fontsize=15)
plt.text(3.2, 1.80, "Depth=1", fontsize=13)
plt.text(4.05, 0.5, "(Depth=2)", fontsize=11)
plt.title('Decision Tree decision boundaries')

plt.show()
  1. 效果展示

    从此图中能够看出,当Depth=0时,分的横轴Petal length,以2.45为标准,当Petal length<2.45时,class=setosa,大于的时候是另外两类;然后以纵轴Petal width划分,当Petal width<1.75时,class=versicolor,大于1.75时是class=virginica
    机器学习-决策树算法-02-LMLPHP

3. 概率估计

估计类概率
输入数据为:花瓣长5厘米,宽1.5厘米的花。 相应的叶节点是深度为2的左节点,因此决策树应输出以下概率:

  • Iris-Setosa 为 0%(0/54)
  • Iris-Versicolor 为 90.7%(49/54)
  • Iris-Virginica 为 9.3%(5/54)
# 预测概率值
tree_clf.predict_proba([[5,1.5]])
## 结果:array([[0. , 0.90740741, 0.09259259]])

# 直接预测结果
tree_clf.predict([[5,1.5]])
## 结果:array([1])

4. 决策树中的正则化

通过 DecisionTreeClassifier类的一些参数来设置,防止出现决策树过拟合的现象,下面列出五种常用的参数以及代表的含义

  • min_samples_split : 节点在分割之前必须具有的最小样本数
  • min_samples_leaf : 叶子节点必须具有的最小样本数
  • max_leaf_nodes : 叶子节点的最大数量
  • max_features : 在每个节点处评估用于拆分的最大特征数
  • max_depth : 树最大的深度
  1. 五种参数的具体实现
# 测试案例
from sklearn.datasets import make_moons
X,y = make_moons(n_samples = 100,noise = 0.25,random_state = 53)
tree_clf1 = DecisionTreeClassifier(random_state=42)
tree_clf2 = DecisionTreeClassifier(min_samples_split=20,random_state=42)
tree_clf3 = DecisionTreeClassifier(min_samples_leaf=4,random_state=42)
tree_clf4 = DecisionTreeClassifier(max_leaf_nodes=20,random_state=42)
tree_clf5 = DecisionTreeClassifier(max_features=2,random_state=42)
tree_clf6 = DecisionTreeClassifier(max_depth=5,random_state=42)
tree_clf1.fit(X,y)
tree_clf2.fit(X,y)
tree_clf3.fit(X,y)
tree_clf4.fit(X,y)
tree_clf5.fit(X,y)
tree_clf6.fit(X,y)

plt.figure(figsize=(18,11))
plt.subplot(231)
plot_decision_boundary(tree_clf1,X,y,axes=[-1.5,2.5,-1,1.5],iris = False)
plt.title('Origin image')

plt.subplot(232)
plot_decision_boundary(tree_clf2,X,y,axes=[-1.5,2.5,-1,1.5],iris = False)
plt.title('min_samples_split=20')

plt.subplot(233)
plot_decision_boundary(tree_clf3,X,y,axes=[-1.5,2.5,-1,1.5],iris = False)
plt.title('min_samples_leaf=4')

plt.subplot(234)
plot_decision_boundary(tree_clf4,X,y,axes=[-1.5,2.5,-1,1.5],iris = False)
plt.title('max_leaf_nodes=20')

plt.subplot(235)
plot_decision_boundary(tree_clf5,X,y,axes=[-1.5,2.5,-1,1.5],iris = False)
plt.title('max_features=2')

plt.subplot(236)
plot_decision_boundary(tree_clf6,X,y,axes=[-1.5,2.5,-1,1.5],iris = False)
plt.title('max_depth=5')
  1. 效果展示

    从图像上看,当min_samples_split=20min_samples_leaf=4的时候效果较好,其他都出现过拟合的现象,在测试集上的表现相对较差。
    机器学习-决策树算法-02-LMLPHP

5. 决策树对数据敏感

  1. 代码实例
np.random.seed(6)
Xs = np.random.rand(100, 2) - 0.5
ys = (Xs[:, 0] > 0).astype(np.float32) * 2

angle = np.pi / 4
rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
Xsr = Xs.dot(rotation_matrix)

tree_clf_s = DecisionTreeClassifier(random_state=42)
tree_clf_s.fit(Xs, ys)
tree_clf_sr = DecisionTreeClassifier(random_state=42)
tree_clf_sr.fit(Xsr, ys)

plt.figure(figsize=(11, 4))
plt.subplot(121)
plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
plt.title('Sensitivity to training set rotation')

plt.subplot(122)
plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
plt.title('Sensitivity to training set rotation')

plt.show()
  1. 效果展示

    左图是原始图像以及分类的结果;右图为左图向右旋转90度后的结果,可以看出,决策树并不是简单的画一条斜线,而是出现连续的线段。
    机器学习-决策树算法-02-LMLPHP

6. 回归任务

6.1. 回归任务
  1. 模拟数据集
np.random.seed(42)
m=200
X=np.random.rand(m,1)
y = 4*(X-0.5)**2
y = y + np.random.randn(m,1)/10
  1. 进行训练
from sklearn.tree import DecisionTreeRegressor

tree_reg = DecisionTreeRegressor(max_depth=2)
tree_reg.fit(X,y)
  1. 导出决策树模型
export_graphviz(
        tree_reg,
        out_file=("regression_tree.dot"),
        feature_names=["x1"],
        rounded=True,
        filled=True
    )
  1. 加载树模型到Jupyter
# 把图片加载到jupyter
from IPython.display import Image
Image(filename='E:/QMDownload/ChromeDownload/regression_tree.png',width = 450,height = 600)
  1. 结果展示
    机器学习-决策树算法-02-LMLPHP
6.2. 树的深度影响
from sklearn.tree import DecisionTreeRegressor

# 对比树的最大深度
tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
tree_reg1.fit(X, y)
tree_reg2.fit(X, y)

def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"):
    x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)
    y_pred = tree_reg.predict(x1)
    plt.axis(axes)
    plt.xlabel("$x_1$", fontsize=18)
    if ylabel:
        plt.ylabel(ylabel, fontsize=18, rotation=0)
    plt.plot(X, y, "b.")
    plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$")

plt.figure(figsize=(11, 4))
plt.subplot(121)
plot_regression_predictions(tree_reg1, X, y)
for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
    plt.plot([split, split], [-0.2, 1], style, linewidth=2)
plt.text(0.21, 0.65, "Depth=0", fontsize=15)
plt.text(0.01, 0.2, "Depth=1", fontsize=13)
plt.text(0.65, 0.8, "Depth=1", fontsize=13)
plt.legend(loc="upper center", fontsize=18)
plt.title("max_depth=2", fontsize=14)

plt.subplot(122)
plot_regression_predictions(tree_reg2, X, y, ylabel=None)
for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
    plt.plot([split, split], [-0.2, 1], style, linewidth=2)
for split in (0.0458, 0.1298, 0.2873, 0.9040):
    plt.plot([split, split], [-0.2, 1], "k:", linewidth=1)
plt.text(0.3, 0.5, "Depth=2", fontsize=13)
plt.title("max_depth=3", fontsize=14)

plt.show()

效果展示:

树的深度为3的时候,在0.0到0.2之间出现过拟合现象
机器学习-决策树算法-02-LMLPHP

6.3. 树的最小叶子结点个数影响
tree_reg1 = DecisionTreeRegressor(random_state=42)
tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)
tree_reg1.fit(X, y)
tree_reg2.fit(X, y)

x1 = np.linspace(0, 1, 500).reshape(-1, 1)
y_pred1 = tree_reg1.predict(x1)
y_pred2 = tree_reg2.predict(x1)

plt.figure(figsize=(11, 4))

plt.subplot(121)
plt.plot(X, y, "b.")
plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$")
plt.axis([0, 1, -0.2, 1.1])
plt.xlabel("$x_1$", fontsize=18)
plt.ylabel("$y$", fontsize=18, rotation=0)
plt.legend(loc="upper center", fontsize=18)
plt.title("No restrictions", fontsize=14)

plt.subplot(122)
plt.plot(X, y, "b.")
plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$")
plt.axis([0, 1, -0.2, 1.1])
plt.xlabel("$x_1$", fontsize=18)
plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14)

plt.show()

效果展示:

左图为不做任何过拟合处理的结果图;右图是做min_samples_leaf=10的拟合结果,可以有效防止过拟合现象

机器学习-决策树算法-02-LMLPHP

11-09 06:52