K Nearest Neighbour - Jupyter Notebook
K Nearest Neighbour - Jupyter Notebook
In [2]: 1 iris.feature_names
In [3]: 1 iris.target_names
In [4]: 1 df=pd.DataFrame(iris.data,columns=iris.feature_names)
2 df.head()
Out[4]: sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)
In [5]: 1 df.shape
Out[5]: (150, 4)
In [6]: 1 df['target']=iris.target
2 df.head()
Out[6]: sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) target
In [7]: 1 df[df.target==1].head()
Out[7]: sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) target
In [8]: 1 df[df.target==2].head()
Out[8]: sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) target
Out[9]: sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) target flower_name
In [10]: 1 df0=df[:50]
2 df1=df[50:100]
3 df2=df[100:]
In [15]: 1 X=df.drop(['target','flower_name'],axis='columns')
2 y=df.target
In [16]: 1 X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=1)
In [17]: 1 len(X_train)
Out[17]: 120
In [18]: 1 len(X_test)
Out[18]: 30
Create KNN
Out[19]: KNeighborsClassifier()
In [20]: 1 knn.score(X_test,y_test)
Out[20]: 1.0
accuracy 1.00 30
macro avg 1.00 1.00 1.00 30
weighted avg 1.00 1.00 1.00 30
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
In [25]: 1 param_grid=dict(n_neighbors=k_range)
2 print(param_grid)
3
{'n_neighbors': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
28, 29, 30]}
In [29]: 1 print(grid.best_score_)
2 print(grid.best_params_)
3 print(grid.best_estimator_)
0.9800000000000001
{'n_neighbors': 13}
KNeighborsClassifier(n_neighbors=13)
{'n_neighbors': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
28, 29, 30], 'weights': ['uniform', 'distance']}
In [33]: 1 print(grid.best_score_)
2 print(grid.best_params_)
0.9800000000000001
{'n_neighbors': 13, 'weights': 'uniform'}
In [ ]: 1
In [ ]: 1
In [ ]: 1