Skip to content

Commit 113ee74

Browse files
authored
Fix TypeError in LogisticRegressionCV with refit, use_legacy_attribute False (scikit-learn#33902)
1 parent 900adff commit 113ee74

3 files changed

Lines changed: 27 additions & 1 deletion

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
- :class:`linear_model.LogisticRegressionCV` no longer raises a ``TypeError``
2+
when `refit=False` and `use_legacy_attributes=False` are set together with a
3+
non-elasticnet penalty like `l1_ratios=[0.0]`. Previously, `None` was stored in `l1_ratio_` instead
4+
of `0.0`, which caused `float()` to fail during post-processing.
5+
By :user:`Mohamad Fazeli <Fazel94>`.

sklearn/linear_model/_logistic.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2195,7 +2195,7 @@ def fit(self, X, y, sample_weight=None, **params):
21952195
best_indices_l1 = best_indices[:, 1]
21962196
self.l1_ratio_.append(np.mean(l1_ratios_[best_indices_l1]))
21972197
else:
2198-
self.l1_ratio_.append(None)
2198+
self.l1_ratio_.append(0.0)
21992199

22002200
if is_binary:
22012201
self.coef_ = w[:, :n_features] if w.ndim == 2 else w[:n_features][None, :]

sklearn/linear_model/tests/test_logistic.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,6 +473,27 @@ def test_logistic_cv(global_random_seed, use_legacy_attributes):
473473
assert lr_cv.scores_.shape == (n_cv, n_l1_ratios, n_Cs)
474474

475475

476+
# TODO(1.11): remove filterwarnings with change of default scoring
477+
@pytest.mark.filterwarnings("ignore:The default value.*scoring.*:FutureWarning")
478+
def test_logistic_cv_refit_false_non_elasticnet(global_random_seed):
479+
"""Test that non-elasticnet penalty with refit=False and
480+
use_legacy_attributes=False works without error.
481+
482+
For non-elasticnet penalties, l1_ratio=0.0 (equivalent to pure L2).
483+
Previously, None was stored, which caused float() to raise a
484+
TypeError when use_legacy_attributes=False converted the value to a scalar.
485+
"""
486+
X, y = make_classification(random_state=global_random_seed)
487+
lr_cv = LogisticRegressionCV(
488+
l1_ratios=[0.0],
489+
refit=False,
490+
use_legacy_attributes=False,
491+
random_state=global_random_seed,
492+
)
493+
lr_cv.fit(X, y)
494+
assert lr_cv.l1_ratio_ == 0.0
495+
496+
476497
def test_logistic_cv_mock_scorer():
477498
"""Test that LogisticRegressionCV calls the scorer."""
478499

0 commit comments

Comments
 (0)