Skip to content

Commit 5e3b845

Browse files
Copilotsiriak
andcommitted
Fix non-deterministic tie-breaking in KNN algorithm
Co-authored-by: siriak <[email protected]>
1 parent 023fb50 commit 5e3b845

File tree

1 file changed

+2
-2
lines changed

1 file changed

+2
-2
lines changed

Algorithms/MachineLearning/KNearestNeighbors.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,9 +98,9 @@ public TLabel Predict(double[] features)
9898
// Majority vote
9999
var labelCounts = distances
100100
.GroupBy(x => x.Label)
101-
.Select(g => new { Label = g.Key, Count = g.Count() })
101+
.Select(g => new { Label = g.Key, Count = g.Count(), MinDistance = g.Min(item => item.Distance) })
102102
.OrderByDescending(x => x.Count)
103-
.ThenBy(x => x.Label?.GetHashCode() ?? 0)
103+
.ThenBy(x => x.MinDistance)
104104
.ToList();
105105

106106
return labelCounts.First().Label;

0 commit comments

Comments
 (0)