您的位置:首页 > 编程语言 > Python开发

python包sk-learn中的随机森林

2016-05-11 16:00 549 查看
最近在学习机器学习,学习到了随机森林算法,想做一个demo,阅读了python的sk-learn包中随机森林的代码实现,做了一些笔记。

sk-learn中的随机森林是基于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
The minimum weighted fraction of the input samples required to be at a leaf node.(这个没看懂)

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


首先把标签和特征分离

from sklearn.cross_validation import train_test_split

feature_train, feature_test, target_train, target_test =

train_test_split(feature, target, test_size=0.1, random_state=42)

主要的方法有

model = RandomForestClassifier(n_estimators=1000)

model.fit(feature_train , target_train) # 创建一个随机森林

predict=predict(Z) # 对新的样本Z做预测

score = model.score(feature_test , target_test) # 评估正确率
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息