Advertisement
toweber

knn_aula_p2

Sep 17th, 2021
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.06 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.  
  6. X = [ [2.0,1.5], [1.0,1.0], [1.0,3.0], [0.8,2.2], [3.0,1.0], [0.4,2.0], [1.2,1.2]  ]
  7. Y = [ 0, 0, 1, 1, 0, 1, 1 ]
  8.  
  9. X = np.array(X)
  10. Y = np.array(Y)
  11.  
  12. clf = neighbors.KNeighborsClassifier(n_neighbors=1)
  13.  
  14. clf = clf.fit(X, Y)
  15.  
  16.  
  17. #****************
  18. # Plot
  19. # baseado em https://scikit-learn.org/stable/auto_examples/neighbors/plot_classification.html
  20. #****************
  21. step_size = 0.01
  22. # encontrando os limites
  23. x_min, x_max = X[:, 0].min(), X[:, 0].max()
  24. y_min, y_max = X[:, 1].min(), X[:, 1].max()
  25.  
  26. x_min, x_max = x_min-abs(0.1*x_min), x_max+abs(0.1*x_max)
  27. y_min, y_max = y_min-abs(0.1*y_min), y_max+abs(0.1*y_max)
  28.  
  29.  
  30. xx, yy = np.meshgrid(np.arange(x_min, x_max, step_size), np.arange(y_min, y_max, step_size))
  31.  
  32. Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
  33.  
  34. Z = Z.reshape(xx.shape)
  35.  
  36. plt.figure()
  37. plt.pcolormesh(xx, yy, Z, cmap='Set3')
  38.  
  39. # plot training points
  40. plt.scatter(X[:, 0], X[:, 1], c=Y, edgecolor='k', s=20, cmap='Set3')
  41.  
  42. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement