Shafayat__

Untitled

Nov 7th, 2023
742
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.98 KB | Source Code | 0 0
  1. import numpy as np
  2.  
  3. def knn_predict(X_train, y_train, X_test, k=9):
  4.     predictions = []
  5.     for x in X_test:
  6.         distances = [np.linalg.norm(x - x_train) for x_train in X_train]
  7.         print("Distances: ", distances)
  8.         sorted_points = np.argsort(distances)[:k]
  9.         print("Sorted Distance Points: ", sorted_points)
  10.         k_nearest_labels = [y_train[i] for i in sorted_points]
  11.         print("Nearest Labels: ", k_nearest_labels)
  12.         common_labels = np.bincount(k_nearest_labels).argmax()
  13.         print("Common Label: ", common_labels)
  14.         predictions.append(common_labels)
  15.         print("Predictions: ", predictions)
  16.     return np.array(predictions)
  17.  
  18. 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]])
  19. y_train = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1])
  20. X_test = np.array([[2.5, 1]])
  21.  
  22. predictions = knn_predict(X_train, y_train, X_test, k=9)
  23.  
  24. print("Class for new data point is:", predictions[0])
  25.  
  26.  
  27.  
  28.  
Advertisement
Add Comment
Please, Sign In to add comment