Skip to content

Numpy Array Error when Training MultioutputClassifer with LogisticRegressionCV with classes underrepresented #30832

Closed

Description

@lionelkusch

Describe the bug

When I train the MultioutputClassifer with LogisticRegressionCV with classes underrepresented, I get the following numpy error.
I think this is connected to the issue #28178 and #26401.

Steps/Code to Reproduce

import sklearn
print(sklearn.__version__)
from sklearn.linear_model import LogisticRegressionCV
from sklearn.multioutput import MultiOutputClassifier
import numpy as np


n, m = 20, 5
model = MultiOutputClassifier(LogisticRegressionCV())
X = np.random.randn(n, m)
y = np.concatenate([[np.random.randint(0, 2, n),
                     np.random.randint(0, 5, n)]], axis=0).T
y[-3:, 0] = [3, 4, 5]
model.fit(X, y)

Expected Results

1.6.1

Actual Results

1.6.1

.venv/lib/python3.12/site-packages/sklearn/model_selection/_split.py:805: UserWarning: The least populated class in y has only 1 members, which is less than n_splits=5.
  warnings.warn(
Traceback (most recent call last):
  File "error_skitlearn.py", line 14, in <module>
    model.fit(X, y)
  File ".venv/lib/python3.12/site-packages/sklearn/multioutput.py", line 543, in fit
    super().fit(X, Y, sample_weight=sample_weight, **fit_params)
  File ".venv/lib/python3.12/site-packages/sklearn/base.py", line 1389, in wrapper
    return fit_method(estimator, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File ".venv/lib/python3.12/site-packages/sklearn/multioutput.py", line 274, in fit
    self.estimators_ = Parallel(n_jobs=self.n_jobs)(
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File ".venv/lib/python3.12/site-packages/sklearn/utils/parallel.py", line 77, in __call__
    return super().__call__(iterable_with_config)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File ".venv/lib/python3.12/site-packages/joblib/parallel.py", line 1918, in __call__
    return output if self.return_generator else list(output)
                                                ^^^^^^^^^^^^
  File ".venv/lib/python3.12/site-packages/joblib/parallel.py", line 1847, in _get_sequential_output
    res = func(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^
  File ".venv/lib/python3.12/site-packages/sklearn/utils/parallel.py", line 139, in __call__
    return self.function(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File ".venv/lib/python3.12/site-packages/sklearn/multioutput.py", line 63, in _fit_estimator
    estimator.fit(X, y, **fit_params)
  File ".venv/lib/python3.12/site-packages/sklearn/base.py", line 1389, in wrapper
    return fit_method(estimator, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File ".venv/lib/python3.12/site-packages/sklearn/linear_model/_logistic.py", line 2038, in fit
    coefs_paths = np.reshape(
                  ^^^^^^^^^^^
  File ".venv/lib/python3.12/site-packages/numpy/_core/fromnumeric.py", line 324, in reshape
    return _wrapfunc(a, 'reshape', shape, order=order)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File ".venv/lib/python3.12/site-packages/numpy/_core/fromnumeric.py", line 54, in _wrapfunc
    return _wrapit(obj, method, *args, **kwds)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File ".venv/lib/python3.12/site-packages/numpy/_core/fromnumeric.py", line 42, in _wrapit
    conv = _array_converter(obj)
           ^^^^^^^^^^^^^^^^^^^^^
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 2 dimensions. The detected shape was (5, 10) + inhomogeneous part.

Versions

System:
    python: 3.12.3 (main, Jan 17 2025, 18:03:48) [GCC 13.3.0]
executable: .venv/bin/python
   machine: Linux-6.8.0-52-generic-x86_64-with-glibc2.39

Python dependencies:
      sklearn: 1.6.1
          pip: 25.0.1
   setuptools: 75.8.0
        numpy: 2.2.3
        scipy: 1.15.1
       Cython: None
       pandas: 2.2.3
   matplotlib: 3.10.0
       joblib: 1.4.2
threadpoolctl: 3.5.0

Built with OpenMP: True

threadpoolctl info:
       user_api: blas
   internal_api: openblas
    num_threads: 8
         prefix: libscipy_openblas
       filepath: .venv/lib/python3.12/site-packages/numpy.libs/libscipy_openblas64_-6bb31eeb.so
        version: 0.3.28
threading_layer: pthreads
   architecture: Haswell

       user_api: blas
   internal_api: openblas
    num_threads: 8
         prefix: libscipy_openblas
       filepath: .venv/lib/python3.12/site-packages/scipy.libs/libscipy_openblas-68440149.so
        version: 0.3.28
threading_layer: pthreads
   architecture: Haswell

       user_api: openmp
   internal_api: openmp
    num_threads: 8
         prefix: libgomp
       filepath: .venv/lib/python3.12/site-packages/scikit_learn.libs/libgomp-a34b3233.so.1.0.0
        version: None

Activity

  1. added
    Needs Triage
    on Feb 14, 2025
  2. ogrisel commented on Feb 21, 2025

    @ogrisel
    Member

    The warning is informative:

    .venv/lib/python3.12/site-packages/sklearn/model_selection/_split.py:805: UserWarning: The least populated class in y has only 1 members, which is less than n_splits=5.
    

    The coefficients are not aligned because some cross-validation estimators do not see all the classes at training time as others.

    We can probably try to make LogisticRegressionCV robust to this case. If not, we should at least detect this problem earlier in fit and raise a more meaningful exception.

    Note that the problem is not related to MultioutputClassifier and can directly be reproduced with:

    from sklearn.linear_model import LogisticRegressionCV
    import numpy as np
    
    n, m = 20, 5
    X = np.random.randn(n, m)
    y = np.random.randint(0, 2, n)
    y[-3:] = [3, 4, 5]
    LogisticRegressionCV().fit(X, y)
    /Users/ogrisel/code/scikit-learn/sklearn/model_selection/_split.py:811: UserWarning: The least populated class in y has only 1 members, which is less than n_splits=5.
      warnings.warn(
    /Users/ogrisel/code/scikit-learn/sklearn/linear_model/_logistic.py:470: ConvergenceWarning: lbfgs failed to converge (status=1):
    STOP: TOTAL NO. OF ITERATIONS REACHED LIMIT.
    
    Increase the number of iterations (max_iter) or scale the data as shown in:
        https://scikit-learn.org/stable/modules/preprocessing.html
    Please also refer to the documentation for alternative solver options:
        https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
      n_iter_i = _check_optimize_result(
    /Users/ogrisel/code/scikit-learn/sklearn/linear_model/_logistic.py:470: ConvergenceWarning: lbfgs failed to converge (status=1):
    STOP: TOTAL NO. OF ITERATIONS REACHED LIMIT.
    
    Increase the number of iterations (max_iter) or scale the data as shown in:
        https://scikit-learn.org/stable/modules/preprocessing.html
    Please also refer to the documentation for alternative solver options:
        https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
      n_iter_i = _check_optimize_result(
    Traceback (most recent call last):
      Cell In[4], line 8
        LogisticRegressionCV().fit(X, y)
      File ~/code/scikit-learn/sklearn/base.py:1389 in wrapper
        return fit_method(estimator, *args, **kwargs)
      File ~/code/scikit-learn/sklearn/linear_model/_logistic.py:2049 in fit
        coefs_paths = np.reshape(
      File ~/miniforge3/envs/dev/lib/python3.12/site-packages/numpy/_core/fromnumeric.py:328 in reshape
        return _wrapfunc(a, 'reshape', shape, order=order)
      File ~/miniforge3/envs/dev/lib/python3.12/site-packages/numpy/_core/fromnumeric.py:54 in _wrapfunc
        return _wrapit(obj, method, *args, **kwds)
      File ~/miniforge3/envs/dev/lib/python3.12/site-packages/numpy/_core/fromnumeric.py:42 in _wrapit
        conv = _array_converter(obj)
    ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 2 dimensions. The detected shape was (5, 10) + inhomogeneous part.
    
  3. removed
    Needs Triage
    on Feb 21, 2025
  4. nunofbiomartins commented on Mar 6, 2025

    @nunofbiomartins

    /take

  5. nunofbiomartins commented on Mar 8, 2025

    @nunofbiomartins

    Hello @ogrisel and everyone. I'm working on this issue, and I'm trying to understand it the best way so I can fix it.

    Do you think that increasing the dataset by repeating the data in each class until the class with the minimum number of samples reaches the number of splits is a bad idea?

    Example:

    old_dataset
    [[ 0.12, -0.43],
    [ 1.23, 0.56],
    [-0.34, 0.78],
    [ 0.90, -1.56],
    [-0.56, 0.34]]

    old_classes
    [0, 1, 0, 1, 3] --> Class 3 only has 1 sample ( Let's say we set the n_splits to 2 )

    * Some code to repeat the the dataset and classes *

    new_dataset
    [[ 0.12, -0.43],
    [ 1.23, 0.56],
    [-0.34, 0.78],
    [ 0.90, -1.56],
    [-0.56, 0.34],
    [ 0.12, -0.43],
    [ 1.23, 0.56],
    [-0.34, 0.78],
    [ 0.90, -1.56],
    [-0.56, 0.34]]

    new_classes
    [0, 1, 0, 1, 3, 0, 1, 0, 1, 3] --> Now, the number of samples in every class is greater than or equal to n_splits.

    Even though it might lead to some overfitting, it is still better than getting a ValueError, right?
    Are there any other tips someone can give me to help me fix this bug?

    Any thoughts or tips will be helpful.
    I will keep working on this.
    Thank you a lot!

  6. lionelkusch commented on Mar 10, 2025

    @lionelkusch
    Author

    In my opinion, if one class is underrepresented, we can assume that its probability is close to zeros. In consequence, we can complete the coefficients with some zeros.

  7. added 4 commits that reference this issue on Mar 27, 2025
    9863412
    cf62543
    9451b2d
    f2c058e
  8. added
    Needs Investigation
    and removed on Jun 4, 2025
  9. lorentzenchr commented on Feb 27, 2026

    @lorentzenchr
    Member

    This is solved by #32747.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugNeeds Investigation

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions