Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): validate sample count for unbiased ZCA (#5332)

AhmetHakanBeziref2286f1c31c
diff --git a/changelog.d/5332.breaking.md b/changelog.d/5332.breaking.md
new file mode 100644
index 000000000..2d9bcd082
--- /dev/null
+++ b/changelog.d/5332.breaking.md
@@ -0,0 +1 @@
+`zca_mean`, `zca_whiten` and `ZCAWhitening.fit` now raise `ValueError` when the sample dimension has fewer than two entries with `unbiased=True` (the default), or none with `unbiased=False`. Previously the covariance was divided by zero, and the result was NaNs, an empty `zca_whiten` output, or a `torch.linalg.LinAlgError` from the SVD, depending on the input shape. Whitening one sample with `unbiased=False` is still supported and returns zeros.
diff --git a/kornia/enhance/zca.py b/kornia/enhance/zca.py
index b4ce69acd..db749ede1 100644
--- a/kornia/enhance/zca.py
+++ b/kornia/enhance/zca.py
@@ -109,6 +109,10 @@ class ZCAWhitening(nn.Module):
Returns:
Returns a fitted ZCAWhiten object instance.
+ Raises:
+ ValueError: If the sample dimension has fewer than two entries with ``unbiased=True``, or none with
+ ``unbiased=False``.
+
"""
T, mean, T_inv = zca_mean(x, self.dim, self.unbiased, self.eps, self.compute_inv)
@@ -198,6 +202,10 @@ def zca_mean(
A tuple containing the ZCA matrix and the mean vector. If return_inverse is set to True,
then it returns the inverse ZCA matrix, otherwise it returns None.
+ Raises:
+ ValueError: If the sample dimension has fewer than two entries with ``unbiased=True``, or none with
+ ``unbiased=False``.
+
.. note::
See a working example `here <https://colab.sandbox.google.com/github/kornia/tutorials/
blob/master/source/zca_whitening.ipynb>`__.
@@ -247,6 +255,12 @@ def zca_mean(
N = inp_size[dim]
+ # The covariance divides by N - 1 (unbiased) or by N (biased), so fewer samples leave it undefined.
+ if unbiased and N < 2:
+ raise ValueError(f"Unbiased covariance requires at least two samples, got {N}.")
+ if N < 1:
+ raise ValueError("Covariance requires at least one sample, got 0.")
+
mean: torch.Tensor = torch.mean(inp_permute, dim=0, keepdim=True)
mean = mean.reshape((1, num_features))
@@ -287,6 +301,10 @@ def zca_whiten(inp: torch.Tensor, dim: int = 0, unbiased: bool = True, eps: floa
Returns:
Whiten Input data.
+ Raises:
+ ValueError: If the sample dimension has fewer than two entries with ``unbiased=True``, or none with
+ ``unbiased=False``.
+
.. note::
See a working example `here <https://colab.sandbox.google.com/github/kornia/tutorials/
blob/master/source/zca_whitening.ipynb>`__.
diff --git a/tests/enhance/test_zca.py b/tests/enhance/test_zca.py
index 0d313464b..2d1d76187 100644
--- a/tests/enhance/test_zca.py
+++ b/tests/enhance/test_zca.py
@@ -24,6 +24,47 @@ from testing.base import BaseTester
class TestZCA(BaseTester):
+ @pytest.mark.parametrize("dim", [0, 1, -1])
+ @pytest.mark.parametrize("sample_count", [0, 1])
+ def test_unbiased_sample_count(self, device, dtype, dim, sample_count):
+ """Unbiased covariance is undefined with fewer than two samples (gh-5313)."""
+ shape = (sample_count, 3) if dim == 0 else (3, sample_count)
+ data = torch.ones(shape, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="at least two samples"):
+ kornia.enhance.zca_mean(data, dim=dim, unbiased=True)
+
+ @pytest.mark.parametrize("dim", [0, 1, -1])
+ def test_biased_single_sample(self, device, dtype, dim):
+ """The population covariance of one sample is zero and remains supported."""
+ data = torch.tensor([[1.0, 2.0, 3.0]], device=device, dtype=dtype)
+ if dim != 0:
+ data = data.t()
+ actual = kornia.enhance.zca_whiten(data, dim=dim, unbiased=False)
+ self.assert_close(actual, torch.zeros_like(data))
+
+ @pytest.mark.parametrize("dim", [0, 1, -1])
+ def test_biased_empty_sample_axis(self, device, dtype, dim):
+ """The biased covariance divides by N, so an empty sample axis is rejected as well."""
+ shape = (0, 3) if dim == 0 else (3, 0)
+ data = torch.ones(shape, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="at least one sample"):
+ kornia.enhance.zca_mean(data, dim=dim, unbiased=False)
+
+ @pytest.mark.parametrize("unbiased", [True, False])
+ @pytest.mark.parametrize("dim", [0, 1, -1])
+ def test_two_samples(self, device, dtype, dim, unbiased):
+ """Two samples are the fewest that unbiased whitening accepts; the divisor is N - 1 = 1, or N = 2 if biased."""
+ data = torch.tensor([[2.0, 1.0], [0.0, 3.0]], device=device, dtype=dtype)
+ # The centred samples (1, -1) and (-1, 1) have scatter eigenvalue 4 along (1, -1) and 0 across it, so with
+ # eps = 1 the output is the centred data divided by sqrt(4 / divisor + 1).
+ expected = (
+ torch.tensor([[1.0, -1.0], [-1.0, 1.0]], device=device, dtype=dtype) / (5.0 if unbiased else 3.0) ** 0.5
+ )
+ if dim != 0:
+ data, expected = data.t(), expected.t()
+ actual = kornia.enhance.ZCAWhitening(dim=dim, unbiased=unbiased, eps=1.0)(data, include_fit=True)
+ self.assert_close(actual, expected)
+
@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):