Skip to content

ConvergenceWarnings cannot be turned off #29294

Closed

Description

@user529481

Hi, I'm unable to turn off convergence warnings from GraphicalLassoCV.

I've tried most of the solutions from, and none of them worked (see below for actual implementations):
https://stackoverflow.com/questions/879173/how-to-ignore-deprecation-warnings-in-python
https://stackoverflow.com/questions/32612180/eliminating-warnings-from-scikit-learn/33812427#33812427
https://stackoverflow.com/questions/53968004/how-to-silence-all-sklearn-warning
https://stackoverflow.com/questions/14463277/how-to-disable-python-warnings

Contrary to what the designers of the sklearn's exceptions must have thought when it was implemented, some of us actually use stdout to log important information of the host program for diagnostics purposes. Flooding it with garbage that cannot be turned off, as is in the case with cross-validation, is not ok.

To briefly speak to the severity of the issue, the above sklearn-specific questions relating to suppressing warnings have been viewed ~500K times with combined ~400 upvotes, and dates back 7 years.

I've tried the following (n_jobs parameter does not appear to affect the result):

from sklearn.covariance import GraphicalLassoCV
import warnings
warnings.filterwarnings("ignore", category=ConvergenceWarning)

model = GraphicalLassoCV(n_jobs=4)
model = model.fit(data)
from sklearn.covariance import GraphicalLassoCV
import warnings
warnings.filterwarnings(action='ignore')

model = GraphicalLassoCV(n_jobs=4)
model = model.fit(data)
import warnings
with warnings.catch_warnings():
    warnings.simplefilter("ignore", ConvergenceWarning)

    model = GraphicalLassoCV(n_jobs=4)
    model = model.fit(data)
from sklearn.covariance import GraphicalLassoCV
def warn(*args, **kwargs):
    pass
import warnings
warnings.warn = warn

model = GraphicalLassoCV(n_jobs=4)
model = model.fit(data)
import contextlib
import os, sys

@contextlib.contextmanager
def suppress_stdout():
    with open(os.devnull, 'w') as fnull:
        old_stdout = sys.stdout
        sys.stdout = fnull
        try:
            yield
        finally:
            sys.stdout = old_stdout

with suppress_stdout():
    model = GraphicalLassoCV(n_jobs=4)
    model = model.fit(data)
import logging
logging.captureWarnings(True)

logging.getLogger("py.warnings").setLevel(logging.ERROR)

model = GraphicalLassoCV(n_jobs=4)
model = model.fit(data)

Activity

  1. added
    Needs Triage
    on Jun 19, 2024
  2. lesteve commented on Jun 19, 2024

    @lesteve
    Member

    If you give a fully stand-alone example, in particular some data that triggers a warning, this may give you a lot more chance that someone tries to look into this 🙏.

    I would expect that warnings.simplefilter would work (I am guessing you did the right import to have ConvergenceWarning defined although you have not included it), but maybe there are subtleties involved with subprocesses, not sure ...

  3. added
    Needs Reproducible Code
    on Jun 19, 2024
  4. lesteve commented on Jun 19, 2024

    @lesteve
    Member

    Hmmm looking at SO myself, it seems like indeed this is subprocesses with joblib, see this answer.

    Basically warnings filters only applied to the main process and not the subprocesses. One proposed solution in the SO answer is to:

    • use warnings.simplefilter for the warnings in the main process
    • set the environment variable PYTHONWARNINGS for the warnings in the subprocesses launched by joblib

    @u3Izx9ql7vW4 can you confirm this fixes the issue for you?

    In an ideal world, you would not need this work-around. In our imperfect world, I don't really know if there is some magic we can do in joblib and/or loky to have the subprocesses inherit the warnings filters from the main process ...

    In any cases this should be an issue in joblib I think: I opened joblib/joblib#1591.

    An alternative may actually be to use our already existing joblib wrappers like delayed to apply the warning filters to subprocesses, not sure how doable this is and that would be scikit-learn specific.

  5. ogrisel commented on Jun 19, 2024

    @ogrisel
    Member

    In the future we will all use free-threading CPython 3.13 or later and use a threading backend instead of subprocesses :)

  6. lesteve commented on Jun 19, 2024

    @lesteve
    Member

    In the future we will all use free-threading CPython 3.13 or later and use a threading backend instead of subprocesses :)

    Yeah that's the ideal world future 🤞 but still some road to get there 😉

  7. jeremiedbb commented on Jun 20, 2024

    @jeremiedbb
    Member

    We could add an option to disable convergence warnings (or warning of a given category) in the global config and define our own warn function that would check the global config to trigger or not the warning. It should work in all settings since the global config is now propagated to sub-processes.

  8. removed
    Needs Triage
    on Jun 20, 2024
  9. lesteve commented on Jun 20, 2024

    @lesteve
    Member

    We could add an option to disable convergence warnings (or warning of a given category) in the global config and define our own warn function that would check the global config to trigger or not the warning.

    Good point indeed! We could indeed, whether we should is another question, since free-threading is coming 🤞 and there is some kind of not so great but at least existing work-around 😰 ...

    Edit: thinking about it more, the config-based solution, may be a reasonable stop-gap solution, I guess someone maybe should have a closer look? Maybe an issue for a sprint? Personally I am not planning to look at it in the near-future. I am going to set the label "Help Wanted"

  10. added
    Moderate
    on Jun 20, 2024
  11. erickdcohen commented on Oct 13, 2024

    @erickdcohen

    Ran into this issue as well. Dropping a reproducible example:

    import warnings
    import numpy as np
    import pandas as pd
    from sklearn.exceptions import ConvergenceWarning
    from sklearn.linear_model import LogisticRegression
    from sklearn.model_selection import RandomizedSearchCV
    
    warnings.filterwarnings("ignore", category=ConvergenceWarning)
    
    X_train = pd.DataFrame(
        data={
            "a": np.linspace(0, 1, 100),
            "b": 1 + np.linspace(0, 1, 100),
            "c": np.repeat([1, 0], 50),
        }
    )
    
    y_train = np.repeat([np.repeat(1, 5), np.repeat(0, 5)], 10)
    
    lr = LogisticRegression(
        penalty="elasticnet",
        l1_ratio=0.5,
        solver="saga",
        max_iter=10,
        random_state=103,
    )
    
    log_reg_params = {
        "tol": (1e-3, 5e-2, 1e-2),
        "C": np.linspace(0.01, 0.8, 5),
    }
    
    
    random_search = RandomizedSearchCV(
        estimator=lr,
        param_distributions=log_reg_params,
        cv=5,
        random_state=104,
        n_jobs=-1, # IF N_JOBS IS 1, THEN NO WARNING
    )
    
    random_search.fit(X_train, y_train)

    output repeated: [/Users/~/.venv/lib/python3.12/site-packages/sklearn/linear_model/_sag.py:349](https://file+.vscode-resource.vscode-cdn.net/Users/~/.venv/lib/python3.12/site-packages/sklearn/linear_model/_sag.py:349):ConvergenceWarning: The max_iter was reached which means the coef_ did not converge warnings.warn(

    Machine info

    Operating System: Darwin
    OS Version: Darwin Kernel Version 20.6.0: Thu Jul  6 22:12:47 PDT 2023; root:xnu-7195.141.49.702.12~1/RELEASE_X86_64
    Machine Architecture: x86_64
    Python Version: 3.12.6
    Number of CPU Cores: 4
    
    Scikit-learn and dependencies info:
    
    System:
        python: 3.12.6 (v3.12.6:a4a2d2b0d85, Sep  6 2024, 16:08:03) [Clang 13.0.0 (clang-1300.0.29.30)]
    executable: [/Users/~/.venv/bin/python](https://file+.vscode-resource.vscode-cdn.net/Users/~/.venv/bin/python)
       machine: macOS-11.7.10-x86_64-i386-64bit
    
    Python dependencies:
          sklearn: 1.5.2
              pip: 24.2
       setuptools: None
            numpy: 2.1.2
            scipy: 1.14.1
           Cython: None
           pandas: 2.2.3
       matplotlib: 3.9.2
           joblib: 1.4.2
    threadpoolctl: 3.5.0
    
  12. removed
    Needs Reproducible Code
    on Oct 16, 2024
  13. ogrisel commented on Nov 18, 2024

    @ogrisel
    Member

    An alternative may actually be to use our already existing joblib wrappers like delayed to apply the warning filters to subprocesses, not sure how doable this is and that would be scikit-learn specific.

    I think this might be a better option, no? This would fix the problem for any kind of warnings and not just convergence warnings.

    Alternatively, we could make joblib itself do this automatically, but I am a bit worried about the extra complexity and potential overhead.

  14. erickdcohen commented on Nov 21, 2024

    @erickdcohen

    I agree that this seems like a joblib issue. I was thinking of just adding the stop-gap as suggested under Steve's comment that "free-threading" is in the works:

    We could add an option to disable convergence warnings (or warning of a given category) in the global config and define our own warn function that would check the global config to trigger or not the warning.

    Good point indeed! We could indeed, whether we should is another question, since free-threading is coming 🤞 and there is some kind of not so great but at least existing work-around 😰 ...

    Edit: thinking about it more, the config-based solution, may be a reasonable stop-gap solution, I guess someone maybe should have a closer look? Maybe an issue for a sprint? Personally I am not planning to look at it in the near-future. I am going to set the label "Help Wanted"

    I am unclear about "free threading" and how this would solve the issue, but agree that as a stop-gap this works. Can someone explain what is in the works for "free threading"?

  15. lesteve commented on Nov 29, 2024

    @lesteve
    Member

    Here is a slightly less hacky work-around than #29294 (comment) based on the fact that loky (the default joblib backend) is trying to reuse the same processes. It may also work for backend='multiprocessing' on POSIX, since the default start method is fork (until Python <= 3.13) even though workers are not reused (not sure and not tested).

    from joblib import Parallel, delayed
    
    def set_warnings_filters():
        warnings.filterwarnings("ignore", category=ConvergenceWarning)
    
    n_jobs = 2
    
    set_warnings_filters()
    # I used 2*n_jobs just to be safe and make sure that set_warnings_filters is called on all workers
    Parallel(n_jobs=n_jobs)(delayed(set_warnings_filters)() for _ in range(2*n_jobs))

    The reproducer from @erickdcohen (thanks by the way!) does not give any warnings for me with this:

    import warnings
    import numpy as np
    import pandas as pd
    from joblib import Parallel, delayed
    from sklearn.exceptions import ConvergenceWarning
    from sklearn.linear_model import LogisticRegression
    from sklearn.model_selection import RandomizedSearchCV
    
    def set_warnings_filters():
        warnings.filterwarnings("ignore", category=ConvergenceWarning)
    
    n_jobs = 2
    
    set_warnings_filters()
    # I used 2*n_jobs just to be safe and make sure that set_warnings_filters is called on all workers
    Parallel(n_jobs=n_jobs)(delayed(set_warnings_filters)() for _ in range(2*n_jobs))
    
    X_train = pd.DataFrame(
        data={
            "a": np.linspace(0, 1, 100),
            "b": 1 + np.linspace(0, 1, 100),
            "c": np.repeat([1, 0], 50),
        }
    )
    
    y_train = np.repeat([np.repeat(1, 5), np.repeat(0, 5)], 10)
    
    lr = LogisticRegression(
        penalty="elasticnet",
        l1_ratio=0.5,
        solver="saga",
        max_iter=10,
        random_state=103,
    )
    
    log_reg_params = {
        "tol": (1e-3, 5e-2, 1e-2),
        "C": np.linspace(0.01, 0.8, 5),
    }
    
    
    random_search = RandomizedSearchCV(
        estimator=lr,
        param_distributions=log_reg_params,
        cv=5,
        random_state=104,
        n_jobs=n_jobs, # IF N_JOBS IS 1, THEN NO WARNING
    )
    
    random_search.fit(X_train, y_train)

    Longer-term I think that tackling this in joblib adding initializers function to all the backend joblib/joblib#381 seems one way to go although this is definitely not going to happen overnight.

    @erickdcohen about free-threading, this is an experimental interpreter in CPython 3.13 that allows you to have efficient multi-threading by removing the GIL (Global Interpreter Lock), see https://py-free-threading.github.io/ for more details. If you are using multi-threading warnings.filters are shared in all workers in contrary to multi-processing where you have separate Python processes with separate warnings.filters.

  16. erickdcohen commented on Dec 2, 2024

    @erickdcohen

    I see! Thank you @lesteve for the explanation and the work around!

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

    Moderatehelp wanted

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions