zoukankan      html  css  js  c++  java
  • 机器学习之决策树分类器

    决策树,当下比较流行的有三种分类器,

    C4.5,

    ID3,

    CART,

    不过大同小异,主要的区别就是选择的目标函数不同,ID3使用的是信息增益,C4.5使用信息增益率,CART使用的是Gini系数。

    ,具体的原理就不说了,去翻翻别的博主吧,下面给出本人测试的小demo,帮助各位学者更快入手。

    # -*- coding:utf-8 -*-
    from sklearn.datasets import load_iris
    from sklearn import preprocessing
    from sklearn.model_selection import train_test_split
    from sklearn.tree import DecisionTreeClassifier

    iris=load_iris()
    x=iris.data #特征数据
    y=iris.target#标签数据

    #数据划分
    x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=1)


    #数据标准化
    scaler=preprocessing.StandardScaler().fit(x_train)
    x1_train=scaler.transform(x_train)
    x1_test=scaler.transform(x_test)


    #模型训练
    clf=DecisionTreeClassifier(criterion='gini')
    clf.fit(x1_train,y_train)

    print(clf.predict(x1_test))

    print(clf.score(x1_test,y_test))

    DecisionTreeClassifier(criterion='entropy', min_samples_leaf=3)函数为创建一个决策树模型,其函数的参数含义如下所示:

    • criterion:gini或者entropy,前者是基尼系数,后者是信息熵。
    • splitter: best or random 前者是在所有特征中找最好的切分点 后者是在部分特征中,默认的”best”适合样本量不大的时候,而如果样本数据量非常大,此时决策树构建推荐”random” 。
    • max_features:None(所有),log2,sqrt,N  特征小于50的时候一般使用所有的
    • max_depth:  int or None, optional (default=None) 设置决策随机森林中的决策树的最大深度,深度越大,越容易过拟合,推荐树的深度为:5-20之间。
    • min_samples_split:设置结点的最小样本数量,当样本数量可能小于此值时,结点将不会在划分。
    • min_samples_leaf: 这个值限制了叶子节点最少的样本数,如果某叶子节点数目小于样本数,则会和兄弟节点一起被剪枝。
    • min_weight_fraction_leaf: 这个值限制了叶子节点所有样本权重和的最小值,如果小于这个值,则会和兄弟节点一起被剪枝默认是0,就是不考虑权重问题。
    • max_leaf_nodes: 通过限制最大叶子节点数,可以防止过拟合,默认是"None”,即不限制最大的叶子节点数。
    • class_weight: 指定样本各类别的的权重,主要是为了防止训练集某些类别的样本过多导致训练的决策树过于偏向这些类别。这里可以自己指定各个样本的权重,如果使用“balanced”,则算法会自己计算权重,样本量少的类别所对应的样本权重会高。
  • 相关阅读:
    [LeetCode]题解(python):136-Single Number
    [LeetCode]题解(python):135-Candy
    [LeetCode]题解(python):134-Gas Station
    [LeetCode]题解(python):133-Clone Graph
    [LeetCode]题解(python):132-Palindrome Partitioning II
    [LeetCode]题解(python):131-Palindrome Partitioning
    [LeetCode]题解(python):130-Surrounded Regions
    [LeetCode]题解(python):129-Sum Root to Leaf Numbers
    [LeetCode]题解(python):128-Longest Consecutive Sequence
    [LeetCode]题解(python):127-Word Ladder
  • 原文地址:https://www.cnblogs.com/xinyumuhe/p/12606063.html
Copyright © 2011-2022 走看看