【机器学习】使用Scikit-Learn库实现随机森林

使用随机森林将弱分类器集成为强分类器

随机森林视为多棵决策树的集成

集成学习的基本理念:将弱分类器集成为鲁棒性更强的模型(强分类器)。

分类器集成后具备更好的泛化误差不容易过拟合

使用随机森林步骤:

1、       使用bootstrap抽样法,随机选择n个样本用于训练

2、       使用第一步选择的样本构造决策树

 1)       不重复的随机选择d个特征

 2)       根据目标函数的要求,最大化信息增益

3、       重复以上过程1-2000次

扫描二维码关注公众号,回复: 1031591 查看本文章

4、       汇总每棵决策树的类标进行多数投票。

通常不需要对随机森林进行剪枝,需要关心的是构建随机森林所需的树的数量

构建随机森林的决策树越多,随机森林整体的分类表现就越好,同时增加计算成本。

第一步的n较大则随机性降低,可能会出现过拟合,一般选择较小的n,防止过拟合。

每次节点划分中用到特征数量m,SKlearn默认,m为训练集中特征总量。


本文使用的数据集库文件定义在该章节有定义了,链接:http://mp.blog.csdn.net/postedit/79196206

代码实现:

def randomForests():
    tree = DecisionTreeClassifier (criterion='entropy', max_depth=3, random_state=0)
    tree.fit (X_train, y_train)
    export_graphviz (tree,
                     out_file='tree.dot',
                     feature_names=['petal length', 'petal width'])

    X_combined = np.vstack ((X_train, X_test))
    y_combined = np.hstack ((y_train, y_test))
    # # 通过随机森林将弱者与强者结合。
    
    forest = RandomForestClassifier (criterion='entropy',
                                     n_estimators=10,
                                     random_state=1,
                                     n_jobs=2)
    forest.fit (X_train, y_train)
    
    plot_decision_regions (X_combined, y_combined,
                           classifier=forest, test_idx=range (105, 150))
    
    plt.xlabel ('花瓣长度(厘米)')
    plt.ylabel ('花瓣宽(厘米)')
    plt.legend (loc='upper left')
    plt.tight_layout ()
    # plt.savefig('./figures/random_forest.png', dpi=300)
    plt.show ()

randomForests()







猜你喜欢

转载自blog.csdn.net/chenvast/article/details/79202227