This is an automated email from the ASF dual-hosted git repository. asf-gitbox-commits pushed a commit to branch geoapi-4.0 in repository https://gitbox.apache.org/repos/asf/sis.git
commit 5bdce224faf979ae0352d964e81c765ea7925c35 Author: jsorel <[email protected]> AuthorDate: Fri Nov 27 09:25:11 2026 +0100 feat(Math): add NDArrays.kMeans --- .../main/org/apache/sis/maths/NDArrays.java | 66 ++++++++++++++++++++++ .../test/org/apache/sis/maths/NDArraysTest.java | 12 ++++ 2 files changed, 78 insertions(+) diff --git a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/maths/NDArrays.java b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/maths/NDArrays.java index 95a3661a18..1b01493814 100644 --- a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/maths/NDArrays.java +++ b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/maths/NDArrays.java @@ -441,6 +441,72 @@ public final class NDArrays { return groups.stream().map((indices) -> subset(array, indices)).toList(); } + /** + * Groups the tuples of the given array in clusters with the k-means algorithm, and returns the cluster means. + * Each tuple belongs to the cluster of the nearest mean, and each mean is the average of the tuples of its cluster. + * + * <ul> + * <li>The initial means are the means of the {@linkplain #medianCut(Array, int) median cut} groups, + * so the result is the same for the same input.</li> + * <li>Fewer means are returned if there are not enough distinct tuples.</li> + * <li>The iterations stop early when no tuple changes of cluster.</li> + * </ul> + * + * @param array the tuples to cluster. + * @param count the number of clusters wanted. + * @param maxIterations the maximal number of iterations. + * @return the means of the clusters, in double precision. + * + * @see "https://en.wikipedia.org/wiki/K-means_clustering" + */ + public static Array kMeans(final Array array, final int count, final int maxIterations) { + final Vector<?>[] means = medianCut(array, count).stream().map(NDArrays::mean).toArray(Vector<?>[]::new); + final int[] clusters = new int[Math.toIntExact(array.getLength())]; + Arrays.fill(clusters, -1); + for (int iteration = 0; iteration < maxIterations; iteration++) { + final Vector<?>[] sums = new Vector<?>[means.length]; + final long[] sizes = new long[means.length]; + boolean changed = false; + final Cursor cursor = array.cursor(); + while (cursor.next()) { + final Vector<?> tuple = cursor.getSamples(); + int nearest = 0; + for (int m = 1; m < means.length; m++) { + if (tuple.distanceSquare(means[m]) < tuple.distanceSquare(means[nearest])) { + nearest = m; + } + } + final int index = Math.toIntExact(cursor.coordinate()); + changed |= (clusters[index] != nearest); + clusters[index] = nearest; + sums[nearest] = (sums[nearest] == null) ? tuple.copy(DataType.DOUBLE) : sums[nearest].add(tuple); + sizes[nearest]++; + } + if (!changed) { + break; + } + for (int m = 0; m < means.length; m++) { + if (sizes[m] != 0) { + means[m] = sums[m].scale(1.0 / sizes[m]); + } + } + } + return of(Arrays.asList(means), array.getSampleSystem(), DataType.DOUBLE); + } + + /** + * Returns the average of the tuples of the given array, which shall not be empty. + */ + private static Vector<?> mean(final Array array) { + Vector<?> sum = null; + final Cursor cursor = array.cursor(); + while (cursor.next()) { + final Vector<?> tuple = cursor.getSamples(); + sum = (sum == null) ? tuple.copy(DataType.DOUBLE) : sum.add(tuple); + } + return sum.scale(1.0 / array.getLength()); + } + /** * Sorts the given tuple indices by their value on the given axis and splits them at the median. * Equal values are kept on the same side. The values shall not be all equal. diff --git a/incubator/src/org.apache.sis.geometry/test/org/apache/sis/maths/NDArraysTest.java b/incubator/src/org.apache.sis.geometry/test/org/apache/sis/maths/NDArraysTest.java index 7f3b985e6b..d69d95c150 100644 --- a/incubator/src/org.apache.sis.geometry/test/org/apache/sis/maths/NDArraysTest.java +++ b/incubator/src/org.apache.sis.geometry/test/org/apache/sis/maths/NDArraysTest.java @@ -174,4 +174,16 @@ public class NDArraysTest { assertArrayEquals(new double[] {6,5}, groups.get(1).toArrayDouble()); assertTrue(NDArrays.medianCut(NDArrays.of(2, new double[0]), 4).isEmpty()); } + + /** + * Tests {@link NDArrays#kMeans(Array, int, int)}. The median cut gives the initial groups {0 1} and {2 3 100}, + * then the values 2 and 3 move to the cluster of the first mean. + */ + @Test + public void testKMeans() { + final Array array = NDArrays.of(1, 0.0, 1, 2, 3, 100); + assertArrayEquals(new double[] {0.5, 35}, NDArrays.kMeans(array, 2, 0).toArrayDouble()); + assertArrayEquals(new double[] {1.5, 100}, NDArrays.kMeans(array, 2, 10).toArrayDouble()); + assertArrayEquals(new double[] {0.5, 0.5, 10.5, 0.5}, NDArrays.kMeans(twoClusters(), 2, 10).toArrayDouble()); + } }
