sklearn中的随机森林

阅读了Python的sklearn包中随机森林的代码实现,做了一些笔记。

sklearn中的随机森林是基于RandomForestClassifier类实现的,它的原型是 class RandomForestClassifier(ForestClassifier) 继承了一个抽象类ForestClassifier,也就是分类树 RandomForestClassifier有若干个参数,下面我们一个个来看:

n_estimators 随机森林中树的个数 默认为10

criterion 每一次分裂的标准,有两个可选项,默认的基尼系数("gini")和熵(“entropy”)

max_features 每一次生成树时使用的特征数量,默认为“auto”。若为int则为对应的数量;若为float则对应n_estimators*max_features,即此时max_features对应的一个百分比;若为“auto”或“sqrt”,max_features=sqrt(总的特征数);若为“log2”,则为log2(总的特征数);若为None,则为总的特征数。

max_depth决策树的最大深度,默认为None

min_samples_split每次分裂节点是最小的分裂个数,即最小被分裂为几个,默认为2

min_samples_leaf若某一次分裂时一个叶子节点上的样本数小于这个值,则会被剪枝,默认为1

max_leaf_nodes最大的叶子节点的个数,默认为None,如果不为None,max_depth参数将被忽略

min_weight_fraction_leaf


oob_score、bootstrap这个两个参数决定是否使用out-of-bag进行误差度量和是否使用bootstrap进行抽样,默认都是False

n_jobs并行计算的个数,默认为1,若为-1,则选择为cores的个数

random_state 默认使用np.random

verbose
Controls the verbosity of the tree building process.

warm_start 是否热启动,默认为True

class_weight权重 默认全为1

 首先把标签和特征分离 

1 from sklearn.cross_validation import train_test_split 
2 feature_train, feature_test, target_train, target_test = train_test_split(feature, target, test_size=0.1, random_state=42)

主要的方法有 

1 model = RandomForestClassifier(n_estimators=1000) 
2 model.fit(feature_train , target_train) # 创建一个随机森林 
3 predict=predict(Z) # 对新的样本Z做预测 
4 score = model.score(feature_test , target_test) # 评估正确率

 

posted @ 2017-07-31 11:01  Freeman耀  阅读(4040)  评论(0编辑  收藏  举报