Spaces:
Sleeping
Sleeping
shawerma
Browse files- KNNMulti.py +0 -30
KNNMulti.py
DELETED
|
@@ -1,30 +0,0 @@
|
|
| 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]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|