π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(enhance): preserve fitted sample axis in inverse ZCA (#5331)
AhmetHakanBezir218c6b33f5f1
diff --git a/changelog.d/5331.fixed.md b/changelog.d/5331.fixed.mdnew file mode 100644index 000000000..c7c63cec9--- /dev/null+++ b/changelog.d/5331.fixed.md@@ -0,0 +1 @@+Fix `ZCAWhitening.inverse_transform` to use the fitted sample dimension, restoring data correctly for nonzero and negative `dim` values instead of raising shape errors or mixing feature values.diff --git a/kornia/enhance/zca.py b/kornia/enhance/zca.pyindex 40a9bcecd..b4ce69acd 100644--- a/kornia/enhance/zca.py+++ b/kornia/enhance/zca.py@@ -150,6 +150,8 @@ class ZCAWhitening(nn.Module):def inverse_transform(self, x: torch.Tensor) -> torch.Tensor:r"""Apply the inverse transform to the whitened data.+ Uses the same sample dimension specified by ``dim`` when fitting.+Args:x: Whitened data.@@ -168,7 +170,7 @@ class ZCAWhitening(nn.Module):mean_inv: torch.Tensor = -self.mean_vector.mm(self.transform_matrix)- return linear_transform(x, self.transform_inv, mean_inv)+ return linear_transform(x, self.transform_inv, mean_inv, self.dim)def zca_mean(diff --git a/tests/enhance/test_zca.py b/tests/enhance/test_zca.pyindex 1d6c3e85e..0d313464b 100644--- a/tests/enhance/test_zca.py+++ b/tests/enhance/test_zca.py@@ -24,6 +24,18 @@ from testing.base import BaseTesterclass TestZCA(BaseTester):+ @pytest.mark.parametrize("shape", [(3, 5, 2), (3, 3, 2)])+ @pytest.mark.parametrize("dim", [0, 1, -2, -1])+ def test_inverse_sample_axis(self, device, dtype, shape, dim):+ """Inverse uses the fitted sample axis, including equal-sized axis aliases (gh-5311)."""+ data = torch.arange(30 if shape[1] == 5 else 18, device=device, dtype=dtype).reshape(shape) / 100+ zca = kornia.enhance.ZCAWhitening(dim=dim, compute_inv=True, eps=1.0).fit(data)+ # A held-out query also exercises the fitted mean, rather than refitting.+ query = (10 * data).cos() / 4+ actual = zca.inverse_transform(zca(query))+ assert actual.shape == query.shape+ self.assert_close(actual, query)+@pytest.mark.parametrize("unbiased", [True, False])def test_zca_unbiased(self, unbiased, device, dtype):data = torch.tensor([[0, 1], [1, 0], [-1, 0], [0, -1]], device=device, dtype=dtype)