from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split,GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
iris = load_iris()
x_train,x_test,y_train,y_test=train_test_split(iris.data,iris.target,random_state=22,test_size=0.2)
transfer = StandardScaler()
x_train=transfer.fit_transform(x_train)
x_test=transfer.fit_transform(x_test)
estimator = KNeighborsClassifier(n_neighbors=5)
param_grid={'n_neighbors':[1,3,5,7,9]}
estimator = GridSearchCV(estimator,param_grid=param_grid,cv=10,n_jobs=1)##cv为几折
estimator.fit(x_train,y_train)
y_pre=estimator.predict(x_test)
print('预测值是:\n',y_pre)
ret = estimator.score(x_test,y_test)
print('准确率是:\n',ret)
print('最好的模型:\n',estimator.best_estimator_)
print('最好的结果:\n',estimator.best_score_)
print('整体模型结果:\n',estimator.cv_results_)
结果显示为:
预测值是:
[0 2 1 1 1 1 1 1 1 0 2 1 2 2 0 2 1 1 1 1 0 2 0 1 1 0 1 1 2 1]
准确率是:
0.7666666666666667
最好的模型:
KNeighborsClassifier()
最好的结果:
0.9666666666666666
最好的模型的括号里没有跳出任何东西!!pycharm里也是这样!!