网格搜索python代码
时间: 2023-07-22 13:10:59 浏览: 34
下面是一个简单的网格搜索的 Python 代码实现:
```python
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
# 定义参数搜索范围
param_grid = {
'n_estimators': [50, 100, 200],
'max_depth': [10, 20, 30],
'min_samples_split': [2, 5, 10]
}
# 定义模型
rf = RandomForestClassifier()
# 定义网格搜索
grid_search = GridSearchCV(estimator=rf,
param_grid=param_grid,
cv=5,
n_jobs=-1,
verbose=2)
# 训练模型
grid_search.fit(X_train, y_train)
# 输出最佳模型的参数和得分
print("Best parameters: ", grid_search.best_params_)
print("Best score: ", grid_search.best_score_)
```
上面的代码定义了一个参数搜索范围,一个随机森林模型和一个网格搜索对象。然后,使用训练数据拟合网格搜索对象。最后输出最佳模型的参数和得分。