Skip to content

LogisticRegressionCV failure when not all classes appear in each fold #12845

Description

@gwerbin

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

  1. jmehault commented on Dec 21, 2018

    @jmehault
    Contributor

    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 ?

  2. gwerbin commented on Dec 21, 2018

    @gwerbin
    Author

    @Phypho I would expect the coefficient matrices in multi_coefs_paths to be re-aligned before combining, like what CalibratedClassifierCV does.

    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:

    1. Get an ordered sequence of "all classes", and an ordered sequences of classes in the data you're using to fit the model
    2. Create a dictionary mapping the position of one to the position of the other
    3. When a coefficient matrix or prediction matrix is generated, reorder it to match the order in the "all classes" sequence, inserting 0 or np.nan (as appropriate) when that class doesn't appear in the training data

    This 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.

  3. jnothman commented on Dec 25, 2018

    @jnothman
    Member
  4. gwerbin commented on Dec 26, 2018

    @gwerbin
    Author

    How do you feel about breaking out the label alignment logic from CalibratedClassifierCV into a separate utility class?

    Something like this:

    class MatrixAligner():
        """ Realign data labels according to given labels """
    
        def __init__(self, data_labels, given_labels):
            """ Create and store a mapping between "data" labels and "given" labels """
            ....
    
        def align_matrix(self, y, fill=0 axis=1):
            """ Realign columns (or other axis) to match "given" labels, using stored mapping """
            ...

    With usage like

    y = ['cat', 'cat', 'bear', 'cat', 'tortoise', 'bear']
    labels = ['tortoise', 'bear', 'elephant', 'cat']
    
    # Produce a matrix with 3 columns, corresponding to 'cat', 'bear' and 'tortoise', respectively
    y_onehot = OneHotEncoder().fit_transform(y)
    
    # Realign above matrix to have 4 columns, corresponding to 'tortoise', 'bear', 'elephant', and 'cat',
    # respectively, with the 'tortoise' column containing all 0s
    matrix_aligner = MatrixAligner(y, labels)
    y_onehot_aligned = matrix_aligner.align_matrix(y_onehot)

    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.

  5. jnothman commented on Dec 27, 2018

    @jnothman
    Member
  6. gwerbin commented on Dec 27, 2018

    @gwerbin
    Author

    My original implementation has two functions: get_label_mapping which returns a frozenbidict mapping between data and given labels (after doing some sanity checks), and a function align_matrix that accepts said mapping as its first argument. You would typically create the label mapping in .fit and use it in .transform, so some way to persist the mapping will be needed.

    And sorry if the terminology in here is confusing, given_labels would 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.

  7. jnothman commented on Dec 29, 2018

    @jnothman
    Member
  8. cvanelteren commented on Jan 27, 2019

    @cvanelteren

    @gwerbin can you share your implementation? I'm currently facing this problem in LogisticRegressionCV w/ LeaveOneOut

  9. gitDawn commented on Jun 16, 2021

    @gitDawn

    Any workaround? I'm training LogisticRegressionCV that fails each time because of this issue.

  10. gwerbin commented on Jun 17, 2021

    @gwerbin
    Author

    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 Model class, which is akin to TransformedTargetRegressor (which either didn't exist or was brand-new at the time) or a hypothetical TransformedTargetClassifier. Model.fit runs get_positional_correspondence on the target and stores the result. Model.fit_and_score does 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 LogisticRegressionCV internally is unaware of all this machinery. Therefore I ended up writing my own cross-validation/resampling framework, which uses Model.fit_and_score at each resampling step.

    The ultimate solution might be to add some kind of align_before_scoring=True option to the various *CV estimators 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 in make_scorer.

    CC @cvanelteren.

    @gitDawn: you have to write your own loop over ParameterSampler/ParameterGrid, something like this:

    def fit_cv(estimator, sampler, cv, score_func, x, y):
        best_score = None
        best_estimator = None
    
        y_unique = np.unique(y)
    
        for p, params in enumerate(sampler):
            for ix_train, ix_test in cv.split(x, y):
                x_train = x[ix_train]
                y_train = y[ix_train]
    
                x_test = x[ix_test]
                y_test = y[ix_test]
    
                y_test_unique = np.unique(y_test)
                column_mapping = get_positional_correspondence(y_test_unique, y_unique)
    
                estimator_ = estimator.clone().fit(x_train, y_train)
                proba_test = estimator_.predict_proba(x_test)
    
                proba_test_aligned = reorder_matrix_columns(proba_test, column_mapping)
                score = score_func(y_test_aligned, proba_test_aligned)
    
                if best_score is None or score > best_score:
                    best_score = score
                    best_estimator = estimator_
    
        return best_score, best_estimator
  11. glemaitre commented on Jul 17, 2022

    @glemaitre
    Member

    A minimal reproducible example to be used as a regression test would be the following:

    from sklearn.datasets import load_iris
    from sklearn.model_selection import KFold
    from sklearn.linear_model import LogisticRegressionCV
    
    X, y = load_iris(return_X_y=True)
    cv = KFold(n_splits=3)
    model = LogisticRegressionCV(cv=cv).fit(X, y)
  12. gwerbin commented on Aug 16, 2022

    @gwerbin
    Author

    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.

  13. tdhock commented on Nov 10, 2022

    @tdhock

    I am having this issue too, please fix!

  14. glemaitre commented on Nov 10, 2022

    @glemaitre
    Member

    I am having this issue too, please fix!

    Please contribute!

  15. gwerbin commented on Nov 11, 2022

    @gwerbin
    Author

    I am having this issue too, please fix!

    Please contribute!

    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 *SearchCV meta-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.

  16. glemaitre commented on Nov 11, 2022

    @glemaitre
    Member

    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.

    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.

  17. gwerbin commented on Nov 11, 2022

    @gwerbin
    Author

    @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.

  18. lorentzenchr commented on Nov 30, 2025

    @lorentzenchr
    Member

    This is fixed by #32747 (or #32073). On current main (to be released in 1.8):

    import numpy as np
    from sklearn.model_selection import KFold
    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 f
    old
    remove = np.where(ytmp == 3)[0][2:]
    keep = np.setdiff1d(np.arange(len(ytmp), dtype='int'), remove)

    does not error (only 2 FutureWarnings from deprecations).

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions