欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

【个人学习用】利用随机森林学习调参总结

时间:2023-05-29

按照这个博主写的进行了学习,在文章的后半段开始有调参的过程,前半段为随机森林的基础知识。https://www.jianshu.com/p/8a2e4e2872c8
数据集:sklearn自带的乳腺癌数据
涉及内容:sklearn,随机森林,交叉验证与网格搜索,调参的方法

## 用sklearn 自带的乳腺癌数据进行随机森林的调参学习## 调参先根据前人经验入手## 对于random forest来说一般调参是针对降低模型复杂度,因为大部分树类的模型,模型复杂度都很高,容易过拟合,准确度当然也高,但泛化误差也高。## 有时候调参会依赖于数据集## 调参后达到最大限度的准确度,若还想提升,只能换算法from sklearn.datasets import load_breast_cancerfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import cross_val_scorefrom sklearn.model_selection import GridSearchCVimport matplotlib.pyplot as pltimport numpy as np## 准确的做法应该是先将数据集分成训练集喝测试集,然后把训练集用到以下调参中## 数据的导入data=load_breast_cancer()x=data.datay=data.target# print(data.data.shape) (569, 30)# print(data.target)## 进行粗略的调参,对泛化误差影响最大的超参数n_estimators调参scores=[]for i in range(0,200,10): rf=RandomForestClassifier(n_estimators=i+1,random_state=0) score=cross_val_score(rf,x,y,cv=10).mean() scores.append(score)## 打印最高分数,以及对应的参数print('最高分数:{},对应的n_estimators为{}'.format(max(scores),(scores.index(max(scores))*10)+1))##画学习曲线plt.figure(figsize=[20,5])plt.plot(range(1,201,10),scores)plt.xlabel('n_estimators')plt.ylabel('score')# plt.legend()plt.title('learning curve')plt.show()## 之后可以根据曲线拐弯点,进一步细分参数,如确定n_estimater的参数为39## 下一步用网格搜索,来确定random forest的其他超参数##调整max_depth,结果是准确度下降,根据泛化误差曲线,以及max_depth前人给出的经验(默认用的是最大,max_depth越小,模型复杂度减小)##说明此时位于泛化误差曲线的最低点偏左,之后只要找能往右移的超参数即可(能做到的只有max_features,调的时候max_depth保持原来的值)param_grid={'max_depth':np.arange(1,20,1)}rf=RandomForestClassifier(n_estimators=39,random_state=0)## 与交叉验证结合的网格搜索gs=GridSearchCV(rf,param_grid,cv=10)gs.fit(data.data,data.target)# print(gs.best_score_) 0.9613721804511279# print(gs.best_params_) {'max_depth': 8}

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。