| 21 | |
| 22 | |
| 23 | class KNN: |
| 24 | def __init__( |
| 25 | self, |
| 26 | train_data: np.ndarray[float], |
| 27 | train_target: np.ndarray[int], |
| 28 | class_labels: list[str], |
| 29 | ) -> None: |
| 30 | """ |
| 31 | Create a kNN classifier using the given training data and class labels |
| 32 | """ |
| 33 | self.data = zip(train_data, train_target) |
| 34 | self.labels = class_labels |
| 35 | |
| 36 | @staticmethod |
| 37 | def _euclidean_distance(a: np.ndarray[float], b: np.ndarray[float]) -> float: |
| 38 | """ |
| 39 | Calculate the Euclidean distance between two points |
| 40 | >>> KNN._euclidean_distance(np.array([0, 0]), np.array([3, 4])) |
| 41 | 5.0 |
| 42 | >>> KNN._euclidean_distance(np.array([1, 2, 3]), np.array([1, 8, 11])) |
| 43 | 10.0 |
| 44 | """ |
| 45 | return float(np.linalg.norm(a - b)) |
| 46 | |
| 47 | def classify(self, pred_point: np.ndarray[float], k: int = 5) -> str: |
| 48 | """ |
| 49 | Classify a given point using the kNN algorithm |
| 50 | >>> train_X = np.array( |
| 51 | ... [[0, 0], [1, 0], [0, 1], [0.5, 0.5], [3, 3], [2, 3], [3, 2]] |
| 52 | ... ) |
| 53 | >>> train_y = np.array([0, 0, 0, 0, 1, 1, 1]) |
| 54 | >>> classes = ['A', 'B'] |
| 55 | >>> knn = KNN(train_X, train_y, classes) |
| 56 | >>> point = np.array([1.2, 1.2]) |
| 57 | >>> knn.classify(point) |
| 58 | 'A' |
| 59 | """ |
| 60 | # Distances of all points from the point to be classified |
| 61 | distances = ( |
| 62 | (self._euclidean_distance(data_point[0], pred_point), data_point[1]) |
| 63 | for data_point in self.data |
| 64 | ) |
| 65 | |
| 66 | # Choosing k points with the shortest distances |
| 67 | votes = (i[1] for i in nsmallest(k, distances)) |
| 68 | |
| 69 | # Most commonly occurring class is the one into which the point is classified |
| 70 | result = Counter(votes).most_common(1)[0][0] |
| 71 | return self.labels[result] |
| 72 | |
| 73 | |
| 74 | if __name__ == "__main__": |
no outgoing calls
no test coverage detected