amirTamer commited on
Commit
4604662
·
1 Parent(s): 8b4d0d5
KNNMulti.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from collections import Counter
3
+
4
+
5
+ class CustomKNN:
6
+ def __init__(self, k=5, weights="distance"):
7
+ self.k = k
8
+ self.weights = weights
9
+
10
+ def fit(self, X, y):
11
+ self.X_train = np.array(X)
12
+ self.y_train = np.array(y)
13
+
14
+ def predict(self, X_test):
15
+ return np.array([self._predict_single(x) for x in np.array(X_test)])
16
+
17
+ def _predict_single(self, x_test):
18
+ distances = np.sqrt(np.sum((self.X_train - x_test) ** 2, axis=1))
19
+ k_indices = np.argsort(distances)[:self.k]
20
+ k_nearest_labels = self.y_train[k_indices]
21
+
22
+ if self.weights == "distance":
23
+ k_distances = distances[k_indices]
24
+ vote_weights = 1.0 / (k_distances + 1e-5)
25
+ class_votes = {}
26
+ for label, weight in zip(k_nearest_labels, vote_weights):
27
+ class_votes[label] = class_votes.get(label, 0) + weight
28
+ return max(class_votes, key=class_votes.get)
29
+
30
+ return Counter(k_nearest_labels).most_common(1)[0][0]
__pycache__/KNNMulti.cpython-313.pyc ADDED
Binary file (2.3 kB). View file
 
__pycache__/app.cpython-313.pyc ADDED
Binary file (10.2 kB). View file
 
app.py CHANGED
@@ -3,7 +3,7 @@ import numpy as np
3
  from skimage.feature import hog
4
  import cv2
5
  import pickle
6
- from KNN import CustomKNN
7
 
8
 
9
 
@@ -31,10 +31,9 @@ def build_knn_from_pca_package(package):
31
  print(f"knn_pca.pkl is missing keys: {sorted(missing_keys)}")
32
  return None
33
 
34
- return CustomKNN(k=package["best_k"], weights=package["weights"]).fit(
35
- package["X_train"],
36
- package["y_train"]
37
- )
38
 
39
  gnb_package = load_pickle_file("gnb_digit6_package.pkl")
40
  pca_multi = load_pickle_file("pcaMulti.pkl")
 
3
  from skimage.feature import hog
4
  import cv2
5
  import pickle
6
+ from KNNMulti import CustomKNN as MultimodeKNN
7
 
8
 
9
 
 
31
  print(f"knn_pca.pkl is missing keys: {sorted(missing_keys)}")
32
  return None
33
 
34
+ knn = MultimodeKNN(k=package["best_k"], weights=package["weights"])
35
+ knn.fit(package["X_train"], package["y_train"])
36
+ return knn
 
37
 
38
  gnb_package = load_pickle_file("gnb_digit6_package.pkl")
39
  pca_multi = load_pickle_file("pcaMulti.pkl")