from sklearn import datasets
#导入鸢尾花数据集
iris = datasets.load_iris()
x = iris.data
y = iris.target
#分配测试集和训练集
from sklearn.model_selection import train_test_split
x_train, x_test,y_train, y_test = train_test_split(x,y,test_size = 0.2)
from sklearn.neighbors import KNeighborsClassifier
#传入参数
param_grid = [
{
'weights':['uniform'],
'n_neighbors':[i for i in range(1,11)]
},
{
'weights':['distance'],
'n_neighbors':[i for i in range(1,11)],
'p':[i for i in range(1,6)]
}
]
from sklearn.model_selection import GridSearchCV
knn_clf = KNeighborsClassifier()
# n_jobs=-1使用所有线程
grid_search = GridSearchCV(knn_clf,param_grid,n_jobs=-1,verbose=2)
grid_search.fit(x_train,y_train)
#打印最佳参数
print(grid_search.best_params_)
print(grid_search.best_score_)
print(grid_search.best_estimator_)
K近邻算法--鸢尾花数据集
最新推荐文章于 2022-07-24 23:58:38 发布