π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(contrib): assign KMeans labels using the final centers (#5922)
Devulapalli Naga Sri Vaishnavi636c7dfbadc3
diff --git a/changelog.d/5922.fixed.md b/changelog.d/5922.fixed.mdnew file mode 100644index 000000000..2da559ff6--- /dev/null+++ b/changelog.d/5922.fixed.md@@ -0,0 +1 @@+`KMeans.cluster_assignments` now uses the final cluster centers, matching `predict` on the training data when fitting stops before assignments have converged.diff --git a/kornia/contrib/kmeans.py b/kornia/contrib/kmeans.pyindex fec3c28fe..dcfea4cca 100644--- a/kornia/contrib/kmeans.py+++ b/kornia/contrib/kmeans.py@@ -100,7 +100,8 @@ class KMeans:Returns:A 1D tensor with shape :math:`(N,)`, where ``N`` is the number ofsamples given to :meth:`fit`. Each value is the cluster index- assigned to the corresponding sample.+ nearest to the corresponding sample in the final centers, matching+ :meth:`predict` on the training data even when fitting stops early.Raises:TypeError: If ``fit`` has not been run yet.@@ -212,8 +213,9 @@ class KMeans:if self.max_iterations != 0 and iteration >= self.max_iterations:break- self._final_cluster_assignments = cluster_assignmentself._final_cluster_centers = current_centers+ # The loop's assignments precede its last center update. Reassign once so labels use the returned centers.+ self._final_cluster_assignments = self.predict(X)def predict(self, x: torch.Tensor) -> torch.Tensor:"""Find the cluster center closest to each point in x.diff --git a/tests/contrib/test_kmeans.py b/tests/contrib/test_kmeans.pyindex e38faea76..a9b792222 100644--- a/tests/contrib/test_kmeans.py+++ b/tests/contrib/test_kmeans.py@@ -24,6 +24,51 @@ from testing.base import BaseTesterclass TestKMeans(BaseTester):+ @pytest.mark.parametrize(+ ("tolerance", "max_iterations", "expected_centers", "expected_assignments"),+ [+ (None, 1, [[0.0], [6.0]], [0, 0, 1, 1, 1]),+ (100.0, 100, [[0.0], [6.0]], [0, 0, 1, 1, 1]),+ (1e-4, 100, [[2.0], [9.0]], [0, 0, 0, 1, 1]),+ ],+ )+ def test_final_assignments_match_centers(+ self, device, dtype, tolerance, max_iterations, expected_centers, expected_assignments+ ):+ x = torch.tensor([[0.0], [2.0], [4.0], [8.0], [10.0]], device=device, dtype=dtype)+ centers = torch.tensor([[0.0], [3.0]], device=device, dtype=dtype)+ kmeans = kornia.contrib.KMeans(2, centers, tolerance=tolerance, max_iterations=max_iterations)++ kmeans.fit(x)++ self.assert_close(kmeans.cluster_centers, x.new_tensor(expected_centers))+ expected = torch.tensor(expected_assignments, device=device, dtype=torch.long)+ self.assert_close(kmeans.cluster_assignments, expected)+ self.assert_close(kmeans.cluster_assignments, kmeans.predict(x))++ def test_final_assignments_after_refit(self, device, dtype):+ x = torch.tensor([[0.0], [2.0], [4.0], [8.0], [10.0]], device=device, dtype=dtype)+ centers = torch.tensor([[0.0], [3.0]], device=device, dtype=dtype)+ kmeans = kornia.contrib.KMeans(2, centers, tolerance=None, max_iterations=1)+ kmeans.fit(x)++ kmeans.fit(2 * x)++ self.assert_close(kmeans.cluster_centers, x.new_tensor([[0.0], [12.0]]))+ expected = torch.tensor([0, 0, 1, 1, 1], device=device, dtype=torch.long)+ self.assert_close(kmeans.cluster_assignments, expected)+ self.assert_close(kmeans.cluster_assignments, kmeans.predict(2 * x))++ def test_dynamo_final_assignments(self, device, dtype, torch_optimizer):+ x = torch.tensor([[0.0], [2.0], [4.0], [8.0], [10.0]], device=device, dtype=dtype)+ centers = torch.tensor([[0.0], [3.0]], device=device, dtype=dtype)+ kmeans = kornia.contrib.KMeans(2, centers, tolerance=None, max_iterations=1)+ torch_optimizer(kmeans.fit)(x)++ expected = torch.tensor([0, 0, 1, 1, 1], device=device, dtype=torch.long)+ self.assert_close(kmeans.cluster_assignments, expected)+ self.assert_close(kmeans.cluster_assignments, kmeans.predict(x))+@pytest.mark.parametrize(("num_clusters", "tolerance", "max_iterations"),[(3, 1e-4, 3), (10, 1e-3, 1000), (1, 1.0, 10)],