随机森林-sklearn

随机森林:就是字面意思,在一个地方,有多个树一起组成的森林。也就是由多棵决策树来组成对于问题的判断。

树林的形成:

对于每一个树木,他的训练集和特征要不一样才可以发挥数的特性,否则就是将一颗决策树多次复制。因此,对于训练集的选择,使用bootstrap的抽样方法,就是不放回随机抽样。特征的选取也采用这种方法

API:

from sklearn.ensemble import RandomForestClassifier

RandomForestClassifier(n_estimators=100, criterion='gini', max_depth=None, bootstrap, min_samples_split=2)

# n_estimator 树木的个数
# criteria 默认gini,可选
# max_depth 树的最大深度
# max_features ‘auto’ 和‘sqrt’效果一样,开方决定个数 
# ‘log2’ 将特征总数取log2得到
# ‘None’ 所有特征都使用 
from math import log2
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV


data = pd.read_csv('DS/wine/winequality-red.csv')
feature = data.iloc[:, :11]
target = data.iloc[:, 11:]

target = target.values.ravel()
x_train, x_test, y_train, y_test = train_test_split(
    feature, target, random_state=0, test_size=0.25)


estimator = RandomForestClassifier()
dir = {'n_estimators': [120],
       'max_depth': [14],
       'max_features': [None, 'log2', 'auto']}
estimator = GridSearchCV(estimator, param_grid=dir, cv=8)

estimator.fit(x_train, y_train)

print(estimator.score(x_test, y_test))
print(estimator.best_estimator_)
0.7
RandomForestClassifier(max_depth=14, n_estimators=120)

可见,随机森林的预测效果相比于单颗树的预测效果还是较好的 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值