Repository navigation
MNT carry out deprecation for 1.8 of multi_class in LogisticRegression and LogisticRegressionCV - #32073
Conversation
|
@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. |
This comment was marked as resolved.
This comment was marked as resolved.
c248ea7 to
e538ff5
Compare
|
Dear reviewers, feel free to finish in case I am unresponsive. |
There was a problem hiding this comment.
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
| # 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, |
There was a problem hiding this comment.
is it a bug fixed in this PR ? is there a way to test it ?
There was a problem hiding this comment.
I don't know (anymore).
There was a problem hiding this comment.
Maybe that's related to the comment above about different number of classes in different folds?
|
Maybe @adrinjalali for a second review ? |
adrinjalali
left a comment
There was a problem hiding this comment.
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
mainand this branch, making sure the results are the same on coefficients and the prediction(proba) values.
| 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. |
| class_weight = dict(enumerate(class_weight)) | ||
| class_weight = dict(zip(self.classes_, class_weight)) | ||
|
|
||
| if is_binary: |
There was a problem hiding this comment.
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_
There was a problem hiding this comment.
Yes, needed. Though I think I can remove encoded_labels.
There was a problem hiding this comment.
About classes_ and self.classes_, we need both.
There was a problem hiding this comment.
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!
|
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 😉 |
e08ea09 to
3cc6349
Compare
lesteve
left a comment
There was a problem hiding this comment.
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.
| # 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, |
There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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 ...
There was a problem hiding this comment.
not change „it“ (the coef)
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
OK thanks for having a look 🙏!
I have opened #32748 to track this bug.
|
I will fix the conflicts introduced by merging #32114 first ... |
…_legacy_attributes=False
| # 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) |
There was a problem hiding this comment.
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 🙏.
| coefs = coefs.reshape(len(clf_multi.Cs_), -1) | ||
| norms = np.sum(coefs * coefs, axis=1) # L2 norm for each C |
There was a problem hiding this comment.
| 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 |
| 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 |
There was a problem hiding this comment.
"no action required" comment: Isn't this ugly?
There was a problem hiding this comment.
🤔 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 🤔
There was a problem hiding this comment.
no action required, just am comment/joke.
There was a problem hiding this comment.
OK thanks, I thought you were criticizing the existing code comment, but actually "no action required comment" was referring your own GitHub comment 😅
| # 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) |
lesteve
left a comment
There was a problem hiding this comment.
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 🤞.
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. |
Reference Issues/PRs
Carries out #28703 and #31241.
Contributes massively to #11865.
Fixes #32072Fixes #26401
What does this implement/fix? Explain your changes.
This PR removes the deprecated parameter
multi_classfromLogisticRegressionandLogisticRegressionCVand 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.