Advertisement
Guest User

Untitled

a guest
Jul 16th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. import threading
  2. from queue import Queue
  3. from collections import Counter
  4.  
  5. import numpy as np
  6. from matplotlib import style, pyplot as plt
  7.  
  8.  
  9. datasets = {
  10. 'red': [[1, 2], [3, 4], [3, 2], [1, 0]],
  11. 'green': [[7, 6], [5, 7], [6, 5], [5, 6]],
  12. 'blue': [[9, 8], [9, 7], [8, 8], [9, 9]]
  13. }
  14.  
  15. predict = [[1, 2], [5, 3], [5, 4], [4, 3],
  16. [7, 9], [7, 5], [3, 6], [9, 7],
  17. [6, 8], [9, 2], [3, 0], [7, 2],
  18. [2, 2], [1, 2], [4, 2], [4, 4],
  19. [5, 9], [2, 5], [6, 4], [8, 7],
  20. [4, 5]]
  21.  
  22. q = Queue()
  23. lock = threading.Lock()
  24. results = []
  25.  
  26. def kNearestNeighbors(data, prediction, k=5):
  27. distances = []
  28. for y in data:
  29. for x in data[y]:
  30. euclidean_dist = np.linalg.norm(np.array(x) - np.array(prediction))
  31. distances.append([euclidean_dist, y])
  32. rank = [n[1] for n in sorted(distances)[:k]]
  33. result = Counter(rank).most_common(1)[0][0]
  34. return result
  35.  
  36.  
  37. def threader():
  38. while True:
  39. features = q.get()
  40. with lock: # Acquire lock.
  41. # Make prediction.
  42. result = kNearestNeighbors(datasets, features)
  43. results.append((features, result))
  44. # Notify that we're done with this lock.
  45. q.task_done()
  46.  
  47. if __name__ == '__main__':
  48. # Create workers.
  49. for _ in range(60):
  50. t = threading.Thread(target=threader)
  51. t.daemon = True
  52. t.start()
  53.  
  54. # Put workers in the queue.
  55. for p in predict:
  56. q.put(p)
  57.  
  58. # Wait for all workers to finish work.
  59. q.join()
  60.  
  61. # Plot the dataset.
  62. [[plt.scatter(f[0], f[1], color=g, s=50)
  63. for f in datasets[g]]
  64. for g in datasets]
  65.  
  66. # Visualize predictions.
  67. print(results)
  68. [plt.scatter(ans[0][0], ans[0][1],
  69. color=ans[1], s=50, marker='*')
  70. for ans in results]
  71.  
  72. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement