CJamie

knn

Mar 23rd, 2022 (edited)
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.65 KB | None | 0 0
  1. """1. KNN on Iris Datset.ipynb
  2.  
  3. from sklearn.datasets import load_iris
  4.  
  5. #Create bunch object containing iris dataset and its attributes.
  6. iris = load_iris()
  7.  
  8.  
  9. X = iris.data
  10. y = iris.target
  11.  
  12. from sklearn.cross_validation import train_test_split
  13. X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=4)
  14.  
  15. from sklearn.neighbors import KNeighborsClassifier
  16.  
  17. from sklearn import metrics
  18. #Try running from k=1 through 25 and record testing accuracy
  19. k_range = range(1,26)
  20. scores = {}
  21. scores_list = []
  22. for k in k_range:
  23.        knn = KNeighborsClassifier(n_neighbors=k)
  24.        knn.fit(X_train,y_train)
  25.        y_pred=knn.predict(X_test)
  26.        scores[k] = metrics.accuracy_score(y_test,y_pred)
  27.        scores_list.append(metrics.accuracy_score(y_test,y_pred))
  28.  
  29. #Testing accuracy for each value of K
  30. scores
  31.  
  32. # Commented out IPython magic to ensure Python compatibility.
  33.  
  34. # %matplotlib inline
  35. import matplotlib.pyplot as plt
  36.  
  37. #plot the relationship between K and the testing accuracy
  38. plt.plot(k_range,scores_list)
  39. plt.xlabel('Value of K for KNN')
  40. plt.ylabel('Testing Accuracy')
  41.  
  42. """### K values with 3 to 19 has the same accuracy which is 96.66, so we can use any one value from that, i choose K as 5 and train the model with full training data"""
  43.  
  44. knn = KNeighborsClassifier(n_neighbors=5)
  45. knn.fit(X,y)
  46.  
  47. #0 = setosa, 1=versicolor, 2=virginica
  48. classes = {0:'setosa',1:'versicolor',2:'virginica'}
  49.  
  50. #Making prediction on some unseen data
  51. #predict for the below two random observations
  52. x_new = [[3,4,5,2],
  53.          [5,4,2,2]]
  54. y_predict = knn.predict(x_new)
  55.  
  56. print(classes[y_predict[0]])
  57. print(classes[y_predict[1]])
Add Comment
Please, Sign In to add comment