69 lines
2.4 KiB
Java
Executable File
69 lines
2.4 KiB
Java
Executable File
package machine_learning.nearest_neighbour;
|
|
|
|
import machine_learning.DataClass;
|
|
import machine_learning.MachineLearning;
|
|
import machine_learning.Vector;
|
|
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
import java.util.Random;
|
|
import java.util.stream.Collectors;
|
|
import java.util.stream.Stream;
|
|
|
|
public class KNearestNeighbour implements MachineLearning {
|
|
private final DistanceFunction distanceFunction;
|
|
private final int k;
|
|
private List<Vector> positives;
|
|
private List<Vector> negatives;
|
|
|
|
public KNearestNeighbour(final DistanceFunction distanceFunction) {
|
|
this(distanceFunction, 1);
|
|
}
|
|
|
|
public KNearestNeighbour(final DistanceFunction distanceFunction, final int k) {
|
|
this.distanceFunction = distanceFunction;
|
|
this.k = k;
|
|
}
|
|
|
|
@Override
|
|
public void learn(final List<Vector> positives, final List<Vector> negatives) {
|
|
this.positives = positives;
|
|
this.negatives = negatives;
|
|
}
|
|
|
|
@Override
|
|
public DataClass classify(final Vector toClassify) {
|
|
final var nearestNeighbours = this.nearestNeighbours(
|
|
Stream.concat(this.positives.stream(), this.negatives.stream())
|
|
.collect(Collectors.toList()),
|
|
toClassify
|
|
);
|
|
|
|
final var positivesWithNearestNeighboursAmount = nearestNeighbours.stream()
|
|
.filter(this.positives::contains)
|
|
.count();
|
|
|
|
final var negativesWithNearestNeighboursAmount = nearestNeighbours.stream()
|
|
.filter(this.negatives::contains)
|
|
.count();
|
|
|
|
if (positivesWithNearestNeighboursAmount > negativesWithNearestNeighboursAmount) {
|
|
return DataClass.POSITIVE;
|
|
} else if (positivesWithNearestNeighboursAmount < negativesWithNearestNeighboursAmount) {
|
|
return DataClass.NEGATIVE;
|
|
}
|
|
|
|
return new Random().nextBoolean() ? DataClass.POSITIVE : DataClass.NEGATIVE;
|
|
}
|
|
|
|
private List<Vector> nearestNeighbours(final List<Vector> vectors, final Vector vector) {
|
|
return vectors.parallelStream()
|
|
.map(v -> Map.entry(this.distanceFunction.distance(v, vector), v))
|
|
.sorted((e1, e2) -> e1.getKey() >= e2.getKey() ? (e1.getKey().equals(e2.getKey()) ? 0 : 1) : -1)
|
|
.map(Map.Entry::getValue)
|
|
.collect(Collectors.toList())
|
|
.subList(0, this.k);
|
|
}
|
|
}
|
|
|