Repository navigation
Open
Labels
Description
Describe the bug and give evidence about its user-facing impact
I noticed new behaviour in sklearn.decomposition.DictioanryLearning. I have noticed an error that I have not seen before. Learner transform_n_nonzero_coefs > n_components and only when transform_algorithm = "omp".
Example below is similar to my current use-case. Situation occurs due to large hyperparameter grid search.
Using newest version, sklearn==1.8.0.
Documentation should be updated to reflect the difference in outputs and limitations.
Steps/Code to Reproduce
import numpy as np
import sklearn
from sklearn.preprocessing import StandardScaler, OneHotEncoder, MinMaxScaler
from sklearn.compose import ColumnTransformer
if __name__ == '__main__':
column_scaler = ColumnTransformer(
transformers=[
('vert_encoder', OneHotEncoder(), [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]),
],
remainder='passthrough',
sparse_threshold=0,
)
N = 150
x_main = np.zeros((N, 26))
x_main[:, :6] = np.random.rand(N, 6)
x_main[:, 6] = np.random.randint(1, 25, size=N)
x_main[:, 7] = np.random.randint(1, 3, size=N)
x_main[:, 8] = np.random.randint(0, 5, size=N)
x_main[:, 9] = np.random.randint(1, 17, size=N)
x_main[:, 10] = np.random.randint(1, 3, size=N)
x_main[:, 11] = np.random.randint(1, 3, size=N)
x_main[:, 12] = np.random.randint(1, 3, size=N)
x_main[:, 13] = np.random.randint(0, 7, size=N)
x_main[:, 14] = np.random.randint(1, 4, size=N)
x_main[:, 15] = np.random.randint(0, 4, size=N)
x_main[:, 16] = np.random.randint(0, 4, size=N)
x_main[:, 17] = np.random.randint(0, 4, size=N)
x_main[:, 18] = np.random.randint(0, 19, size=N)
x_main[:, 19:] = np.random.rand(N, 7)
column_scaler.fit(x_main)
x_scaled = column_scaler.transform(x_main)
x_val_scaled = column_scaler.transform(x_main)
dict_params = {'n_components': 18,
'max_iter': 1000,
'transform_algorithm': 'lars',
'transform_n_nonzero_coefs': 19,
}
dl_lars = sklearn.decomposition.DictionaryLearning(random_state=0,
**dict_params)
dl_lars.fit(x_scaled)
x_scaled_transformed = dl_lars.transform(x_scaled)
print('passed (fake) training data')
x_val_scaled_transformed = dl_lars.transform(x_val_scaled)
print('passed (fake) validation data')
print('Changing to "omp"')
dict_params = {'n_components': 18,
'max_iter': 1000,
'transform_algorithm': 'omp',
'transform_n_nonzero_coefs': 19,
}
dl_omp = sklearn.decomposition.DictionaryLearning(random_state=0,
**dict_params)
dl_omp.fit(x_scaled)
x_scaled_transformed = dl_omp.transform(x_scaled)
print('passed (fake) training data')
x_val_scaled_transformed = dl_omp.transform(x_val_scaled)
print('passed (fake) validation data')Expected Results
No errors.
Actual Results
Connected to pydev debugger (build 253.28294.336)
passed (fake) training data
passed (fake) validation data
Changing to "omp"
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm\plugins\python-ce\helpers\pydev\pydevd.py", line 1647, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\JetBrains\PyCharm\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:\SpineFracturePrediction\test_sklearn_dl.py", line 69, in <module>
x_scaled_transformed = dl_omp.transform(x_scaled)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Miniforge3\envs\spine_frac_312\Lib\site-packages\sklearn\utils\_set_output.py", line 316, in wrapped
data_to_wrap = f(self, X, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Miniforge3\envs\spine_frac_312\Lib\site-packages\sklearn\decomposition\_dict_learning.py", line 1141, in transform
return self._transform(X, self.components_)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Miniforge3\envs\spine_frac_312\Lib\site-packages\sklearn\decomposition\_dict_learning.py", line 1102, in _transform
code = sparse_encode(
^^^^^^^^^^^^^^
File "C:\Miniforge3\envs\spine_frac_312\Lib\site-packages\sklearn\utils\_param_validation.py", line 218, in wrapper
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "C:\Miniforge3\envs\spine_frac_312\Lib\site-packages\sklearn\decomposition\_dict_learning.py", line 374, in sparse_encode
return _sparse_encode(
^^^^^^^^^^^^^^^
File "C:\Miniforge3\envs\spine_frac_312\Lib\site-packages\sklearn\decomposition\_dict_learning.py", line 429, in _sparse_encode
code = _sparse_encode_precomputed(
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Miniforge3\envs\spine_frac_312\Lib\site-packages\sklearn\decomposition\_dict_learning.py", line 192, in _sparse_encode_precomputed
new_code = orthogonal_mp_gram(
^^^^^^^^^^^^^^^^^^^
File "C:\Miniforge3\envs\spine_frac_312\Lib\site-packages\sklearn\utils\_param_validation.py", line 191, in wrapper
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "C:\Miniforge3\envs\spine_frac_312\Lib\site-packages\sklearn\linear_model\_omp.py", line 605, in orthogonal_mp_gram
raise ValueError(
ValueError: The number of atoms cannot be more than the number of featuresVersions
sklearn.show_versions()
System:
python: 3.12.12 | packaged by conda-forge | (main, Jan 26 2026, 23:38:32) [MSC v.1944 64 bit (AMD64)]
executable: C:\Miniforge3\envs\spine_frac_312\python.exe
machine: Windows-11-10.0.26100-SP0
Python dependencies:
sklearn: 1.8.0
pip: 26.0.1
setuptools: 82.0.0
numpy: 2.4.2
scipy: 1.17.1
Cython: None
pandas: 3.0.1
matplotlib: 3.10.8
joblib: 1.5.3
threadpoolctl: 3.6.0
Built with OpenMP: True
threadpoolctl info:
user_api: blas
internal_api: mkl
num_threads: 8
prefix: libblas
filepath: C:\Miniforge3\envs\spine_frac_312\Library\bin\libblas.dll
version: 2020.0.4
threading_layer: intel
user_api: openmp
internal_api: openmp
num_threads: 16
prefix: libiomp
filepath: C:\Miniforge3\envs\spine_frac_312\Library\bin\libiomp5md.dll
version: None
user_api: openmp
internal_api: openmp
num_threads: 16
prefix: vcomp
filepath: C:\Miniforge3\envs\spine_frac_312\vcomp140.dll
version: NoneInterest in fixing the bug
No
Activity
[-]DictionaryLearner dies on inferencing[/-][+]DictionaryLearner dies with 'omp' only [/+]Pratham-ja commentedon Mar 9, 2026
Hi @kleingeo, can I work on fixing this bug?
kleingeo commentedon Mar 9, 2026
Hi, yes I will not be able to for a while.
Pratham-ja commentedon Mar 10, 2026
Hi @kleingeo @norbert @eggie5 @gojomo, I looked into this issue and traced the code paths for both
larsandomp. I wanted to summarize what I found and ask for clarification on the intended behavior.ompmethod as the numbertransform_n_nonzero_coefscannot be greater thann_components. Sinceompis iterative method and itselects atoms one by one and cannot select more atoms than exist in the dictionary.transformwhich calls _sparse_encode----->_sparse_encode_precomputedtransform_algorithm==larslars.fit() methodwhich uses this methodlars_pathwhich callslars_path_solverwe can find this linemax_features = min(max_iter, n_features). This effectively clips the number of active features to n_features, so no error occurs even iftransform_n_nonzero_coefs > n_components.transform_algorithm="omp"the error we see in the code is due tothis check_gram_ompsaying the same atom cannot be used twice. I tried the same code as in the issue after commenting the raise value error and it triggers theRuntimeWarning: Orthogonal matching pursuit ended prematurely due to linear dependence in the dictionary. The requested precision might not have been met.Possible solutions:
tranformbefore callingsparse encodemethod and going deep into the _omp.py call.Happy to raise a PR after gaining some more clarifications and testing.
kleingeo commentedon Mar 10, 2026
I think a more clear error would be clear, as well as making it more explicit of the limitations in the documentation.
themavik commentedon Mar 19, 2026
Fix submitted in #33581.
AnneBeyer commentedon Mar 19, 2026
Hi @themavik, thank you for your interest in contributing to scikit-learn!
Some remarks on the etiquette, though:
Pratham-ja commentedon Mar 19, 2026
@AnneBeyer, Thanks for addressing this. Yeah I don't submit a PR as the issue is labelled needs triage. I also mentioned this discussion in discord to discuss further and then raise a PR if the maintainers felt the necessity to do so. So I am just waiting for the response.
@themavik Thanks for your interest but I would recommend for future contributions,first show your interest and then discuss your approach instead of directly raising a PR for some issue that you want to work on.
tabtempera commentedon Mar 20, 2026
Hi! I’m an undergraduate student working on a course project (bugfix contribution).
I went through the discussion above and I agree that the most appropriate fix is to fail fast with a clearer error message when transform_algorithm="omp" and transform_n_nonzero_coefs > n_components, instead of raising a confusing error deep in _omp.py. I also agree it would be good to document this limitation explicitly.
Is it OK if I work on this?
Fix scikit-learn#33454: validate OMP n_nonzero_coefs in sparse_encode
Fix scikit-learn#33454: validate OMP n_nonzero_coefs in sparse_encode
Fix scikit-learn#33454: validate OMP n_nonzero_coefs in sparse_encode
betatim commentedon Mar 23, 2026
@tabtempera please read the conversation in this issue. It will answer your question.
If we implement a check for
n_components <= transform_n_nonzero_coefsit should happen infitI think. I'm wondering why for thelarsmethod this wasn't done, and instead they clip the value. I suspect the reason for that is to make hyper-parameter optimisation easier.In an ideal world we'd make both methods behave the same way. Having one clip the value and another raise an error is inconsistent. The next thing to do is to do some digging to understand why the choice was made in LARS to clip. Once that is known I think we can pick what to do.
tabtempera commentedon Apr 27, 2026
Hi @betatim, thanks for the guidance.
Now that the “Needs triage” label has been removed, do you have a preferred direction for the fix? Should we keep LARS’ current behavior (clipping) and make OMP consistent by clipping as well, or should we instead switch to raising an error (ideally validating early, e.g. in fit), or is there another approach you’d prefer?
AnneBeyer commentedon Apr 27, 2026
Hi @tabtempera, as @betatim noted above:
Feel free to contribute some research on this. GitLens/git blame might be helpful tools here to find the related PRs where this was introduced to figure out why this decision was made. (Note that this is an equally (or even more) valuable contribution compared to submitting a bugfix for a known issue).
divakantpandey commentedon Oct 26, 2026
Regarding the question on why LARS clips while OMP raises an error:
Looking through the git history (commit
fa7b914e5ffrom 2011 by Fabian Pedregosa),lars_pathconsolidatedmax_featuresandmax_iterinto:In Least Angle Regression (LAR), each step activates at most one variable into the active set. When invoked via
sparse_encodein_dict_learning.py,Lars.fit(dictionary.T, X.T)is called withn_features = n_components(the number of dictionary atoms). Because an active set cannot contain more variables than total available features/atoms, LARS naturally halts once all dictionary atoms are active (max_features = min(n_nonzero_coefs, n_components)).In contrast,
_omp.py(line 617) enforces an explicit validation guard:When
DictionaryLearning(n_components=k, transform_algorithm='omp')passesn_nonzero_coefs > k,len(Gram) == k, soorthogonal_mp_gramaborts with an error referencing "features" rather than dictionary atoms. Meanwhile, the defaulttransform_n_nonzero_coefs=Nonealready clips viamin(max(n_features / 10, 1), n_components).To achieve consistency between the two methods:
_dict_learning.pycan cliptransform_n_nonzero_coefs = min(transform_n_nonzero_coefs, n_components)before passing tosparse_encode(mirroring the default behavior and LARS)._dict_learning.pycan validatetransform_n_nonzero_coefs <= self.n_componentswith an explicit error indicating that the requested number of nonzero coefficients cannot exceed the number of dictionary components.