Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions python/cuml/cuml/covariance/empirical_covariance.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ def _empirical_covariance(X, assume_centered=False):
return cp.dot(X_centered.T, X_centered) / X.shape[0]


def _pinv(covariance):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I’d suggest investigating a Hermitian-specific pseudoinverse based on cp.linalg.eigh in a follow-up. That would also match scikit-learn’s use of scipy.linalg.pinvh. I ran some quick tests, and performance looked promising. This fix looks good, so we can merge as-is.

"""Compute a dtype-aware Moore-Penrose pseudoinverse."""
rcond = max(covariance.shape) * cp.finfo(covariance.dtype).eps
return cp.linalg.pinv(covariance, rcond=rcond)


def _log_likelihood(emp_cov, precision):
"""Compute the sample mean log-likelihood under a covariance model."""
sign, log_det_precision = cp.linalg.slogdet(precision)
Expand Down Expand Up @@ -188,7 +194,7 @@ def fit(self, X, y=None) -> "EmpiricalCovariance":
self.covariance_ = covariance

if self.store_precision:
self.precision_ = cp.linalg.pinv(covariance)
self.precision_ = _pinv(covariance)
else:
self.precision_ = None

Expand All @@ -207,7 +213,7 @@ def get_precision(self):

if self.store_precision:
return self.precision_
return cp.linalg.pinv(self.covariance_)
return _pinv(self.covariance_)

@mlfunc(convert_output=False)
def score(self, X_test, y=None) -> float:
Expand Down
22 changes: 21 additions & 1 deletion python/cuml/tests/test_empirical_covariance.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#
# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION.
# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#

Expand Down Expand Up @@ -244,6 +244,26 @@ def test_mahalanobis_matches_sklearn():
)


@pytest.mark.parametrize("store_precision", [True, False])
def test_singular_covariance_matches_sklearn(store_precision):
X = np.array([[1, 2], [3, 4], [5, 6]], dtype=np.float32)
cu_cov = EmpiricalCovariance(store_precision=store_precision).fit(X)
sk_cov = SklearnEmpiricalCovariance(store_precision=store_precision).fit(X)

np.testing.assert_allclose(
np.asarray(cu_cov.get_precision()),
sk_cov.get_precision(),
rtol=1e-5,
atol=1e-6,
)
np.testing.assert_allclose(
np.asarray(cu_cov.mahalanobis(X[:2])),
sk_cov.mahalanobis(X[:2]),
rtol=1e-5,
atol=1e-6,
)


def test_error_norm_frobenius_matches_sklearn():
X = _make_random_data()
cu_cov = EmpiricalCovariance().fit(X)
Expand Down
Loading