Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- def knn_predict(X_train, y_train, X_test, k=9):
- predictions = []
- for x in X_test:
- distances = [np.linalg.norm(x - x_train) for x_train in X_train]
- print("Distances: ", distances)
- sorted_points = np.argsort(distances)[:k]
- print("Sorted Distance Points: ", sorted_points)
- k_nearest_labels = [y_train[i] for i in sorted_points]
- print("Nearest Labels: ", k_nearest_labels)
- common_labels = np.bincount(k_nearest_labels).argmax()
- print("Common Label: ", common_labels)
- predictions.append(common_labels)
- print("Predictions: ", predictions)
- return np.array(predictions)
- X_train = np.array([[1, 2], [1, 3], [2, 3], [1, 4], [2, 4], [2, 1], [3, 1], [3, 1.5], [4, 2], [5, 2]])
- y_train = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1])
- X_test = np.array([[2.5, 1]])
- predictions = knn_predict(X_train, y_train, X_test, k=9)
- print("Class for new data point is:", predictions[0])
Advertisement
Add Comment
Please, Sign In to add comment