如何使用GridSearchCV进行参数调优?
时间: 2024-06-15 20:04:54 浏览: 13
GridSearchCV是scikit-learn库中的一个函数,用于系统地遍历多种参数组合,通过交叉验证来确定最佳参数。下面是使用GridSearchCV进行参数调优的步骤:
1. 导入必要的库和模块:
```python
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
```
2. 准备数据集:
```python
# 假设X为特征矩阵,y为目标变量
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
```
3. 定义模型和参数网格:
```python
# 定义模型
model = SVC()
# 定义参数网格
param_grid = {'C': [0.1, 1, 10, 100], 'kernel': ['linear', 'rbf']}
```
4. 创建GridSearchCV对象:
```python
grid_search = GridSearchCV(estimator=model, param_grid=param_grid, cv=5)
```
其中,estimator参数指定了要调优的模型,param_grid参数指定了要搜索的参数组合,cv参数指定了交叉验证的折数。
5. 执行网格搜索:
```python
grid_search.fit(X_train, y_train)
```
6. 查看最佳参数和最佳得分:
```python
best_params = grid_search.best_params_
best_score = grid_search.best_score_
print("Best parameters: ", best_params)
print("Best score: ", best_score)
```
通过以上步骤,你可以使用GridSearchCV进行参数调优,并找到最佳参数组合和对应的模型得分。