Java: k-nearest-neighbors classification
k-nearest neighbours is a simple classifier with no training phase. To classify a new point it finds the k training points closest to it, usually by Euclidean distance, and predicts the most common label among them.
Java
import java.util.*;
class Main {
static double[][] points = {{1, 1}, {1, 2}, {2, 1}, {6, 6}, {7, 6}, {6, 7}};
static String[] labels = {"A", "A", "A", "B", "B", "B"};
static double dist(double[] a, double[] b) {
return Math.hypot(a[0] - b[0], a[1] - b[1]);
}
static Map<String, Integer> classify(double[] query, int k) {
Integer[] order = {0, 1, 2, 3, 4, 5};
Arrays.sort(order, Comparator.comparingDouble(i -> dist(points[i], query)));
Map<String, Integer> votes = new TreeMap<>();
for (int i = 0; i < k; i++) {
votes.merge(labels[order[i]], 1, Integer::sum);
}
return votes;
}
public static void main(String[] args) {
System.out.println("near (5,5): " + classify(new double[] {5, 5}, 3));
System.out.println("near (2,2): " + classify(new double[] {2, 2}, 3));
System.out.println("near (3,3) with k=5: " + classify(new double[] {3, 3}, 5));
}
}