Skip to content

Commit adc1e59

Browse files
belletagramfort
authored andcommitted
[MRG] Fix bug in graph lasso when n_features=2 (scikit-learn#13276)
* fix bug in graph lasso * better fix * add test for case n_features=2 * remove test for deprecated version * update whats new * note that the bug was a regression
1 parent 3e715fd commit adc1e59

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

doc/whats_new/v0.20.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,13 @@ Changelog
2929
negative indexes in the columns list of the transformers.
3030
:issue:`12946` by :user:`Pierre Tallotte <pierretallotte>`.
3131

32+
:mod:`sklearn.covariance`
33+
......................
34+
35+
- |Fix| Fixed a regression in :func:`covariance.graphical_lasso` so that
36+
the case `n_features=2` is handled correctly. :issue:`13276` by
37+
:user:`Aurélien Bellet <bellet>`.
38+
3239
:mod:`sklearn.decomposition`
3340
............................
3441

sklearn/covariance/graph_lasso_.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ def graphical_lasso(emp_cov, alpha, cov_init=None, mode='cd', tol=1e-4,
204204
# https://github.com/scikit-learn/scikit-learn/issues/4134
205205
d_gap = np.inf
206206
# set a sub_covariance buffer
207-
sub_covariance = np.ascontiguousarray(covariance_[1:, 1:])
207+
sub_covariance = np.copy(covariance_[1:, 1:], order='C')
208208
for i in range(max_iter):
209209
for idx in range(n_features):
210210
# To keep the contiguous matrix `sub_covariance` equal to

sklearn/covariance/tests/test_graphical_lasso.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,23 @@ def test_graphical_lasso_iris():
8585
assert_array_almost_equal(icov, icov_R)
8686

8787

88+
def test_graph_lasso_2D():
89+
# Hard-coded solution from Python skggm package
90+
# obtained by calling `quic(emp_cov, lam=.1, tol=1e-8)`
91+
cov_skggm = np.array([[3.09550269, 1.186972],
92+
[1.186972, 0.57713289]])
93+
94+
icov_skggm = np.array([[1.52836773, -3.14334831],
95+
[-3.14334831, 8.19753385]])
96+
X = datasets.load_iris().data[:, 2:]
97+
emp_cov = empirical_covariance(X)
98+
for method in ('cd', 'lars'):
99+
cov, icov = graphical_lasso(emp_cov, alpha=.1, return_costs=False,
100+
mode=method)
101+
assert_array_almost_equal(cov, cov_skggm)
102+
assert_array_almost_equal(icov, icov_skggm)
103+
104+
88105
def test_graphical_lasso_iris_singular():
89106
# Small subset of rows to test the rank-deficient case
90107
# Need to choose samples such that none of the variances are zero

0 commit comments

Comments
 (0)