Repository navigation
Expand file tree
/
Copy pathKNN.java
More file actions
74 lines (61 loc) · 2.28 KB
/
Copy pathKNN.java
File metadata and controls
74 lines (61 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.thealgorithms.machinelearning;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class KNN {
public static class DataPoint {
double[] features;
String label;
public DataPoint(double[] features, String label) {
this.features = features;
this.label = label;
}
}
private static class DistancePair {
double distance;
String label;
public DistancePair(double distance, String label) {
this.distance = distance;
this.label = label;
}
}
public static double calculateEuclideanDistance(double[] point1, double[] point2) {
double sum = 0.0;
for (int i = 0; i < point1.length; i++) {
sum += Math.pow(point1[i] - point2[i], 2);
}
return Math.sqrt(sum);
}
public static String classify(List<DataPoint> dataset, double[] queryPoint, int k) {
List<DistancePair> distances = new ArrayList<>();
for (DataPoint p : dataset) {
double dist = calculateEuclideanDistance(p.features, queryPoint);
distances.add(new DistancePair(dist, p.label));
}
distances.sort(Comparator.comparingDouble(d -> d.distance));
List<String> topKLabels = new ArrayList<>();
for (int i = 0; i < Math.min(k, distances.size()); i++) {
topKLabels.add(distances.get(i).label);
}
String bestLabel = null;
int maxCount = -1;
for (String label : topKLabels) {
int count = Collections.frequency(topKLabels, label);
if (count > maxCount) {
maxCount = count;
bestLabel = label;
}
}
return bestLabel;
}
public static void main(String[] args) {
List<DataPoint> trainData = new ArrayList<>();
trainData.add(new DataPoint(new double[] {1.0, 2.0}, "ClassA"));
trainData.add(new DataPoint(new double[] {2.0, 3.0}, "ClassA"));
trainData.add(new DataPoint(new double[] {7.0, 8.0}, "ClassB"));
double[] target = new double[] {1.5, 2.5};
String prediction = classify(trainData, target, 3);
System.out.println("Predicted Category: " + prediction);
}
}