current position:Home>KNN algorithm can not come up with the best model selection

KNN algorithm can not come up with the best model selection

2022-02-02 12:56:29 CSDN Q & A

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

1. Get data set

iris = load_iris()

2. Basic data processing

2.1 Data segmentation

x_train,x_test,y_train,y_test=train_test_split(iris.data,iris.target,random_state=22,test_size=0.2)

3. Feature Engineering

3.1 Instantiate a converter

transfer = StandardScaler()

3.2 call fit_transform Method

x_train=transfer.fit_transform(x_train)
x_test=transfer.fit_transform(x_test)

4. machine learning ( model training )

4.1 Instantiate an estimator

estimator = KNeighborsClassifier(n_neighbors=5)

4.2 Call cross validation grid search model

param_grid={'n_neighbors':[1,3,5,7,9]}
estimator = GridSearchCV(estimator,param_grid=param_grid,cv=10,n_jobs=1)##cv How much discount

4.3 model training

estimator.fit(x_train,y_train)

5. Model to evaluate

5.1 Output predicted value

y_pre=estimator.predict(x_test)
print(' The forecast is :\n',y_pre)

5.2 Output accuracy

ret = estimator.score(x_test,y_test)
print(' The accuracy is :\n',ret)

5.3 Other evaluation indicators

print(' The best model :\n',estimator.best_estimator_)
print(' Best outcome :\n',estimator.best_score_)
print(' Overall model results :\n',estimator.cv_results_)
It turns out that :

The forecast is :
[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]
The accuracy is :
0.7666666666666667
The best model :
KNeighborsClassifier()
Best outcome :
0.9666666666666666

The best model doesn't jump out of anything in parentheses !!pycharm The same is true in !!

copyright notice
author[CSDN Q & A],Please bring the original link to reprint, thank you.
https://en.primo.wiki/2022/02/202202021256278319.html

Random recommended