Skip to content

MNT carry out deprecation for 1.8 of multi_class in LogisticRegression and LogisticRegressionCV - #32073

Merged
lesteve merged 24 commits into
scikit-learn:mainfrom
lorentzenchr:dep_logistic_multiclass
Nov 19, 2025
Merged

lesteve merged 24 commits into
scikit-learn:mainfrom
lorentzenchr:dep_logistic_multiclass

Conversation

@lorentzenchr

@lorentzenchr lorentzenchr commented Sep 1, 2025 •

Copy link
Copy Markdown
Member

Reference Issues/PRs

Carries out #28703 and #31241.
Contributes massively to #11865.
Fixes #32072
Fixes #26401

What does this implement/fix? Explain your changes.

This PR removes the deprecated parameter multi_class from LogisticRegression and LogisticRegressionCV and does all the necessary code refactoring to not drown of all the legacy code.

Any other comments?

A lot of work, but I hope it is useful for the future.

@lorentzenchr lorentzenchr added this to the 1.8 milestone Sep 1, 2025
@github-actions

github-actions Bot commented Sep 1, 2025 •

Copy link
Copy Markdown

✔️ Linting Passed

All linting checks passed. Your pull request is in excellent shape! ☀️

Generated for commit: 71f527e. Link to the linter CI: here

@lorentzenchr

Copy link
Copy Markdown
Member Author

@jeremiedbb This is a very difficult to carry out deprecation. At least, this PR is a big jump start. I might not be able to finish it in time. In that case, someone can take over.

@lorentzenchr

This comment was marked as resolved.

@lorentzenchr
lorentzenchr force-pushed the dep_logistic_multiclass branch from c248ea7 to e538ff5 Compare September 2, 2025 10:40
@lorentzenchr

Copy link
Copy Markdown
Member Author

Dear reviewers, feel free to finish in case I am unresponsive.

@jeremiedbb jeremiedbb left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'm glad I didn't have to do this one, thanks ! 😄
I directly pushed a few nitpicks and clean-ups as requested.

LGTM

There are a few things that need some clean-up now like attributes with the same values repeated n_classes times or arrays of shape (1,), but I'll open a dedicated issue to discuss them and they can be dealt with in separate PRs.
EDIT: you already opened one #32075

Comment on lines +678 to +684
# Note: We pass classes for the whole dataset to avoid inconsistencies, i.e.
# different number of classes in different folds. This way, if a class is empty
# in a fold, _logistic_regression_path will initialize it to zero and not change.
coefs, Cs, n_iter = _logistic_regression_path(
X_train,
y_train,
classes=classes,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

is it a bug fixed in this PR ? is there a way to test it ?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I don't know (anymore).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Maybe that's related to the comment above about different number of classes in different folds?

@jeremiedbb

Copy link
Copy Markdown
Member

Maybe @adrinjalali for a second review ?

Comment thread sklearn/linear_model/_logistic.py Resolved

@adrinjalali adrinjalali left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Since this is such a large diff, would be nice to have the following:

  • a time benchmark making sure this doesn't slow things down (I doubt if it does)
  • a few runs comparing main and this branch, making sure the results are the same on coefficients and the prediction(proba) values.

Comment thread sklearn/linear_model/_logistic.py Resolved
Comment thread sklearn/linear_model/_logistic.py Resolved
Comment thread sklearn/linear_model/_logistic.py Resolved
Comment thread sklearn/linear_model/_logistic.py Resolved
not. ``None`` means 1 unless in a :obj:`joblib.parallel_backend`
context. ``-1`` means using all processors.
See :term:`Glossary <n_jobs>` for more details.
Not used at the moment.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is it going to be used?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Comment thread sklearn/linear_model/_logistic.py Resolved
Comment thread sklearn/linear_model/_logistic.py Resolved
Comment thread sklearn/linear_model/_logistic.py Resolved
class_weight = dict(enumerate(class_weight))
class_weight = dict(zip(self.classes_, class_weight))

if is_binary:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

a bit confused here. Is it still needed? Certainly a comment in the code would help.

Also, here we set classes_, but bellow we use self.classes_

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes, needed. Though I think I can remove encoded_labels.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

About classes_ and self.classes_, we need both.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I renamed the classes_ variable to classes_only_pos_if_binary, not sure it helps, let me know if you can think of a better name!

@lesteve

lesteve commented Nov 14, 2025 •

Copy link
Copy Markdown
Member

Oops sorry did not mean to push into this branch ... trying to do things in parallel which is not a good idea 😓

But yeah I am starting to review this 😉

@lesteve
lesteve force-pushed the dep_logistic_multiclass branch from e08ea09 to 3cc6349 Compare November 14, 2025 09:32

@lesteve lesteve left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I am in the middle (maybe probably less) of my review but it's the end of the week, so here are my comments so far.

Comment thread sklearn/linear_model/_logistic.py Resolved
Comment thread sklearn/linear_model/_logistic.py Resolved
Comment on lines +678 to +684
# Note: We pass classes for the whole dataset to avoid inconsistencies, i.e.
# different number of classes in different folds. This way, if a class is empty
# in a fold, _logistic_regression_path will initialize it to zero and not change.
coefs, Cs, n_iter = _logistic_regression_path(
X_train,
y_train,
classes=classes,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Maybe that's related to the comment above about different number of classes in different folds?

# Train clf on the original dataset where classes 0 and 1 are separated
clf = LogisticRegressionCV(cv=precomputed_folds, multi_class="ovr")
# Train clf on the original dataset
clf = LogisticRegressionCV(cv=precomputed_folds, solver="newton-cholesky")

@lesteve lesteve Nov 14, 2025 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Just curious you use solver="newton-cholesky" (here and in other places of this PR), so you expect it to be more stable/reliable for iris data or in general?

@lorentzenchr lorentzenchr Nov 17, 2025 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It is just a better solver (than lbfgs) for most cases, see #15556.


# Note: We pass classes for the whole dataset to avoid inconsistencies, i.e.
# different number of classes in different folds. This way, if a class is empty
# in a fold, _logistic_regression_path will initialize it to zero and not change.

@lesteve lesteve Nov 17, 2025 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Not sure whether the sentence is missing the end, "will initialize it to zero and not change" what?

To be honest, even the "it" is not super clear ...

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

not change „it“ (the coef)

@lesteve lesteve Nov 18, 2025 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I may be missing something but it seems like the coefficient for a given class does not stay at zero when a class is missing.

I took the Iris dataset with the well known issue that y is ordered with 3 classes so that if you use cv=KFold(3) you will get the issue that each training fold will have 2 of the 3 classes, and the the test fold has the third class.

import numpy as np

from sklearn.linear_model import LogisticRegressionCV
from sklearn.datasets import load_iris
from sklearn.model_selection import KFold

X, y = load_iris(return_X_y=True)

# Error occurs on `main` but on on this branch
lr = LogisticRegressionCV(cv=KFold(3), Cs=[1], fit_intercept=False).fit(X, y)
lr.coefs_paths_

As far as I can see there are no zero-coefficient anywhere?

{np.int64(0): array([[[ 0.36617189,  0.4181025 , -1.80054529, -1.59885258,
          11.94538259]],
 
        [[-0.27013869,  0.19659815, -1.0394569 , -0.4717853 ,
           8.11303679]],
 
        [[-0.2259761 ,  0.55491805, -1.32935417, -0.56475712,
           6.7920903 ]]]),
 np.int64(1): array([[[-0.36863165, -0.41910848,  1.80385762,  1.60144714,
          -4.03491417]],
 
        [[ 0.26501596, -0.1994853 ,  1.03704383,  0.47085702,
          -1.69095992]],
 
        [[ 0.22447638, -0.55428594,  1.33474803,  0.56733333,
          -0.29154238]]]),
 np.int64(2): array([[[ 2.45975917e-03,  1.00598025e-03, -3.31232754e-03,
          -2.59456480e-03, -7.91046843e+00]],
 
        [[ 5.12273225e-03,  2.88714428e-03,  2.41307063e-03,
           9.28278209e-04, -6.42207687e+00]],
 
        [[ 1.49971712e-03, -6.32115481e-04, -5.39386365e-03,
          -2.57621573e-03, -6.50054792e+00]]])}

For completeness, the same snippet fails on main so I guess this could be turned into a test for the new behaviour if it becomes clearer what to test exactly (maybe a smoke test is enough?) ...

ValueError: cannot reshape array of size 15 into shape (3,1,3,newaxis)

@lorentzenchr lorentzenchr Nov 18, 2025 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Warning

@lesteve spotted a hickup (call it bug) that needs fixing.

Checking the assumptions

Smuggling in

c, f = np.unique(y_train, return_counts=True)
cf = {int(ci):int(fi) for ci, fi in zip(c, f)}
print(f"y_train counts={cf}")

right before coefs, Cs, n_iter = _logistic_regression_path( around line 683 gives

y_train counts={1: 50, 2: 50}
y_train counts={0: 50, 2: 50}
y_train counts={0: 50, 1: 50}

This confirms: Class i is missing in fold i.

Why are the coefficients of all classes changed?

Because they enter the objective function via the penalty. Therefore, the above code comment should be modified.

Why there is a bug to fix?

Inside function _logistic_regression_path, around line 280

le = LabelEncoder()

This should instead read

le = LabelEncoder().fit(classes)

and the subsequent fit_transform should be changed to transform (this fixes a bug and makes it faster).

Remaining tasks

Even if this is fixed, there remains a bug if one passes another scorer, e.g.

lr = LogisticRegressionCV(cv=KFold(3), Cs=[1], fit_intercept=False,scoring="neg_brier_score").fit(X, y)
ValueError: y_true contains only one label (0). Please provide the list of all expected class labels explicitly through the labels argument.

I would postpone fixing this to another future PR, maybe not part of 1.8. The situation is already better if the above is fixed.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

OK thanks for having a look 🙏!

I have opened #32748 to track this bug.

@lesteve

lesteve commented Nov 18, 2025

Copy link
Copy Markdown
Member

I will fix the conflicts introduced by merging #32114 first ...

Comment on lines +747 to +756
# Norm of coefficients should increase with increasing C.
for fold in range(clf_multi.coefs_paths_.shape[0]):
# with use_legacy_attributes=False, coefs_paths_ has shape
# (n_folds, n_l1_ratios, n_Cs, n_classes, n_features + 1)
# Note that we have to exclude the intercept, hence the ':-1'
# on the last dimension
coefs = clf_multi.coefs_paths_[fold, 0, :, :, :-1]
coefs = coefs.reshape(len(clf_multi.Cs_), -1)
norms = np.sum(coefs * coefs, axis=1) # L2 norm for each C
assert np.all(np.diff(norms) >= 0)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Would you be kind enough to double-check this @lorentzenchr, the test pass but it would be nice to have a second pairs of eyes 🙏.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Seems right.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for double-checking 🙏

Comment on lines +754 to +755
coefs = coefs.reshape(len(clf_multi.Cs_), -1)
norms = np.sum(coefs * coefs, axis=1) # L2 norm for each C

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Suggested change
coefs = coefs.reshape(len(clf_multi.Cs_), -1)
norms = np.sum(coefs * coefs, axis=1) # L2 norm for each C
norms = np.sum(coefs * coefs, axis=(-2, -1)) # L2 norm for each C

Comment on lines +728 to +732
coefs = [
clf_multi.coefs_paths_[c][fold, :, :-1] for c in clf_multi.classes_
]
coefs = np.swapaxes(coefs, 1, 0).reshape(len(clf_multi.Cs_), -1)
norms = np.sum(coefs * coefs, axis=1) # L2 norm for each C

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

"no action required" comment: Isn't this ugly?

@lesteve lesteve Nov 19, 2025 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🤔 my brain reader is not functioning well enough sorry ... am I supposed to do something about it, or does your comment apply to itself as well, as a recursive/self-referential/infinite loop kind of joke 😅 ?

For explicitness I copied the comment that was in the other branch, I don't see anything obviously wrong with the comment personally 🤔

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

no action required, just am comment/joke.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

OK thanks, I thought you were criticizing the existing code comment, but actually "no action required comment" was referring your own GitHub comment 😅

Comment on lines +747 to +756
# Norm of coefficients should increase with increasing C.
for fold in range(clf_multi.coefs_paths_.shape[0]):
# with use_legacy_attributes=False, coefs_paths_ has shape
# (n_folds, n_l1_ratios, n_Cs, n_classes, n_features + 1)
# Note that we have to exclude the intercept, hence the ':-1'
# on the last dimension
coefs = clf_multi.coefs_paths_[fold, 0, :, :, :-1]
coefs = coefs.reshape(len(clf_multi.Cs_), -1)
norms = np.sum(coefs * coefs, axis=1) # L2 norm for each C
assert np.all(np.diff(norms) >= 0)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Seems right.

@lesteve lesteve left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I am going to merge this one, mostly because I am going to trust the tests and I feel like I have spent enough time on this already ...

I felt it was nearly impossible for me to understand the changes (without spending a few more days on it) for a number of reasons, including the following ones:

  • I was not familiar with the previous code, which looks like it had some intrinsic complexity
  • some of the logic was moved in different place making the diff hard to review

I guess future will tell if we missed something or not 🤞.

@lesteve
lesteve merged commit 6a9ce61 into scikit-learn:main Nov 19, 2025
@lorentzenchr
lorentzenchr deleted the dep_logistic_multiclass branch November 19, 2025 17:20
@lorentzenchr

Copy link
Copy Markdown
Member Author

the previous code, which looks like it had some intrinsic complexity

Same for me, the old code was (partially still is) hard to understand, even though I am familiar with the code base. In #11865 @amueller called it opaque for a good reason.

As I anticipated the difficulty in carrying out this deprecation I prepared it well in advance of the release.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

5 participants