Skip to content

DictionaryLearner dies with 'omp' only  #33454

Open

Description

@kleingeo

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 features

Versions

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: None

Interest in fixing the bug

No

Activity

  1. added
    Needs Triage
    on Mar 4, 2026
  2. changed the title [-]DictionaryLearner dies on inferencing[/-] [+]DictionaryLearner dies with 'omp' only [/+] on Mar 5, 2026
  3. Pratham-ja commented on Mar 9, 2026

    @Pratham-ja

    Hi @kleingeo, can I work on fixing this bug?

  4. kleingeo commented on Mar 9, 2026

    @kleingeo
    Author

    Hi, yes I will not be able to for a while.

  5. Pratham-ja commented on Mar 10, 2026

    @Pratham-ja

    Hi @kleingeo @norbert @eggie5 @gojomo, I looked into this issue and traced the code paths for both lars and omp. I wanted to summarize what I found and ask for clarification on the intended behavior.

    1. I think the main error here is that in omp method as the number transform_n_nonzero_coefs cannot be greater than n_components. Since omp is iterative method and itselects atoms one by one and cannot select more atoms than exist in the dictionary.
    2. Tracing the execution path:
    raise ValueError(
                    "The number of atoms cannot be more than the number of features")
    • There is a check here also in the _gram_omp saying 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 the RuntimeWarning: Orthogonal matching pursuit ended prematurely due to linear dependence in the dictionary. The requested precision might not have been met.

    Possible solutions:

    • One option could be clipping the value internally (similar to LARS).
    • Other option is that the error is correct but somewhat not clear so we might check early inside tranform before calling sparse encode method and going deep into the _omp.py call.
    if (
        self.transform_n_nonzero_coefs is not None
        and self.transform_n_nonzero_coefs > self.n_components
    ):
        raise ValueError(
            "transform_n_nonzero_coefs cannot be greater than "
            f"n_components ({self.n_components}). "
            f"Got {self.transform_n_nonzero_coefs}."
        )

    Happy to raise a PR after gaining some more clarifications and testing.

  6. kleingeo commented on Mar 10, 2026

    @kleingeo
    Author

    I think a more clear error would be clear, as well as making it more explicit of the limitations in the documentation.

  7. themavik commented on Mar 19, 2026

    @themavik

    Fix submitted in #33581.

  8. AnneBeyer commented on Mar 19, 2026

    @AnneBeyer
    Member

    Hi @themavik, thank you for your interest in contributing to scikit-learn!
    Some remarks on the etiquette, though:

    • This issue is still labelled "Needs triage", so no consensus has been reached on how to proceed yet, see our guidelines.
    • @Pratham-ja actually expressed interest to work on a PR for this (and suggested an approach), so it is not very considerate of you to jump ahead.
  9. Pratham-ja commented on Mar 19, 2026

    @Pratham-ja

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

  10. tabtempera commented on Mar 20, 2026

    @tabtempera

    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?

  11. added 3 commits that reference this issue on Mar 22, 2026
    c7cd816
    482927a
    a54a51a
  12. betatim commented on Mar 23, 2026

    @betatim
    Member

    @tabtempera please read the conversation in this issue. It will answer your question.


    If we implement a check for n_components <= transform_n_nonzero_coefs it should happen in fit I think. I'm wondering why for the lars method 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.

  13. removed
    Needs Triage
    on Apr 7, 2026
  14. tabtempera commented on Apr 27, 2026

    @tabtempera

    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?

  15. AnneBeyer commented on Apr 27, 2026

    @AnneBeyer
    Member

    Hi @tabtempera, as @betatim noted above:

    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.

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

  16. divakantpandey commented on Oct 26, 2026

    @divakantpandey

    Regarding the question on why LARS clips while OMP raises an error:

    Looking through the git history (commit fa7b914e5f from 2011 by Fabian Pedregosa), lars_path consolidated max_features and max_iter into:

    max_features = min(max_iter, n_features)

    In Least Angle Regression (LAR), each step activates at most one variable into the active set. When invoked via sparse_encode in _dict_learning.py, Lars.fit(dictionary.T, X.T) is called with n_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:

    if tol is None and n_nonzero_coefs > len(Gram):
        raise ValueError("The number of atoms cannot be more than the number of features")

    When DictionaryLearning(n_components=k, transform_algorithm='omp') passes n_nonzero_coefs > k, len(Gram) == k, so orthogonal_mp_gram aborts with an error referencing "features" rather than dictionary atoms. Meanwhile, the default transform_n_nonzero_coefs=None already clips via min(max(n_features / 10, 1), n_components).

    To achieve consistency between the two methods:

    • Either _dict_learning.py can clip transform_n_nonzero_coefs = min(transform_n_nonzero_coefs, n_components) before passing to sparse_encode (mirroring the default behavior and LARS).
    • Or _dict_learning.py can validate transform_n_nonzero_coefs <= self.n_components with an explicit error indicating that the requested number of nonzero coefficients cannot exceed the number of dictionary components.
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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions