This is an automated email from the ASF dual-hosted git repository. aherbert pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/commons-math.git
The following commit(s) were added to refs/heads/master by this push: new 3e72f1ea3 MATH-1651: Ensure neuron distances are returned in a consistent order 3e72f1ea3 is described below commit 3e72f1ea31f4b0ed43e6cb48381f86b95c15f36c Author: aherbert <aherb...@apache.org> AuthorDate: Thu Nov 3 16:42:53 2022 +0000 MATH-1651: Ensure neuron distances are returned in a consistent order Use of the iterator order should be avoided as the underlying collection uses an unspecified iteration order. --- .../neuralnet/sofm/KohonenUpdateActionTest.java | 31 +++++++++++++++------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/commons-math-neuralnet/src/test/java/org/apache/commons/math4/neuralnet/sofm/KohonenUpdateActionTest.java b/commons-math-neuralnet/src/test/java/org/apache/commons/math4/neuralnet/sofm/KohonenUpdateActionTest.java index a445bad43..aaefa130d 100644 --- a/commons-math-neuralnet/src/test/java/org/apache/commons/math4/neuralnet/sofm/KohonenUpdateActionTest.java +++ b/commons-math-neuralnet/src/test/java/org/apache/commons/math4/neuralnet/sofm/KohonenUpdateActionTest.java @@ -68,11 +68,7 @@ public class KohonenUpdateActionTest { // all neuron's features get closer to the input's features. final double[] features = new double[] {0.3}; - final double[] distancesBefore = new double[netSize]; - int count = 0; - for (Neuron n : net) { - distancesBefore[count++] = dist.applyAsDouble(n.getFeatures(), features); - } + final double[] distancesBefore = getDistances(net, dist, features); final Neuron bestBefore = rank.rank(features, 1).get(0); // Initial distance from the best match is larger than zero. @@ -80,11 +76,7 @@ public class KohonenUpdateActionTest { update.update(net, features); - final double[] distancesAfter = new double[netSize]; - count = 0; - for (Neuron n : net) { - distancesAfter[count++] = dist.applyAsDouble(n.getFeatures(), features); - } + final double[] distancesAfter = getDistances(net, dist, features); final Neuron bestAfter = rank.rank(features, 1).get(0); Assert.assertEquals(bestBefore, bestAfter); @@ -96,4 +88,23 @@ public class KohonenUpdateActionTest { Assert.assertTrue(distancesAfter[i] < distancesBefore[i]); } } + + /** + * Gets the distance of each Neuron to the specified features. + * Distances are returned ordered by the Neuron ID. + * + * @param net Network + * @param dist Distance measure + * @param features Feature vector + * @return the distances + */ + private static double[] getDistances(Network net, + DistanceMeasure dist, + double[] features) { + return net.getNeurons() + .stream() + .sorted((a, b) -> Long.compare(a.getIdentifier(), b.getIdentifier())) + .mapToDouble(n -> dist.applyAsDouble(n.getFeatures(), features)) + .toArray(); + } }