Repository navigation
Closed
Copy link
Description
Description
When not all classes appear in each CV fold, LogisticRegressionCV fails when trying to collect the coefficient array.
Steps/Code to Reproduce
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegressionCV
xtmp, ytmp = make_classification(n_samples=2500, n_informative=10, n_classes=6)
# remove all but 2 instances of class 3, in order to make class 3 not-appear in at least one fold
remove = np.where(ytmp == 3)[0][2:]
keep = np.setdiff1d(np.arange(len(ytmp), dtype='int'), remove)
lr = LogisticRegressionCV(multi_class='multinomial', cv=KFold(5)).fit(xtmp[keep], ytmp[keep])Expected Results
No errors; lr contains a fitted instance of LogisticRegressionCV.
Actual Results
<ipython-input-51-ac4dd6663338> in <module>
4 remove = np.where(ytmp == 3)[0][2:] # remove all but 2 instances of class 3
5 keep = np.setdiff1d(np.arange(len(ytmp), dtype='int'), remove)
----> 6 lr = LogisticRegressionCV(multi_class='multinomial', cv=KFold(5)).fit(xtmp[keep], ytmp[keep])
<redacted>/lib/python3.6/site-packages/sklearn/linear_model/logistic.py in fit(self, X, y, sample_weight)
1796 if multi_class == 'multinomial':
1797 multi_coefs_paths, Cs, multi_scores, n_iter_ = zip(*fold_coefs_)
-> 1798 multi_coefs_paths = np.asarray(multi_coefs_paths)
1799 multi_scores = np.asarray(multi_scores)
1800
<redacted>/lib/python3.6/site-packages/numpy/core/numeric.py in asarray(a, dtype, order)
499
500 """
--> 501 return array(a, dtype, copy=False, order=order)
502
503
ValueError: could not broadcast input array from shape (10,5,21) into shape (10)
If you go inspect the multi_coefs_paths object, you'll see that its elements have different shapes, due to the misaligned classes. Only workaround as far as I can tell is to do grid search manually.
Versions
System:
python: 3.6.7 |Anaconda, Inc.| (default, Oct 23 2018, 19:16:44) [GCC 7.3.0]
executable: <redacted>/bin/python
machine: Linux-3.10.0-514.26.2.el7.x86_64-x86_64-with-redhat-7.3-Maipo
BLAS:
macros: SCIPY_MKL_H=None, HAVE_CBLAS=None
lib_dirs: <redacted>/lib
cblas_libs: mkl_rt, pthread
Python deps:
pip: 18.1
setuptools: 40.6.2
sklearn: 0.20.1
numpy: 1.15.4
scipy: 1.1.0
Cython: 0.29
pandas: 0.23.4
Activity
jmehault commentedon Dec 21, 2018
Indeed, Kfold is splitting your dataset without taking into account the group information. Then, as you see, you get folds where the 3rd group is not represented.
Instead, StrafitiedKfold (the default one in case of classification in any CV estimator in scikit-learn) makes that every groups are present in the folds. Then, the expected shape of the estimator output is really filled.
I do not understand what would you like to grid search.
Do you expect that Kfold yields the same none error that StrafitiedKfold ?
gwerbin commentedon Dec 21, 2018
@Phypho I would expect the coefficient matrices in
multi_coefs_pathsto be re-aligned before combining, like whatCalibratedClassifierCVdoes.IMO this should be a part of scikit-learn anyway: a routine to re-align matrices when models are fit using only a subset of classes. The basic method is straightforward:
0ornp.nan(as appropriate) when that class doesn't appear in the training dataThis would be very helpful when working with highly-imbalanced classes in multivariate problems. As it stands right now, several other parts of the scikit-learn codebase fail in this scenario as well (e.g.
log_loss).I have my own wrapper class that does this label aligning, and it works very well for me so far. I can share it if there is interest.
jnothman commentedon Dec 25, 2018
gwerbin commentedon Dec 26, 2018
How do you feel about breaking out the label alignment logic from CalibratedClassifierCV into a separate utility class?
Something like this:
With usage like
Does that make sense? My own code is written in a very different style, but I would rather write something that will be more comfortable to use within the Scikit-learn ecosystem.
The idea is that this could be used in multiple places, basically any place where cross-validation is done internally (e.g. scoring inside GridSearchCV). It should also be exposed directly to users so that they can write their own cross-validation code using ParameterGrid and such.
jnothman commentedon Dec 27, 2018
gwerbin commentedon Dec 27, 2018
My original implementation has two functions:
get_label_mappingwhich returns afrozenbidictmapping between data and given labels (after doing some sanity checks), and a functionalign_matrixthat accepts said mapping as its first argument. You would typically create the label mapping in.fitand use it in.transform, so some way to persist the mapping will be needed.And sorry if the terminology in here is confusing,
given_labelswould correspond to "all possible labels", while "data labels" would be a subset thereof, throwing an error if any value outside of the "all possible" set is included. You could maybe add an option to ignore, instead of error on, such "unknown" labels.jnothman commentedon Dec 29, 2018
cvanelteren commentedon Jan 27, 2019
@gwerbin can you share your implementation? I'm currently facing this problem in LogisticRegressionCV w/ LeaveOneOut
gitDawn commentedon Jun 16, 2021
Any workaround? I'm training LogisticRegressionCV that fails each time because of this issue.
gwerbin commentedon Jun 17, 2021
Hi all, sorry for the long absence.
I dug up my old code for this task and posted the core of it as a Gist here: https://gist.github.com/gwerbin/3e095a63169042de88c80410ceca8705. As you can see, it's mostly docstrings and error checking; the logic itself is not complicated. I used a Bidict to maintain the label correspondence because that's what made sense to me at the time. As @jnothman pointed out, you could do it using
LabelEncoder.I had also written my own
Modelclass, which is akin toTransformedTargetRegressor(which either didn't exist or was brand-new at the time) or a hypotheticalTransformedTargetClassifier.Model.fitrunsget_positional_correspondenceon the target and stores the result.Model.fit_and_scoredoes pretty much what you'd expect, with the added feature that classification targets are re-aligned using the stored correspondence before trying to compute the scores.Note that this still didn't solve the original problem, because
LogisticRegressionCVinternally is unaware of all this machinery. Therefore I ended up writing my own cross-validation/resampling framework, which usesModel.fit_and_scoreat each resampling step.The ultimate solution might be to add some kind of
align_before_scoring=Trueoption to the various*CVestimators and meta-estimators, which would then apply this column realignment before scoring in multi-class and multi-label tasks. Or maybe it should be an option inmake_scorer.CC @cvanelteren.
@gitDawn: you have to write your own loop over
ParameterSampler/ParameterGrid, something like this:glemaitre commentedon Jul 17, 2022
A minimal reproducible example to be used as a regression test would be the following:
gwerbin commentedon Aug 16, 2022
Sorry again for bumping this, but I think I had meant to cross-link this with #11777 back in 2018 when I first posted the two issues.
tdhock commentedon Nov 10, 2022
I am having this issue too, please fix!
glemaitre commentedon Nov 10, 2022
Please contribute!
gwerbin commentedon Nov 11, 2022
I was holding off on making a PR because I wanted to get feedback on my solution from a more-frequent contributor who was more familiar with Scikit-learn internals.
I wasn't sure where to insert my solution, what abstractions to build around it, etc. It seems like it would need to be added to some base location that can be reused by any muticlass-compatible
Estimator.I never got that far in my own implementation. I write my own parameter search "loops" as I showed in #12845 (comment), rather than using the
*SearchCVmeta-estimators.Perhaps one option is to merge these utility functions and describe their usage in the user guide, and put off figuring out how to incorporate them more deeply into the sklearn classifier design later.
glemaitre commentedon Nov 11, 2022
It will be easier to have a pull request to have the implementation indeed. We can write the non-regression test and make sure that we always are getting what we expect and we don't get some side effects. We can make it a draft until we are happy enough with the actual implementation.
gwerbin commentedon Nov 11, 2022
@glemaitre thanks. Are you OK with the PR only containing utility functions and usage guidance in the User Guide?
I feel like this will be challenging to inject into the scikit-learn interface more broadly, and that it will benefit from some concentrated consideration and discussion.
lorentzenchr commentedon Nov 30, 2025
This is fixed by #32747 (or #32073). On current main (to be released in 1.8):
does not error (only 2 FutureWarnings from deprecations).