zoukankan      html  css  js  c++  java
  • Sklearn库例子——决策树分类

    Sklearn上关于决策树算法使用的介绍:http://scikit-learn.org/stable/modules/tree.html

    1、关于决策树:决策树是一个非参数的监督式学习方法,主要用于分类和回归。算法的目标是通过推断数据特征,学习决策规则从而创建一个预测目标变量的模型。如下如所示,决策树通过一系列if-then-else 决策规则 近似估计一个正弦曲线。

      

    决策树优势:

    • 简单易懂,原理清晰,决策树可以实现可视化

    • 数据准备简单。其他的方法需要实现数据归一化,创建虚拟变量,删除空白变量。(注意:这个模块不支持缺失值)

    • 使用决策树的代价是数据点的对数级别。

    • 能够处理数值和分类数据

    • 能够处理多路输出问题

    • 使用白盒子模型(内部结构可以直接观测的模型)。一个给定的情况是可以观测的,那么就可以用布尔逻辑解释这个结果。相反,如果在一个黑盒模型(ANN),结果可能很难解释

    • 可以通过统计学检验验证模型。这也使得模型的可靠性计算变得可能

    • 即使模型假设违反产生数据的真实模型,表现性能依旧很好。

    决策树劣势:

    • 可能会建立过于复杂的规则,即过拟合。为避免这个问题,剪枝、设置叶节点的最小样本数量、设置决策树的最大深度有时候是必要的。

    • 决策树有时候是不稳定的,因为数据微小的变动,可能生成完全不同的决策树。 可以通过总体平均(ensemble)减缓这个问题。应该指的是多次实验。

    • 学习最优决策树是一个NP完全问题。所以,实际决策树学习算法是基于试探性算法,例如在每个节点实现局部最优值的贪心算法。这样的算法是无法保证返回一个全局最优的决策树。可以通过随机选择特征和样本训练多个决策树来缓解这个问题。

    • 有些问题学习起来非常难,因为决策树很难表达。如:异或问题、奇偶校验或多路复用器问题

    • 如果有些因素占据支配地位,决策树是有偏的。因此建议在拟合决策树之前先平衡数据的影响因子。

    2、分类

    DecisionTreeClassifier 能够实现多类别的分类。输入两个向量:向量X,大小为[n_samples,n_features],用于记录训练样本;向量Y,大小为[n_samples],用于存储训练样本的类标签。

    from sklearn import tree
    X = [[0, 0], [1, 1]]
    Y = [0, 1]
    clf = tree.DecisionTreeClassifier()
    clf = clf.fit(X, Y)
     
    clf.predict([[2., 2.]])
    clf.predict_proba([[2., 2.]])     
    

    下面我们使用iris数据集:

    from sklearn.datasets import load_iris
    from sklearn import tree
    iris = load_iris()
    clf = tree.DecisionTreeClassifier()
    clf = clf.fit(iris.data, iris.target)
     
    # export the tree in Graphviz format using the export_graphviz exporter
    with open("iris.dot", 'w') as f:
        f = tree.export_graphviz(clf, out_file=f)
     
    # predict the class of samples
    clf.predict(iris.data[:1, :])
    # the probability of each class
    clf.predict_proba(iris.data[:1, :])
    

     安装Graphviz将其添加到环境变量,使用dot创建一个PDF文件。dot -Tpdf iris.dot -o iris.pdf 

     关于安装Graphviz方法请参照:http://blog.csdn.net/lanchunhui/article/details/49472949

    运行结果在文件夹下会有:

    这两个文件。我们打开iris.pdf

    你也可以通过安装pydotplus包。安装方式:pip install pydotplus.在Python 中直接生成:

    import pydotplus 
    dot_data = tree.export_graphviz(clf, out_file=None) 
    graph = pydotplus.graph_from_dot_data(dot_data) 
    graph.write_pdf("iris.pdf")
    

     注意:运行这段代码是会出错。我解决了很久没有解决掉。可以参考:http://stackoverflow.com/questions/31209016/python-pydot-and-decisiontree/36456995#36456995

    下面代码是Sklearn官网上的演示代码:

    import numpy as np
    import matplotlib.pyplot as plt
    
    from sklearn.datasets import load_iris
    from sklearn.tree import DecisionTreeClassifier
    
    # Parameters
    n_classes = 3
    plot_colors = "bry"
    plot_step = 0.02
    
    # Load data
    iris = load_iris()
    
    for pairidx, pair in enumerate([[0, 1], [0, 2], [0, 3],
                                    [1, 2], [1, 3], [2, 3]]):
        # We only take the two corresponding features
        X = iris.data[:, pair]
        y = iris.target
    
        # Train
        clf = DecisionTreeClassifier().fit(X, y)
    
        # Plot the decision boundary
        plt.subplot(2, 3, pairidx + 1)
    
        x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
        y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
        xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step),
                             np.arange(y_min, y_max, plot_step))
    
        Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
        Z = Z.reshape(xx.shape)
        cs = plt.contourf(xx, yy, Z, cmap=plt.cm.Paired)
    
        plt.xlabel(iris.feature_names[pair[0]])
        plt.ylabel(iris.feature_names[pair[1]])
        plt.axis("tight")
    
        # Plot the training points
        for i, color in zip(range(n_classes), plot_colors):
            idx = np.where(y == i)
            plt.scatter(X[idx, 0], X[idx, 1], c=color, label=iris.target_names[i],
                        cmap=plt.cm.Paired)
    
        plt.axis("tight")
    
    plt.suptitle("Decision surface of a decision tree using paired features")
    plt.legend()
    plt.show()
    

     代码运行结果:

  • 相关阅读:
    文件的权限与隐藏属性
    Linux工具之bc计算器进制的转换
    老司机教你在windows不用软件隐藏重要文件
    LInux基础命令分类
    Linux文本的处理
    文件的默认权限UMASK
    H3C虚拟化之IRF
    H3C单臂路由配置
    H3C路由交换常用命令
    H3C交换机802.1&dot1x认证
  • 原文地址:https://www.cnblogs.com/itdyb/p/6144511.html
Copyright © 2011-2022 走看看