nearestneighbors.py 2.4 KB

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