Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import threading
- from queue import Queue
- from collections import Counter
- import numpy as np
- from matplotlib import style, pyplot as plt
- datasets = {
- 'red': [[1, 2], [3, 4], [3, 2], [1, 0]],
- 'green': [[7, 6], [5, 7], [6, 5], [5, 6]],
- 'blue': [[9, 8], [9, 7], [8, 8], [9, 9]]
- }
- predict = [[1, 2], [5, 3], [5, 4], [4, 3],
- [7, 9], [7, 5], [3, 6], [9, 7],
- [6, 8], [9, 2], [3, 0], [7, 2],
- [2, 2], [1, 2], [4, 2], [4, 4],
- [5, 9], [2, 5], [6, 4], [8, 7],
- [4, 5]]
- q = Queue()
- lock = threading.Lock()
- results = []
- def kNearestNeighbors(data, prediction, k=5):
- distances = []
- for y in data:
- for x in data[y]:
- euclidean_dist = np.linalg.norm(np.array(x) - np.array(prediction))
- distances.append([euclidean_dist, y])
- rank = [n[1] for n in sorted(distances)[:k]]
- result = Counter(rank).most_common(1)[0][0]
- return result
- def threader():
- while True:
- features = q.get()
- with lock: # Acquire lock.
- # Make prediction.
- result = kNearestNeighbors(datasets, features)
- results.append((features, result))
- # Notify that we're done with this lock.
- q.task_done()
- if __name__ == '__main__':
- # Create workers.
- for _ in range(60):
- t = threading.Thread(target=threader)
- t.daemon = True
- t.start()
- # Put workers in the queue.
- for p in predict:
- q.put(p)
- # Wait for all workers to finish work.
- q.join()
- # Plot the dataset.
- [[plt.scatter(f[0], f[1], color=g, s=50)
- for f in datasets[g]]
- for g in datasets]
- # Visualize predictions.
- print(results)
- [plt.scatter(ans[0][0], ans[0][1],
- color=ans[1], s=50, marker='*')
- for ans in results]
- plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement