以下是一个简单的 Java 实现 K-近邻算法 (KNN) 的示例:
import java.util.ArrayList;
import java.util.List;
class Point {
double[] features;
String label;
Point(double[] features, String label) {
this.features = features;
this.label = label;
}
double distance(Point other) {
double sum = 0;
for (int i = 0; i < features.length; i++) {
sum += Math.pow(features[i] - other.features[i], 2);
}
return Math.sqrt(sum);
}
}
class KNN {
private List<Point> points;
private int k;
KNN(int k) {
this.k = k;
this.points = new ArrayList<>();
}
void fit(List<Point> trainingPoints) {
this.points = trainingPoints;
}
String predict(Point newPoint) {
points.sort((p1, p2) -> Double.compare(p1.distance(newPoint), p2.distance(newPoint)));
List<String> neighborsLabels = new ArrayList<>();
for (int i = 0; i < k; i++) {
neighborsLabels.add(points.get(i).label);
}
return majorityVote(neighborsLabels);
}
private String majorityVote(List<String> labels) {
return labels.stream()
.reduce((label1, label2) -> label1.equals(label2) ? label1 : null)
.orElse(labels.get(0));
}
public static void main(String[] args) {
KNN knn = new KNN(3);
List<Point> trainingData = new ArrayList<>();
trainingData.add(new Point(new double[]{1.0, 2.0}, "A"));
trainingData.add(new Point(new double[]{2.0, 3.0}, "A"));
trainingData.add(new Point(new double[]{3.0, 1.0}, "B"));
trainingData.add(new Point(new double[]{6.0, 5.0}, "B"));
knn.fit(trainingData);
Point newPoint = new Point(new double[]{2.5, 2.5}, null);
String predictedLabel = knn.predict(newPoint);
System.out.println("Predicted Label: " + predictedLabel);
}
}
说明:
- Point 类:表示数据点,包含特征和标签,以及计算距离的方法。
- KNN 类:实现 K-近邻算法,包含训练和预测的方法。
- fit 方法:用于训练模型,接收训练数据。
- predict 方法:接收新的数据点并预测其标签。
- majorityVote 方法:通过投票确定邻居中最常见的标签。
可以根据需求扩展此实现,例如改进投票机制、支持加权投票等。
4o