python - 固定随机状态后随机森林的不同结果
问题描述
我有以下代码。我已经设置了随机状态。每次我进行交叉验证时,它都会给我一组新的最优参数。这对我来说没有意义。为什么会这样?
rs = 5
param_range = np.arange(1,150,10,dtype=int)
param_range2 = np.arange(5,20,5,dtype=int)
pipe_steps = [('rfc',RandomForestClassifier())]
check_params = {
'rfc__n_estimators':param_range,
'rfc__max_depth':param_range2
}
pipeline = Pipeline(pipe_steps)
print('-------------------------- CV Start - Fitting training data --------------------------')
for K in [5,8,10]:
create_grid = GridSearchCV(pipeline,param_grid=check_params,cv=KFold(n_splits=K, random_state=rs, shuffle=True))
create_grid.fit(X_train,y_train)
print('********************* Pipeline %d fold CV *********************' % (K))
print(create_grid.best_params_)
print("test score:= %3.2f" % (create_grid.score(X_test,y_test)))
print("CV End")
第一次,我运行代码,它会给我下面
-------------------------- CV Start - Fitting training data --------------------------
********************* Pipeline 5 fold CV *********************
{'rfc__max_depth': 10, 'rfc__n_estimators': 21}
test score:= 0.53
********************* Pipeline 8 fold CV *********************
{'rfc__max_depth': 10, 'rfc__n_estimators': 101}
test score:= 0.61
********************* Pipeline 10 fold CV *********************
{'rfc__max_depth': 5, 'rfc__n_estimators': 81}
test score:= 0.68
CV End
第二次,我运行代码,最优参数改变。
-------------------------- CV Start - Fitting training data --------------------------
********************* Pipeline 5 fold CV *********************
{'rfc__max_depth': 10, 'rfc__n_estimators': 81}
test score:= 0.55
********************* Pipeline 8 fold CV *********************
{'rfc__max_depth': 15, 'rfc__n_estimators': 71}
test score:= 0.53
********************* Pipeline 10 fold CV *********************
{'rfc__max_depth': 15, 'rfc__n_estimators': 81}
test score:= 0.63
CV End
解决方案
为了获得可重现的结果,您必须为代码中涉及随机性的每个操作设置种子。在这里你为GridSearchCV
and做KFold
,但不是为你的RandomForestClassifier
; 你应该把它初始化为
pipe_steps = [('rfc',RandomForestClassifier(random_state=rs))]
推荐阅读
- php - 致命错误:未捕获的错误:在 null 上调用成员函数 format()
- google-cloud-platform - 资源组中的虚拟机,资源需要权限才能访问 BigQuery,如何实现?
- python - 从字典Python中的excel表中获取随机数的行
- python - 有没有办法获得复合条形图(又名堆叠条形图)?
- express - 如何在将文件下载到数据库 mongoDB 之前使用 GridF 调整文件大小
- javascript - 如何在 Tampermonkey JS 脚本中使用 GAPI?我正在尝试将 google sheet API 用于我的 Tampermonkey 脚本
- python - 分类数据框的 Pandas 从长到宽
- javascript - refs 类型脚本错误数组:“RefObject”类型上不存在属性“getBoundingClientRect”
' - amazon-web-services - 在 Parameter Store 中创建存储在同一 Cloudformation 模板中构建的 AMI 的 ImageID 的参数时出错
- webauthn - 为什么浏览器中的 WebAuthn API 将数据从身份验证器重组为 WebAuth 中的依赖方?