The k-Nearest Neighbors (k-NN) algorithm is one of the most straightforward machine learning algorithms. It falls under the category of instance-based learning, where the function is approximated locally, and all calculations are postponed until the prediction phase. In the k-NN algorithm, the result is either class membership for classification tasks or an average of values for regression tasks. Classification is determined by a majority vote of the neighboring instances, with the object being assigned to the class that appears most frequently among its k nearest neighbors. Now, let’s look at a basic implementation in Python using the Euclidean distance as the distance measure. from collections import Counter def euclidean_distance ( point1 , point2 ) : return sum ( ( a - b ) ** 2 for a , b in zip ( point1 , point2 ) ) ** 0.5 def k_nearest_neighbors ( data , query , k , distance_fn ) : neighbor_distances_and_indices = [ ] for index , example in enumerate ( data ) : distance = distance_fn ( example [ : - 1 ] , query ) neighbor_distances_and_indices . append ( ( distance , index ) ) sorted_neighbor_distances_and_indices = sorted ( neighbor_distances_and_indices ) k_nearest_distances_and_indices = sorted_neighbor_distances_and_indices [ : k ] k_nearest_labels = [ data [ i ] [ - 1 ] for distance , i in k_nearest_distances_and_indices ] return k , Counter ( k_nearest_labels ) . most_common ( 1 ) [ 0 ] [ 0 ] The above code provides an implementation of the k-NN algorithm from scratch. The k_nearest_neighbors function computes the Euclidean distance between the query example and each example in the dataset, sorts these distances, selects the top k nearest, and conducts a majority vote on their labels. The Counter class is utilized to count hashable objects in the form of (label, count).