Advertisement
makispaiktis

ML - Lab 5 - KNN

Oct 19th, 2022 (edited)
844
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.19 KB | None | 1 0
  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. import sklearn
  5.  
  6. # Load data
  7. knndata = pd.read_csv("./knndata.txt")
  8. print("knndata = ")
  9. print(knndata)
  10. print()
  11. X = knndata.loc[:, ["X1", "X2"]]
  12. y = knndata.loc[:, "Y"]
  13.  
  14. # Show data
  15. plt.scatter(X[y == 1].X1, X[y == 1].X2, c="blue", marker="o", label="1")
  16. plt.scatter(X[y == 2].X1, X[y == 2].X2, c="red", marker="+", label="2")
  17. plt.title("Points")
  18. plt.xlabel("X1")
  19. plt.ylabel("X2")
  20. plt.legend()
  21. plt.show()
  22.  
  23. # Classifier kNN
  24. from sklearn.neighbors import KNeighborsClassifier
  25. k = 1
  26. clf = KNeighborsClassifier(n_neighbors=k)
  27. clf = clf.fit(X, y)
  28. # Predict
  29. new_X1 = 0.7
  30. new_X2 = 0.4
  31. new_X = [new_X1, new_X2]
  32. print("k = " + str(k))
  33. print(clf.predict([new_X]))                 # [new], where new = [..., ...]
  34. print(clf.predict_proba([new_X]))           # [new], where new = [..., ...]
  35. print()
  36.  
  37. k = 5
  38. clf = KNeighborsClassifier(n_neighbors=k)
  39. clf = clf.fit(X, y)
  40. # Predict
  41. new_X1 = 0.7
  42. new_X2 = 0.4
  43. new_X = [new_X1, new_X2]
  44. print("k = " + str(k))
  45. print(clf.predict([new_X]))                 # [new], where new = [..., ...]
  46. print(clf.predict_proba([new_X]))           # [new], where new = [..., ...]
  47. print()
  48.  
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement