Implement the K-Nearest Neighbors (KNN) algorithm for classification. Given training data with labels, classify a new point by finding its K closest neighbors and returning the majority label.
import numpy as np
from collections import Counter
from typing import List
def knn_classify(X_train: np.ndarray, y_train: np.ndarray,
X_query: np.ndarray, k: int = 3) -> List:
predictions = []
for query in X_query:
distances = np.sqrt(np.sum((X_train - query) ** 2, axis=1))
nearest_indices = np.argsort(distances)[:k]
nearest_labels = y_train[nearest_indices].tolist()
counts = Counter(nearest_labels)
predictions.append(counts.most_common(1)[0][0])
return predictions