Skip to content

Numpy Array Error when Training LogisticRegressionCV #26401

Description

@ajr426

Describe the bug

When I attempt to train LogisticRegressionCV, I get the error: 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.

The inputs to LogisticRegressionCV are:

  • X = output of StandardScaler.fit_transform, with a shape of (24, 12) and dtype of float64
  • y = array with shape (24, ) and dtype of int64

I checked that there are not null or infinite values in either array.

Steps/Code to Reproduce

data_for_color_training = training_data.loc[training_data["IdentCode"] == color]
x_train = data_for_color_training.loc[:, (data_for_color_training.columns.str.startswith("dx") | data_for_color_training.columns.str.startswith("dy") | data_for_color_training.columns.str.startswith("dz"))]
y_train = data_for_color_training["Grade"]
			
#--------------Edit specific pre-processing and model here-----------------------------
scaler = StandardScaler()
X_train = scaler.fit_transform(x_train)
modelTrained = LogisticRegressionCV(max_iter=10000).fit(X_train, y_train)

Expected Results

The variable modelTrained will output a LogisticRegressionCV model.

Actual Results

Traceback (most recent call last):
  File "C:\Users\...\PythonScripts\UserDefinedModel.py", line 22, in train_predict_by_colorcode
    modelTrained = LogisticRegressionCV(max_iter=10000).fit(X_train, y_train)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\...\AppData\Local\Programs\Python\Python311\Lib\site-packages\sklearn\linear_model\_logistic.py", line 1912, in fit
    coefs_paths = np.reshape(
                  ^^^^^^^^^^^
  File "<__array_function__ internals>", line 200, in reshape
  File "C:\Users\...\AppData\Local\Programs\Python\Python311\Lib\site-packages\numpy\core\fromnumeric.py", line 298, in reshape
    return _wrapfunc(a, 'reshape', newshape, order=order)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\...\AppData\Local\Programs\Python\Python311\Lib\site-packages\numpy\core\fromnumeric.py", line 54, in _wrapfunc
    return _wrapit(obj, method, *args, **kwds)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\...\AppData\Local\Programs\Python\Python311\Lib\site-packages\numpy\core\fromnumeric.py", line 43, in _wrapit
    result = getattr(asarray(obj), method)(*args, **kwds)
                     ^^^^^^^^^^^^
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.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\...\AppData\Local\Programs\Python\Python311\Lib\site-packages\numpy\core\fromnumeric.py", line 298, in reshape
    return _wrapfunc(a, 'reshape', newshape, order=order)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\...\AppData\Local\Programs\Python\Python311\Lib\site-packages\numpy\core\fromnumeric.py", line 54, in _wrapfunc
    return _wrapit(obj, method, *args, **kwds)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\...\AppData\Local\Programs\Python\Python311\Lib\site-packages\numpy\core\fromnumeric.py", line 43, in _wrapit
    result = getattr(asarray(obj), method)(*args, **kwds)
                     ^^^^^^^^^^^^
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.11.1 (tags/v3.11.1:a7a450f, Dec  6 2022, 19:58:39) [MSC v.1934 64 bit (AMD64)]
executable: C:\Users\...\AppData\Local\Programs\Python\Python311\python.exe
   machine: Windows-10-10.0.19044-SP0

Python dependencies:
      sklearn: 1.2.2
          pip: 22.3.1
   setuptools: 65.5.0
        numpy: 1.24.1
        scipy: 1.10.0
       Cython: None
       pandas: 1.5.3
   matplotlib: 3.6.3
       joblib: 1.2.0
threadpoolctl: 3.1.0

Built with OpenMP: True

threadpoolctl info:
       user_api: blas
   internal_api: openblas
         prefix: libopenblas
       filepath: C:\Users\...\AppData\Local\Programs\Python\Python311\Lib\site-packages\numpy\.libs\libopenblas64__v0.3.21-gcc_10_3_0.dll
        version: 0.3.21
threading_layer: pthreads
   architecture: Haswell
    num_threads: 16

       user_api: openmp
internal_api: openmp
         prefix: vcomp
       filepath: C:\Users\...\AppData\Local\Programs\Python\Python311\Lib\site-packages\sklearn\.libs\vcomp140.dll
        version: None
    num_threads: 16

       user_api: blas
   internal_api: openblas
         prefix: libopenblas
       filepath: C:\Users\...\AppData\Local\Programs\Python\Python311\Lib\site-packages\scipy.libs\libopenblas-802f9ed1179cb9c9b03d67ff79f48187.dll
        version: 0.3.18
threading_layer: pthreads
   architecture: Haswell
    num_threads: 16

Activity

  1. added
    Needs Triage
    on May 19, 2023
  2. Micky774 commented on May 19, 2023

    @Micky774
    Contributor

    Hey there @ajr426!

    As it is right now, it is a bit difficult to provide accurate and helpful guidance/diagnosis. If at all possible, can you try to provide a minimal-reproducer of your problem? Without access to your source data training_data it is a bit difficult to figure out what exactly is happening. I suspect it is a problem with how you construct x_train, however the fact that scaler.fit_transform(x_train) doesn't fail seems to contradict that.

  3. added and removed
    Needs Triage
    on May 19, 2023
  4. ajr426 commented on May 19, 2023

    @ajr426
    Author

    Hi @Micky774!

    training_data comes from a SQL query, but attached is the data from the SQL query.
    LogisticRegressionCV Issue.xlsx

    Is this enough info?

  5. viren1419 commented on May 23, 2023

    @viren1419

    @ajr426 Hello ! I would suggest to verify training data non numeric features needed encoding or missing values can also cause issues with StandardScalar while preprocessing

  6. adrinjalali commented on Jun 1, 2023

    @adrinjalali
    Member

    This seems to be more of a data issue rather than a scikit-learn issue. Closing, happy to reopen if there's a minimal reproducible resulting in an error here.

  7. asuchaneck commented on Jun 5, 2023

    @asuchaneck

    I got the same error and it's not a data problem. asarray is failing because obj[0] has shape (10,58,3228) and obj[1] has shape (10,59,3228) in my case. Therefore the second dimension is a mismatch. LogisticRegression is working fine, so it's probably an issue with the CV. Not sure how I could provide a data example here. @adrinjalali

  8. adrinjalali commented on Jun 5, 2023

    @adrinjalali
    Member

    A toy small reproducible example would enable us to investigate.

  9. Micky774 commented on Jun 5, 2023

    @Micky774
    Contributor

    Not sure how I could provide a data example here. @adrinjalali

    Try to find out what is unique about your data that causes this. Downsize your data and simplify it to the utmost until the problem no longer occurs. The simplest instance in which it occurs should hopefully make the triggering aspects a bit more obvious. Try to then create an easy, small synthetic data example with the same inherent properties which still triggers the error.

    It is very hard for us to work backwards from provided data, and sometimes indeed unsafe for us to do so, thus small reproducers from those reporting the error are the best way to move the issue forwards

  10. asuchaneck commented on Jun 6, 2023

    @asuchaneck

    I've made a smaller example, but there isn't anything unique about the data. Probably the labels happen to be such that the CV split algorithm exposes a bug (sklearn 1.2.2):

    from sklearn.linear_model import LogisticRegressionCV
    import numpy as np
    
    X=np.zeros(shape=(20,1))
    y=[5, 4, 4, 1, 3, 0, 3, 3, 2, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3]
    LogisticRegressionCV().fit(X,y)
    
    # ERROR
    File ~/miniforge3/lib/python3.10/site-packages/numpy/core/fromnumeric.py:43, in _wrapit(obj, method, *args, **kwds)
         41 except AttributeError:
         42     wrap = None
    ---> 43 result = getattr(asarray(obj), method)(*args, **kwds)
         44 if wrap:
         45     if not isinstance(result, mu.ndarray):
    
    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.
    
    # pdb
    ipdb>  obj[0].shape
    (10, 5, 2)
    ipdb>  obj[1].shape
    (10, 6, 2)
    

    There is a dimension mismatch. @Micky774

  11. Micky774 commented on Jun 6, 2023

    @Micky774
    Contributor

    Thank you for the minimal reproduction. I am away from my machine for much of this week and can't guarantee a speedy response from myself, but I will investigate a bit when I have some availability.

    If anyone else has the capacity and interest in the meantime, please feel free to investigate.

  12. adrinjalali commented on Jun 6, 2023

    @adrinjalali
    Member

    This is the full stack trace on main:

    In [1]: from sklearn.linear_model import LogisticRegressionCV
       ...: import numpy as np
       ...: 
       ...: X=np.zeros(shape=(20,1))
       ...: y=[5, 4, 4, 1, 3, 0, 3, 3, 2, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3]
       ...: LogisticRegressionCV().fit(X,y)
    /home/adrin/Projects/sklearn/scikit-learn/sklearn/model_selection/_split.py:723: UserWarning: The least populated class in y has only 1 members, which is less than n_splits=5.
      warnings.warn(
    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    Cell In[1], line 6
          4 X=np.zeros(shape=(20,1))
          5 y=[5, 4, 4, 1, 3, 0, 3, 3, 2, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3]
    ----> 6 LogisticRegressionCV().fit(X,y)
    
    File ~/Projects/sklearn/scikit-learn/sklearn/linear_model/_logistic.py:1919, in LogisticRegressionCV.fit(self, X, y, sample_weight)
       1917 self.Cs_ = Cs[0]
       1918 if multi_class == "multinomial":
    -> 1919     coefs_paths = np.reshape(
       1920         coefs_paths,
       1921         (len(folds), len(l1_ratios_) * len(self.Cs_), n_classes, -1),
       1922     )
       1923     # equiv to coefs_paths = np.moveaxis(coefs_paths, (0, 1, 2, 3),
       1924     #                                                 (1, 2, 0, 3))
       1925     coefs_paths = np.swapaxes(coefs_paths, 0, 1)
    
    File <__array_function__ internals>:200, in reshape(*args, **kwargs)
    
    File ~/miniforge3/envs/sklearn/lib/python3.10/site-packages/numpy/core/fromnumeric.py:298, in reshape(a, newshape, order)
        198 @array_function_dispatch(_reshape_dispatcher)
        199 def reshape(a, newshape, order='C'):
        200     """
        201     Gives a new shape to an array without changing its data.
        202 
       (...)
        296            [5, 6]])
        297     """
    --> 298     return _wrapfunc(a, 'reshape', newshape, order=order)
    
    File ~/miniforge3/envs/sklearn/lib/python3.10/site-packages/numpy/core/fromnumeric.py:54, in _wrapfunc(obj, method, *args, **kwds)
         52 bound = getattr(obj, method, None)
         53 if bound is None:
    ---> 54     return _wrapit(obj, method, *args, **kwds)
         56 try:
         57     return bound(*args, **kwds)
    
    File ~/miniforge3/envs/sklearn/lib/python3.10/site-packages/numpy/core/fromnumeric.py:43, in _wrapit(obj, method, *args, **kwds)
         41 except AttributeError:
         42     wrap = None
    ---> 43 result = getattr(asarray(obj), method)(*args, **kwds)
         44 if wrap:
         45     if not isinstance(result, mu.ndarray):
    
    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.

    we already do raise a warning about y, but the error message should be a more friendly one.

  13. asuchaneck commented on Jun 6, 2023

    @asuchaneck

    I suppose there must be away that it does not crash (despite the warning). Especially, since I get the same on very large data (which however may include rare classes too)

  14. mathis-saunier commented on Oct 20, 2025

    @mathis-saunier

    Hi everyone,

    I would like to take on this old issue as my first contribution to Scikit-learn.

    I fully understand how an under-represented class could cause an error during the cross-validation step.

    Out of curiosity, I also tested RidgeClassifierCV with the minimal reproduction example and didn’t encounter any errors. However, we still get the following warning:
    UserWarning: The least populated class in y has only 1 member, which is less than n_splits=5.

    Since RidgeClassifierCV seems to handle rare classes without getting the same error as the LogisticRegressionCV, we might find a solution to our problem there.

    Does this approach sound reasonable? Do you have any advice that could help me with my first contribution?

  15. adrinjalali commented on Oct 20, 2025

    @adrinjalali
    Member

    Not sure what version you're checking, but on main RidgeClassifierCV doesn't raise anything:

    In [2]: In [1]: from sklearn.linear_model import RidgeClassifierCV
       ...:    ...: import numpy as np
       ...:    ...:
       ...:    ...: X=np.zeros(shape=(20,1))
       ...:    ...: y=[5, 4, 4, 1, 3, 0, 3, 3, 2, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3]
       ...:    ...: RidgeClassifierCV().fit(X,y)
    Out[2]: RidgeClassifierCV()

    Do you have any advice that could help me with my first contribution?

    Please read our contribution guidelines and make sure your follow our AI contribution policy: https://github.com/scikit-learn/scikit-learn/blob/main/CODE_OF_CONDUCT.md#low-quality-and-ai-generated-contributions-policy

  16. mathis-saunier commented on Oct 20, 2025

    @mathis-saunier

    Thanks, I will read the contribution guidelines.

    Yes, RidgeClassifierCV doesn't raise anything and run with under-represented classes.
    That's why I think we can found the solution to this issue inside the RidgeClassifierCV's code.

  17. mathis-saunier commented on Nov 2, 2025

    @mathis-saunier

    Hi everyone,

    To recap, this error occurs when some classes are very rare and the smallest class has fewer samples than the number of splits defined for cross-validation.

    More specifically, I believe the issue comes from the absence of certain classes in some training folds. If I understand correctly, when a class k is missing from a training split, most solvers fail because they cannot compute the corresponding parameters (it may be an issue with the gradient computation).

    A simple way to avoid this error would be to explicitly use a one-vs-rest strategy — either via the (now deprecated) argument multi_class='ovr' or by wrapping the model in sklearn.multiclass.OneVsRestClassifier(LogisticRegressionCV()).

    from sklearn.linear_model import LogisticRegressionCV
    from sklearn.multiclass import OneVsRestClassifier
    import numpy as np
    
    X = np.zeros(shape=(20,1))
    y_issue = [1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4]
    
    # Error occurs here (solver='lbfgs' by default)
    LogisticRegressionCV(cv=2).fit(X,y_issue)
    
    # No error with the deprecated argument multi_class='ovr'
    LogisticRegressionCV(cv=2, multi_class='ovr').fit(X,y_issue)
    
    # No error with with the OVR wrapper
    OneVsRestClassifier(LogisticRegressionCV(cv=2)).fit(X,y_issue)

    Moreover, the error doesn't always append when we have at least two members inside the least populated class. I didn't analyse this yet.

    from sklearn.linear_model import LogisticRegressionCV
    import numpy as np
    
    X = np.zeros(shape=(20,1))
    y_issue = [1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5]
    
    # No error with different cv values and at least 2 members per class
    LogisticRegressionCV(cv=5).fit(X,y_issue)
    LogisticRegressionCV(cv=7).fit(X,y_issue)

    Given how rare this situation (when an error appear) is, it might not be worth changing the implementation of LogisticRegressionCV itself. Maybe this could instead be handled through a warning or a note in the documentation.

    I’m not sure if this investigation helps move the issue forward, but I’d be glad to hear your thoughts.

  18. adrinjalali commented on Nov 5, 2025

    @adrinjalali
    Member

    We don't have to fix it, but we should at least raise a more meaningful error message.

  19. mathis-saunier commented on Nov 6, 2025

    @mathis-saunier

    Ok, I will think about it during the weekend.

    Thank you for your response

  20. mathis-saunier commented on Nov 16, 2025

    @mathis-saunier

    Could the following warning be appropriate ?

    "UserWarning: The least populated class in y has only 1 member, which is fewer than n_splits=X. Some classes may be missing from training folds, which can cause LogisticRegressionCV to fail. Reduce the number of CV splits or use a
    one-vs-rest strategy (e.g., OneVsRestClassifier)."

    If so, I will prepare a pull request for the change.

  21. lesteve commented on Nov 18, 2025

    @lesteve
    Member

    Thanks @mathis-saunier for the follow-up!

    I would wait until #32073 is merged (hopefully in a few days) it seems like the following snippet does not give an error any more on the #32073 branch:

    from sklearn.linear_model import LogisticRegressionCV
    import numpy as np
    
    X = np.zeros(shape=(20,1))
    y_issue = [1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4]
    
    # Error occurs on `main` but on on #32073 branch
    LogisticRegressionCV(cv=2).fit(X,y_issue)

    On #32073 branch, there is the following warning

    /home/lesteve/dev/scikit-learn/sklearn/model_selection/_split.py:812: UserWarning: The least populated class in y has only 1 members, which is less than n_splits=2.
    
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