from scipy.stats import randint random_params = {'n_estimators': randint(low=80, high=200), 'max_features': randint(low=2, high=8)} forset_reg = RandomForestRegressor(random_state=2020) random_search_forest = RandomizedSearchCV(forest_reg, param_distributions=random_params, n_iter=20, scoring='neg_mean_squared_error', cv=5, random_state=2020) random_search_forest.fit(housing_prepares, housing_label) cvrus = random_search_forest.cv_results_ for mean_score, params in zip(cvrus['mean_test_score'], cvrus['params']): print(np.sqrt(-mean_score), params) print('随机搜索下最佳参数', random_search_forest.best_params_) print('随机搜索下最佳评估器', random_search_forest.best_estimator_) 将以上代码用plot绘图
时间: 2024-03-22 12:42:31 浏览: 121
Python错题本:from scipy.misc import imread 报错cannot import name imread 的解决方案
同样,我无法直接绘制图表,但是你可以将不同超参数下的模型得分绘制成图表进行可视化展示。以下是一个示例代码:
```python
import matplotlib.pyplot as plt
import pandas as pd
# 将 cv_results_ 转化为 DataFrame 格式
cvres_df = pd.DataFrame(random_search_forest.cv_results_)
# 提取所需列
cvres_df = cvres_df[['param_n_estimators', 'param_max_features', 'mean_test_score']]
# 将 param_n_estimators 和 param_max_features 转化为数值类型
cvres_df['param_n_estimators'] = cvres_df['param_n_estimators'].astype('int')
cvres_df['param_max_features'] = cvres_df['param_max_features'].astype('int')
# 绘制图表
fig, ax = plt.subplots(figsize=(12, 8))
for n_estimators in range(80, 201, 20):
df = cvres_df[cvres_df['param_n_estimators'] == n_estimators]
ax.plot(df['param_max_features'], np.sqrt(-df['mean_test_score']), label=f'n_estimators={n_estimators}')
ax.set_xlabel('max_features')
ax.set_ylabel('RMSE')
ax.legend()
plt.show()
```
该代码将不同超参数下的模型得分绘制成了一张折线图,横坐标为 max_features,纵坐标为 RMSE。其中,每种颜色代表不同的 n_estimators 值。你可以根据实际情况进行修改和调整。
阅读全文