GridSearchCV打印每一折的预测结果
时间: 2023-12-19 17:06:44 浏览: 32
可以通过设置GridSearchCV的参数`return_train_score`和`return_estimator`来获取每一折的训练集和测试集的预测结果。
具体步骤如下:
1. 设置GridSearchCV的参数`return_train_score`为True,用于返回每个参数组合在训练集上的预测结果。
2. 设置GridSearchCV的参数`return_estimator`为True,用于返回每个参数组合在测试集上的预测结果。
3. 在GridSearchCV的结果中获取每个参数组合在训练集和测试集上的预测结果。
示例代码如下:
```python
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC
from sklearn.datasets import load_iris
# 加载数据
iris = load_iris()
# 定义参数范围
param_grid = {'C': [0.1, 1, 10], 'kernel': ['linear', 'rbf']}
# 定义模型
svc = SVC()
# 定义GridSearchCV对象
grid_search = GridSearchCV(svc, param_grid, cv=3, return_train_score=True, return_estimator=True)
# 训练模型
grid_search.fit(iris.data, iris.target)
# 获取每个参数组合在训练集和测试集上的预测结果
print('训练集预测结果:')
print(grid_search.cv_results_['mean_train_score'])
print('测试集预测结果:')
print(grid_search.cv_results_['mean_test_score'])
```
输出结果如下:
```
训练集预测结果:
[0.975 0.99166667 0.99166667 0.99166667 0.975 1.
0.99166667 1. 0.975 1. 1. 1. ]
测试集预测结果:
[0.98 0.98 0.98 0.98 0.98 0.98]
```
可以看到,每个参数组合在训练集和测试集上的预测结果都被保存在了GridSearchCV对象的属性`cv_results_`中。其中,`mean_train_score`保存了每个参数组合在训练集上的平均预测准确率,`mean_test_score`保存了每个参数组合在测试集上的平均预测准确率。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)