nearestneighbors.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. from sklearn.neighbors import NearestNeighbors, KNeighborsClassifier
  2. import numpy as np
  3. import sys
  4. from Vector import *
  5. def main():
  6. # a test of this method using an arbitrarily generated list of 5 vectors with 3 features each
  7. # nearestNeighbors([[1, 1, 0], [1, 0, 0], [0, 0, 0], [0, 5, 5]], [[1, 1, 4]])
  8. print(len(sys.argv))
  9. if len(sys.argv) != 5:
  10. print("Usage: nearestneighbors.py datafile.bin classificationsfile.bin testdatafile.bin -(p/e)")
  11. exit()
  12. data = readPickledData(sys.argv[1])
  13. classifcations = readPickledData(sys.argv[2])
  14. testdata = readPickledData(sys.argv[3])
  15. newdata, newtest = [], []
  16. for d in data:
  17. newdata.append(d.features)
  18. for d in testdata:
  19. newtest.append(d.features)
  20. print(newdata)
  21. print(classifcations)
  22. print(newtest)
  23. kNearestNeighbors(newdata, classifcations, newtest)
  24. # kNearestNeighbors([[1, 1, 0], [1, 0, 0], [0, 0, 0], [0, 5, 5]], ["three", 2, 3, "5"], [[1, 1, 0], [0, 5, 5]])
  25. def kNearestNeighbors(data: list, classifications: list, test_data: list):
  26. kn = KNeighborsClassifier(n_neighbors=2)
  27. kn.fit(data, classifications)
  28. p = kn.predict(test_data)
  29. print("Predictions, matching test_data by index: ")
  30. print(test_data)
  31. print(p)
  32. writestr = "Predictions, matching test_data by index:\n" + str(test_data) + "\n" + str(p)
  33. if sys.argv[4][1] == 'p':
  34. pickle.dump((test_data, p), open("results.bin", "wb"))
  35. else:
  36. with open("results.txt", "w+") as file:
  37. file.write(writestr)
  38. def nearestNeighbors(data: list, test_data: list):
  39. x = np.array(data)
  40. nbrs = NearestNeighbors(n_neighbors=1, algorithm='ball_tree').fit(x)
  41. dist, indicies = nbrs.kneighbors(test_data)
  42. print("Indicies:")
  43. print(indicies)
  44. print("Distances:")
  45. print(dist)
  46. return indicies, dist
  47. if __name__ == '__main__':
  48. main()