toweber

knn_aula_p3

Sep 17th, 2021
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.07 KB | None | 0 0
  1. from sklearn import neighbors
  2. from sklearn import datasets
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. import ipdb
  6.  
  7. dataset = datasets.load_breast_cancer()
  8.  
  9. X = dataset.data[:, :2]
  10. Y = dataset.target
  11.  
  12. clf = neighbors.KNeighborsClassifier(n_neighbors=13)
  13.  
  14. clf = clf.fit(X, Y)
  15.  
  16. print(clf.predict([[0.9, 1.1]]))
  17.  
  18.  
  19. #ipdb.set_trace()
  20.  
  21.  
  22. #****************
  23. # Plot
  24. # baseado em https://scikit-learn.org/stable/auto_examples/neighbors/plot_classification.html
  25. #****************
  26. step_size = 0.1
  27. # encontrando os limites
  28. x_min, x_max = X[:, 0].min(), X[:, 0].max()
  29. y_min, y_max = X[:, 1].min(), X[:, 1].max()
  30.  
  31. x_min, x_max = x_min-abs(0.1*x_min), x_max+abs(0.1*x_max)
  32. y_min, y_max = y_min-abs(0.1*y_min), y_max+abs(0.1*y_max)
  33.  
  34.  
  35. xx, yy = np.meshgrid(np.arange(x_min, x_max, step_size), np.arange(y_min, y_max, step_size))
  36.  
  37. Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
  38.  
  39. Z = Z.reshape(xx.shape)
  40.  
  41. plt.figure()
  42. plt.pcolormesh(xx, yy, Z, cmap='Set3')
  43.  
  44. # plot training points
  45. plt.scatter(X[:, 0], X[:, 1], c=Y, edgecolor='k', s=20, cmap='Set3')
  46.  
  47. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment