Repository navigation
Labels
Description
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
Micky774 commentedon May 19, 2023
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_datait is a bit difficult to figure out what exactly is happening. I suspect it is a problem with how you constructx_train, however the fact thatscaler.fit_transform(x_train)doesn't fail seems to contradict that.ajr426 commentedon May 19, 2023
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?
viren1419 commentedon May 23, 2023
@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
adrinjalali commentedon Jun 1, 2023
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.
asuchaneck commentedon Jun 5, 2023
I got the same error and it's not a data problem.
asarrayis 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. @adrinjalaliadrinjalali commentedon Jun 5, 2023
A toy small reproducible example would enable us to investigate.
Micky774 commentedon Jun 5, 2023
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
asuchaneck commentedon Jun 6, 2023
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):
There is a dimension mismatch. @Micky774
Micky774 commentedon Jun 6, 2023
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.
adrinjalali commentedon Jun 6, 2023
This is the full stack trace on
main:we already do raise a warning about
y, but the error message should be a more friendly one.asuchaneck commentedon Jun 6, 2023
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)
mathis-saunier commentedon Oct 20, 2025
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?
adrinjalali commentedon Oct 20, 2025
Not sure what version you're checking, but on
mainRidgeClassifierCVdoesn't raise anything: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
mathis-saunier commentedon Oct 20, 2025
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.
mathis-saunier commentedon Nov 2, 2025
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()).
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.
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.
adrinjalali commentedon Nov 5, 2025
We don't have to fix it, but we should at least raise a more meaningful error message.
mathis-saunier commentedon Nov 6, 2025
Ok, I will think about it during the weekend.
Thank you for your response
mathis-saunier commentedon Nov 16, 2025
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.
lesteve commentedon Nov 18, 2025
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:
On #32073 branch, there is the following warning