Reformat code

This commit is contained in:
niklas committed 2026-11-12 13:52:04 +01:00
1 parent 51c12cc0ea
commit 60c654936a
31 files changed
+262 -466

No files matched your search

@@ -10,36 +10,29 @@ import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class KNearestNeighbour implements MachineLearning
{
public class KNearestNeighbour implements MachineLearning {
private final DistanceFunction distanceFunction;
private final int k;
private List<Vector> positives;
private List<Vector> negatives;
private final DistanceFunction distanceFunction;
private final int k;
public KNearestNeighbour(final DistanceFunction distanceFunction)
{
public KNearestNeighbour(final DistanceFunction distanceFunction) {
this(distanceFunction, 1);
}
public KNearestNeighbour(final DistanceFunction distanceFunction, final int k)
{
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)
{
public void learn(final List<Vector> positives, final List<Vector> negatives) {
this.positives = positives;
this.negatives = negatives;
}
@Override
public DataClass classify(final Vector toClassify)
{
public DataClass classify(final Vector toClassify) {
final var nearestNeighbours = this.nearestNeighbours(
Stream.concat(this.positives.stream(), this.negatives.stream())
.collect(Collectors.toList()),
@@ -54,20 +47,16 @@ public class KNearestNeighbour implements MachineLearning
.filter(this.negatives::contains)
.count();
if (positivesWithNearestNeighboursAmount > negativesWithNearestNeighboursAmount)
{
if (positivesWithNearestNeighboursAmount > negativesWithNearestNeighboursAmount) {
return DataClass.POSITIVE;
}
else if (positivesWithNearestNeighboursAmount < negativesWithNearestNeighboursAmount)
{
} 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)
{
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)