写一个K近邻的交叉验证选择最优参数的Python代码
时间: 2023-04-07 22:04:13 浏览: 125
Python3实现k近邻算法
以下是K近邻的交叉验证选择最优参数的Python代码:
```python
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.datasets import load_iris
# 加载数据集
iris = load_iris()
X, y = iris.data, iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 定义KNN分类器
knn = KNeighborsClassifier()
# 定义参数范围
param_grid = {'n_neighbors': [3, 5, 7, 9, 11]}
# 使用网格搜索进行交叉验证选择最优参数
grid_search = GridSearchCV(knn, param_grid, cv=5)
grid_search.fit(X_train, y_train)
# 输出最优参数和最优得分
print("Best parameters: {}".format(grid_search.best_params_))
print("Best cross-validation score: {:.2f}".format(grid_search.best_score_))
```
希望这个代码能够帮到你!
阅读全文