|
6 | 6 | from six.moves import xrange
|
7 | 7 | from sklearn.metrics import pairwise_distances
|
8 | 8 | from sklearn.datasets import load_iris, make_classification, make_regression
|
9 |
| -from numpy.testing import assert_array_almost_equal, assert_array_equal |
| 9 | +from numpy.testing import (assert_array_almost_equal, assert_array_equal, |
| 10 | + assert_allclose) |
10 | 11 | from sklearn.utils.testing import assert_warns_message
|
11 | 12 | from sklearn.exceptions import ConvergenceWarning
|
12 | 13 | from sklearn.utils.validation import check_X_y
|
@@ -53,6 +54,23 @@ def test_iris(self):
|
53 | 54 | # deterministic result
|
54 | 55 | self.assertAlmostEqual(csep, 0.72981476)
|
55 | 56 |
|
| 57 | + def test_singular_returns_pseudo_inverse(self): |
| 58 | + """Checks that if the input covariance matrix is singular, we return |
| 59 | + the pseudo inverse""" |
| 60 | + X, y = load_iris(return_X_y=True) |
| 61 | + # We add a virtual column that is a linear combination of the other |
| 62 | + # columns so that the covariance matrix will be singular |
| 63 | + X = np.concatenate([X, X[:, :2].dot([[2], [3]])], axis=1) |
| 64 | + cov_matrix = np.cov(X, rowvar=False) |
| 65 | + covariance = Covariance() |
| 66 | + covariance.fit(X) |
| 67 | + pseudo_inverse = covariance.get_mahalanobis_matrix() |
| 68 | + # here is the definition of a pseudo inverse according to wikipedia: |
| 69 | + assert_allclose(cov_matrix.dot(pseudo_inverse).dot(cov_matrix), |
| 70 | + cov_matrix) |
| 71 | + assert_allclose(pseudo_inverse.dot(cov_matrix).dot(pseudo_inverse), |
| 72 | + pseudo_inverse) |
| 73 | + |
56 | 74 |
|
57 | 75 | class TestLSML(MetricTestCase):
|
58 | 76 | def test_iris(self):
|
|
0 commit comments