【机器学习实战】随机森林在乳腺癌数据上的调参
·
1. 数据集
- 特征值

- 目标值


共569个样本,30维特征。
2.代码实现
2.1 未调参时的代码及结果
# 获取数据集
data = load_breast_cancer()
# 建模
rfc = RandomForestClassifier(n_estimators=100, random_state=90) # 交叉验证
rfc_score = cross_val_score(rfc, data.data, data.target, cv=10).mean()
rfc_score
结果:
2.2 调参
2.2.1 粗略调节n_estimators
# 粗略调参
score1 = []
for i in range(0,200,10):
rfc = RandomForestClassifier(n_estimators=i+1
,n_jobs=-1
,random_state=90)
score = cross_val_score(rfc, data.data, data.target, cv=10).mean()
# 将20次交叉验证结果(每次取均值)存入score1
score1.append(score)
print(max(score1), (score1.index(max(score1)))*10+1)
plt.figure(figsize=[20,5])
plt.plot(range(1,201,10), score1)
plt.show()
结果:
2.2.2 上一步得到41左右score最优,缩小范围继续调参
# 细化范围,继续调参
score2 = []
for i in range(35,45):
rfc = RandomForestClassifier(n_estimators=i
,n_jobs=-1,
random_state=90)
score = cross_val_score(rfc, data.data, data.target, cv=10).mean()
score2.append(score)
print(max(score2), ([*range(35, 45)][score2.index(max(score2))]))
plt.figure(figsize=[20,5])
plt.plot(range(35, 45), score2)
plt.show()
结果:
2.2.3 调max_depth(网格搜索)
# 调max_depth(网格搜索)
param_grid = {'max_depth':np.arange(1,20,1)}
rfc = RandomForestClassifier(n_estimators=39
,random_state=90)
GS = GridSearchCV(rfc, param_grid=param_grid, cv=10)
GS.fit(data.data, data.target)
结果:
2.2.4 调max_features
param_grid = {'max_features':np.arange(5,30,1)}
rfc = RandomForestClassifier(n_estimators=39,random_state=90)
GS = GridSearchCV(rfc,param_grid,cv=10)
GS.fit(data.data,data.target)
结果:
综合2.2.3和2.2.4的结果,说明在调整完n_estimators为39之后,模型就已经达到最优状态了,无需继续调参了。
【PS】这是我看看sklearn菜菜的视频学习笔记~
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)