ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

ML之RF:随机森林RF算法简介、应用、经典案例之详细攻略

2021-06-15 20:58:42  阅读:405  来源: 互联网

标签:leaf features min ML RF split 攻略 max


ML之RF:随机森林RF算法简介、应用、经典案例之详细攻略

 

 

目录

随机森林RF算法简介

1、RF基本的构建算法过程

2、RF算法相关文献、论文

随机森林RF算法的应用

1、RF用于回归

2、RF用于分类

随机森林RF算法的经典案例

1、基础用法


 

 

 

随机森林RF算法简介

         随机森林指的是利用多棵决策树对样本进行训练并预测的一种分类器。它包含多个决策树的分类器,并且其输出的类别是由个别树输出的类别的众数而定。随机森林是一种灵活且易于使用的机器学习算法,即便没有超参数调优,也可以在大多数情况下得到很好的结果。随机森林也是最常用的算法之一,因为它很简易,既可用于分类也能用于回归
         随机森林集成了所有的分类投票结果,将投票次数最多的类别指定为最终的输出,这就是一种最简单的Bagging思想。

1、RF基本的构建算法过程

  • 1. 用N来表示训练用例(样本)的个数,M表示特征数目。
  • 2. 输入特征数目m,用于确定决策树上一个节点的决策结果;其中m应远小于M。
  • 3. 从N个训练用例(样本)中以有放回抽样的方式,取样N次,形成一个训练集(即bootstrap取样),并用未抽到的用例(样本)作预测,评估其误差。
  • 4. 对于每一个节点,随机选择m个特征,决策树上每个节点的决定都是基于这些特征确定的。根据这m个特征,计算其最佳的分裂方式。
  • 5. 每棵树都会完整成长而不会剪枝,这有可能在建完一棵正常树状分类器后被采用)。

 

2、RF算法相关文献、论文

1. Panda Biswanath , Joshua S. Herbach , Sugato Basu , and Roberto J. Bayardo .( 2009 ).PLANET: Massively Parallel Learning of Tree Ensembles with MapReduce. Proceedings of the 35th International Conference on Very Large Data Bases. Retrieved from http://research.google.com/pubs/pub36296.html .
2. Leo Breiman . (September, 1994 ). Bagging Predictors. Technical Report No. 421.Department of Statistics, UC Berkeley. Retrieved from http:// statistics.berkeley.edu/sites/default/files/tech-reports/421.pdf .
3. Leo Breiman . (2001). Random forests . Machine Learning g , 45 : 5 – 32 . Retrieved from http://oz.berkeley.edu/~breiman/randomforest2001.pdf .
4. J.H. Friedman . (2001). Greedy Function Approximation: A Gradient Boosting Machine .Annals of Statistics,29(5): 1189–1232.Retrieved from http://statweb. stanford.edu/~jhf/ftp/trebst.pdf.
5. J.H. Friedman . (2002). Stochastic Gradient Boosting . Computational Statistics and Data Analysis , 38 (4): 367– 378 . Retrieved from http://statweb.stanford.edu/~jhf/ftp/stobst.pdf .

 

 

 

随机森林RF算法的应用

1、RF用于回归

klearn.ensemble.RandomForestRegressor的类构造函数

函数API官方解释:https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html#sklearn.ensemble.RandomForestRegressor
(1)、重点参数解释
n_estimators:整型,可选(缺省值为10)。此参数指定集成方法中决策树的数目。通常缺省值就可以工作得很好。如果想获得最佳的性能,就需要多于10 个决策树。可以通过做实验尝试确定最佳的决策树数目。正如全书始终强调的,合适的模型复杂度(决策树的深度和决策树的数目)取决于问题的复杂度和可获得的数据的规模。比较好的尝试是100 ~ 500。

max_depth:整型或者none, 可选(缺省值为None)。如果这个参数设置为None,决策树就会持续增长,直到叶子节点为空或者所含数据实例小于min_samples_split。除了指定决策树的深度,可以用参数max_leaf_nodes 来指定决策树的叶子节点数。如果指定了max_leaf_nodes,max_depth 参数就会被忽略。不设置max_depth,让决策树自由生长,形成一个满度的决策树可能可以获得性能上的好处。当然与之相伴的代价就是训练时间。在模型的训练过程中,可能需要尝试不同深度的决策树。

min_sample_split:整型,可选(缺省值为2)。当节点含有的数据实例少于min_sample_split 时,此节点不再分割。对含有较少实例的节点进行分割是过拟合错误的源头。

min_samples_leaf:整型,可选(缺省值为1)。如果分割导致节点拥有的数据实例少于min_sample_leaf,分割就不会进行。这个参数的缺省值实际上导致此参数被忽略。通常这是可行的,特别是对数据集进行头几次试运行时。可以用各种方法为这个参数选择一个更有意义的值。一个方法是参数选取为叶子节点含有实例数的平均值,这样如果叶节点含有多于1 个的数据实例,就可以获得更低的均方差。另一种方法是将此参数看作控制决策树深度的替代方法。

max_features:整型、浮点型或字符串型,可选(缺省值为None)。当查找最佳分割点时,需要考虑多少个属性是由max_features 参数和问题中一共有多少个属性共同决定的。假设问题数据集中共有nFeatures 个属性。则:
● 如果 max_features 是整型,则在每次分割时考虑 max_features 个属性。注:如果max_features > nFeatures,则抛出错误。
● 如果 max_features 是浮点型,max_features 表示需考虑的属性占全部属性的百分比,即int( max_features*nFeatures)。
● 可选择的字符串值如下:
auto max_features=nFeatures
sqrt max_features=sqrt(nFeatures)
log2 max_features=log2(nFeatures)
● 如果 max_features=None, 则 max_features=nFeatures。绝大多数训练过程的参数都在RandomForestRegressor的构造函数中设置。max_features参数是唯一没有使用缺省值。
(1)、此参数的缺省值(None)会导致在决策树的每个节点都要考虑全部的属性。这意味着实际上实现的是Bagging 方法,因为这里没有随机选择属性的过程。

Brieman 和Cutler 建议对回归问题使用sqrt(nFeatues) 个属性。模型通常对max_features 不是很敏感,但是这个参数还是有一些影响,因此可以根据需要尝试一些不同的值。

random_state:整型,RandomState 实例,或者None ( 缺省值为None)。
● 如果类型是整型,则此整数作为随机数生成器的种子。
● 如果是 RandomState 的一个实例,则此实例用来作为随机数生成器。
● 如果是None,则随机数生成器是numpy.random用的RandomState的一个实例。

       RandomForestRegressor 类有几个属性,包括用来构成集成方法的决策树。RandomForestRegressor 类有用训练好的决策树进行预测的方法,因此通常不需要直接访问这些属性。但是可能需要访问变量importances。下面是对此变量的描述。
      feature_importances这是一个数组,数组的长度等于问题的属性数(也就是nFeatures)。数组中的值是正的浮点数,表明对应的属性对预测结果的贡献重要性。属性的重要性由Brieman 在最初的随机森林论文中所提的一个方法来确定。基本思想是,每次选中一个属性,然后对属性的值进行随机置换,记录下预测准确性的变化,预测的准确性越高,此属性也越重要。

(2)、重点类解释

fit(XTrain, yTrain, sample_weight=None)
       XTrain 是属性值的数组(训练数据),它有nInstances 行和nFeatures 列。yTrain 是目标(标签)值的数组。y 同样有nInstances 行。在本章的例子中可以看到yTrain 只有一列,但是此方法可以应用于具有不同目标的模型。因此y 可以有nTargets 列,每列对应一个结果(目标,标签)集合。Sample_weight 用来对训练数据集中的每个实例分配不同的权重,它有两种形式:缺省值是None,意味着所有输入实例具有相同的权重;如果对每个实
例分配不同的权重,sample_weight 就是一个数组,具有nInstances 行和1 列。

predict(XTest)
       XTest 是属性值的数组(测试数据),基于这些属性值进行预测。此数组是predict() 方法的输入,此数组的列数与输入fit() 的数组的列数相同,但是可能具有不同的行数,也可能只有一行。Predict() 的输出形式与用于训练的目标数组y 相同。

(3)、详细文档

class RandomForestRegressor Found at: sklearn.ensemble.forest

class RandomForestRegressor(ForestRegressor):

    
    Examples
    --------
    >>> from sklearn.ensemble import RandomForestRegressor
    >>> from sklearn.datasets import make_regression
    >>>
    >>> X, y = make_regression(n_features=4, n_informative=2,
    ...                        random_state=0, shuffle=False)
    >>> regr = RandomForestRegressor(max_depth=2, random_state=0)
    >>> regr.fit(X, y)
    RandomForestRegressor(bootstrap=True, criterion='mse', 
     max_depth=2,
    max_features='auto', max_leaf_nodes=None,
    min_impurity_decrease=0.0, min_impurity_split=None,
    min_samples_leaf=1, min_samples_split=2,
    min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1,
    oob_score=False, random_state=0, verbose=0, warm_start=False)
    >>> print(regr.feature_importances_)
    [ 0.17339552  0.81594114  0.          0.01066333]
    >>> print(regr.predict([[0, 0, 0, 0]]))
    [-2.50699856]
    
    Notes
    -----
    The default values for the parameters controlling the size of the trees
    (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and
    unpruned trees which can potentially be very large on some data sets. 
     To
    reduce memory consumption, the complexity and size of the trees 
     should be
    controlled by setting those parameter values.
    
    The features are always randomly permuted at each split. Therefore,
    the best found split may vary, even with the same training data,
    ``max_features=n_features`` and ``bootstrap=False``, if the improvement
    of the criterion is identical for several splits enumerated during the
    search of the best split. To obtain a deterministic behaviour during
    fitting, ``random_state`` has to be fixed.
    
    References
    ----------
    
    .. [1] L. Breiman, "Random Forests", Machine Learning, 45(1), 5-32, 
     2001.
    
    See also
    --------
    DecisionTreeRegressor, ExtraTreesRegressor
    """
    def __init__(self, 
        n_estimators=10, 
        criterion="mse", 
        max_depth=None, 
        min_samples_split=2, 
        min_samples_leaf=1, 
        min_weight_fraction_leaf=0., 
        max_features="auto", 
        max_leaf_nodes=None, 
        min_impurity_decrease=0., 
        min_impurity_split=None, 
        bootstrap=True, 
        oob_score=False, 
        n_jobs=1, 
        random_state=None, 
        verbose=0, 
        warm_start=False):
        super(RandomForestRegressor, self).__init__
         (base_estimator=DecisionTreeRegressor(), n_estimators=n_estimators, 
         estimator_params=("criterion", "max_depth", "min_samples_split", 
         "min_samples_leaf", "min_weight_fraction_leaf", "max_features", 
         "max_leaf_nodes", "min_impurity_decrease", "min_impurity_split", 
         "random_state"), bootstrap=bootstrap, oob_score=oob_score, 
         n_jobs=n_jobs, random_state=random_state, verbose=verbose, 
         warm_start=warm_start)
        self.criterion = criterion
        self.max_depth = max_depth
        self.min_samples_split = min_samples_split
        self.min_samples_leaf = min_samples_leaf
        self.min_weight_fraction_leaf = min_weight_fraction_leaf
        self.max_features = max_features
        self.max_leaf_nodes = max_leaf_nodes
        self.min_impurity_decrease = min_impurity_decrease
        self.min_impurity_split = min_impurity_split

 

2、RF用于分类

0、RF用于分类与用于回归的两点区别
(1)、第一个不同是用于判断分割点质量的标准。DT的训练过程,需要尝试所有可能的属性,针对每个属性尝试所有可能的分割点,然后从中找出最佳的属性及其分割点。对于回归决策树,分割点的质量是由平方误差和( sum squared error)决定的。但是平方误差和对于分类问题就不起作用了,需要类似误分类率的指标来描述。
(2)、

1、sklearn.ensemble.RandomForestClassifier类构造函数
函数API官方解释:https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html#sklearn-ensemble-randomforestclassifier

(1)、重点参数解释

Criterion:字符串,可选(缺省值为“gini”)。可能的取值如下。
Gini :利用基尼不纯度(Gini impurity)。
Entropy :利用基于熵的信息增益。
          当训练数据终结于决策树的叶子节点时,叶子节点含有属于不同类别的数据,则根据叶子节点中不同类别的数据所占的百分比,分类决策树自然就可以得到数据属于某个类别的概率。依赖于具体的应用,可能想直接获得上述的概率,或者想直接将叶子节点中所占数据最多的类别作为预测值返回。如果在获得预测结果的同时想要调整阈值,则需要获得概率值。为了生成曲线下面积(area under the curve,AUC),可能想获得接收者操作特征曲线(receiver operating curve,ROC) 及其概率以保证精确度。如果想计算误分类率,则需要将概率转换为类别的预测。

(2)、重点方法解释

Fit( X, y, sample_weight=None):随机森林分类版本惟一的不同在于标签y 的特征。对于分类问题,标签的取值为0 到类别数减1 的整数。对于二分类问题,标签的取值是0 或1。对于有nClass 个不同类别的多类别分类问题,标签是从0 到nClass-1 的整数。
Predict(X):对于属性矩阵(二维的numpy 数组)X,此函数产生所属类别的预测。它生成一个单列的数组,行数等于X 的行数。每个元素是预测的所属类别,不管问题是二分类问题还是多类别分类问题,都是一样的。
Predict_proba(X):这个版本的预测函数产生一个二维数组。行数等于X 的行数。列数就是预测的类别数(对于二分类问题就是2 列)。每行的元素就是对应类别的概率。
Predict_log_proba(X):这个版本的预测函数产生一个与predict_proba 相似的二维数组。但是显示的不是所属类别的概率,而是概率的log 值。

(3)、详细文档

class RandomForestClassifier Found at: sklearn.ensemble.forest

class RandomForestClassifier(ForestClassifier):
    
    Examples
    --------
    >>> from sklearn.ensemble import RandomForestClassifier
    >>> from sklearn.datasets import make_classification
    >>>
    >>> X, y = make_classification(n_samples=1000, n_features=4,
    ...                            n_informative=2, n_redundant=0,
    ...                            random_state=0, shuffle=False)
    >>> clf = RandomForestClassifier(max_depth=2, random_state=0)
    >>> clf.fit(X, y)
    RandomForestClassifier(bootstrap=True, class_weight=None, 
     criterion='gini',
    max_depth=2, max_features='auto', max_leaf_nodes=None,
    min_impurity_decrease=0.0, min_impurity_split=None,
    min_samples_leaf=1, min_samples_split=2,
    min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1,
    oob_score=False, random_state=0, verbose=0, warm_start=False)
    >>> print(clf.feature_importances_)
    [ 0.17287856  0.80608704  0.01884792  0.00218648]
    >>> print(clf.predict([[0, 0, 0, 0]]))
    [1]
    
    Notes
    -----
    The default values for the parameters controlling the size of the trees
    (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and
    unpruned trees which can potentially be very large on some data 
     sets. To
    reduce memory consumption, the complexity and size of the trees 
     should be
    controlled by setting those parameter values.
    
    The features are always randomly permuted at each split. Therefore,
    the best found split may vary, even with the same training data,
    ``max_features=n_features`` and ``bootstrap=False``, if the 
     improvement
    of the criterion is identical for several splits enumerated during the
    search of the best split. To obtain a deterministic behaviour during
    fitting, ``random_state`` has to be fixed.
    
    References
    ----------
    
    .. [1] L. Breiman, "Random Forests", Machine Learning, 45(1), 5-32, 
     2001.
    
    See also
    --------
    DecisionTreeClassifier, ExtraTreesClassifier
    """
    def __init__(self, 
        n_estimators=10, 
        criterion="gini", 
        max_depth=None, 
        min_samples_split=2, 
        min_samples_leaf=1, 
        min_weight_fraction_leaf=0., 
        max_features="auto", 
        max_leaf_nodes=None, 
        min_impurity_decrease=0., 
        min_impurity_split=None, 
        bootstrap=True, 
        oob_score=False, 
        n_jobs=1, 
        random_state=None, 
        verbose=0, 
        warm_start=False, 
        class_weight=None):
        super(RandomForestClassifier, self).__init__
         (base_estimator=DecisionTreeClassifier(), n_estimators=n_estimators, 
         estimator_params=("criterion", "max_depth", "min_samples_split", 
         "min_samples_leaf", "min_weight_fraction_leaf", "max_features", 
         "max_leaf_nodes", "min_impurity_decrease", "min_impurity_split", 
         "random_state"), bootstrap=bootstrap, oob_score=oob_score, 
         n_jobs=n_jobs, random_state=random_state, verbose=verbose, 
         warm_start=warm_start, class_weight=class_weight)
        self.criterion = criterion
        self.max_depth = max_depth
        self.min_samples_split = min_samples_split
        self.min_samples_leaf = min_samples_leaf
        self.min_weight_fraction_leaf = min_weight_fraction_leaf
        self.max_features = max_features
        self.max_leaf_nodes = max_leaf_nodes
        self.min_impurity_decrease = min_impurity_decrease
        self.min_impurity_split = min_impurity_split

 

随机森林RF算法的经典案例

1、基础用法

ML之RF:kaggle比赛之利用泰坦尼克号数据集建立RF模型对每个人进行获救是否预测
ML之RF:基于RF算法实现案例(数据集samtrain.csv、samval.csv、samtest.csv)
ML之RF:基于Matlab利用RF算法实现根据乳腺肿瘤特征向量高精度(better)预测肿瘤的是恶性还是良性
ML之RF:利用Js语言设计随机森林算法【DT之CART算法(gain index)】&并应用随机森林算法
ML之RF&DT:利用RF(RFR)、DT(DTR)两种算法实现对boston(波士顿房价)数据集进行训练并预测
ML之RF&XGBoost:分别基于RF随机森林、XGBoost算法对Titanic(泰坦尼克号)数据集进行二分类预测(乘客是否生还)
ML之RF&XGBoost:基于RF/XGBoost(均+5f-CrVa)算法对Titanic(泰坦尼克号)数据集进行二分类预测(乘客是否生还)

 

 

 

 

标签:leaf,features,min,ML,RF,split,攻略,max
来源: https://blog.51cto.com/u_14217737/2906452

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有