Python机器学习之sklearn随机森林

1.随机森林是什么?

随机森林是一个集成工具,它使用观测数据的子集和变量的子集来建立一个决策树。 它建立多个这样的决策树,然后将他们合并在一起以获得更准确和稳定的预测。(个人理解就是建立很多决策树,然后根据决策树的结果来判断哪个分类更好选哪个)

2.随机森林API

在这里插入图片描述

3.参数调优(网格搜索)

class sklearn.model_selection.GridSearchCV(estimator, param_grid, scoring=None, fit_params=None,n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch=2*n_jobs’, error_score=raise, return_train_score=’warn’)

GridSearchCV:自动调参,只要把参数输进去,就能给出最优化的结果和参数,比较适合小数据集。

介绍几个参数

1.estimator:需要调参的实例化函数对象
2.param_grid:需要最优化的参数的取值,值为字典或者列表
3.cv:交叉验证的次数

 #随机森林(超参数调优)
    rf=RandomForestClassifier()
    param = {"n_estimators":[120,200,300,500,800,1200],"max_depth":[5,8,15,25,30]}
    #网格搜索与交叉验证
    gc=GridSearchCV(rf,param_grid=param,cv=2)#cv表示验证的次数为2
    gc.fit(x_train,y_train)
    print("准确率:",gc.score(x_test,y_test))
    print("查看参数选择:",gc.best_params_)

结果如下:
在这里插入图片描述

附上全部代码

# 获取文件,处理数据
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
def taitan2():
 taitan = pd.read_csv("http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt")
    # 处理数据,找出特征值和目标值
    x = taitan[["pclass", "age", "sex"]]
    y = taitan["survived"]
    print(x)
    # 缺失值处理,对于na值用平均值处理
    x['age'].fillna(x["age"].mean(), inplace=True)
    # 分割数据集,一部分测试一部分训练
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25)
    # 进行特征工程的处理
    dict = DictVectorizer(sparse=False)
    x_train = dict.fit_transform(x_train.to_dict(orient="records"))
    print(dict.get_feature_names())
    x_test = dict.transform(x_test.to_dict(orient="records"))
    rf=RandomForestClassifier()
    param = {"n_estimators":[120,200,300,500,800,1200],"max_depth":[5,8,15,25,30]}
    #网格搜索与交叉验证
    gc=GridSearchCV(rf,param_grid=param,cv=2)#cv表示验证的次数为2
    gc.fit(x_train,y_train)
    print("准确率:",gc.score(x_test,y_test))
    print("查看参数选择:",gc.best_params_)
    return None


if __name__ == "__main__":
    taitan2()
  • 4
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柳小葱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值