Skip to content

RandomizedSearchCV: warnings cannot be suppressed #12939

Closed

Description

@yihengli

Description

I would like to suppress the warnings thrown by sklearn. This can be done while I was working on a single classifier, however, it failed on SearchCV task. I am wondering if this is designed for purpose and if there are any workarounds.

Steps/Code to Reproduce

File 1 (No warnings)

import warnings
import sklearn
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import RandomizedSearchCV
import pandas as pd
import numpy as np


x = np.random.normal(0, 1, (100, 100))
y = [0] * 50 + [1] * 50

if __name__ == "__main__":
    warnings.filterwarnings("ignore")
    clf = LogisticRegression()
    clf.fit(x, y)
    clf.predict(x)
    print("done")

Run the code from terminal

File 2 (Warnings still exist)

import warnings
import sklearn
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import RandomizedSearchCV
import pandas as pd
import numpy as np


x = np.random.normal(0, 1, (100, 100))
y = [0] * 50 + [1] * 50

if __name__ == "__main__":
    warnings.filterwarnings("ignore")
    clf = LogisticRegression()
    clf = RandomizedSearchCV(clf, {"C": [1,2]}, n_jobs=-1)
    clf.fit(x, y)
    clf.predict(x)
    print("done")

Expected Results

should see done from terminal. While the second file gave me multiple FutureWarning

Actual Results

As above

Versions

appnope==0.1.0
backcall==0.1.0
certifi==2018.11.29
Click==7.0
cycler==0.10.0
decorator==4.3.0
feather-format==0.4.0
ipykernel==5.1.0
ipython==7.2.0
ipython-genutils==0.2.0
jedi==0.13.2
jupyter-client==5.2.4
jupyter-core==4.4.0
kiwisolver==1.0.1
matplotlib==3.0.2
mkl-fft==1.0.6
mkl-random==1.0.2
numpy==1.15.4
pandas==0.23.4
parso==0.3.1
pexpect==4.6.0
pickleshare==0.7.5
prompt-toolkit==2.0.7
ptyprocess==0.6.0
pyarrow==0.11.1
Pygments==2.3.1
pyparsing==2.3.0
python-dateutil==2.7.5
pytz==2018.7
pyzmq==17.1.2
scikit-learn==0.20.2
scipy==1.1.0
six==1.12.0
tornado==5.1.1
traitlets==4.3.2
wcwidth==0.1.7
xlrd==1.2.0

Tested on 3.6.8 with MacOS 10.14

Activity

  1. baluyotraf commented on Jan 20, 2019

    @baluyotraf
    Contributor

    Looks like it has something to do with the multiprocessing since an n_jobs=1 removes the warning.

  2. jnothman commented on Jan 21, 2019

    @jnothman
    Member

    Yes, I'm guessing that somehow joblib is not maintaining the warnings environment across processes correctly. (@tomMoral?)

  3. yihengli commented on Jan 21, 2019

    @yihengli
    Author

    I forgot to mention this in my original description.

    I also tested this script in a Jupyter notebook, and warnings can be suppressed as expected. I was wondering if the warning or joblib mechanism is different from Jupyter and vanilla python

  4. baluyotraf commented on Jan 21, 2019

    @baluyotraf
    Contributor

    Jupyter will print it to the terminal you used after you close the notebook.

  5. tomMoral commented on Jan 21, 2019

    @tomMoral
    Contributor

    Yes the warning environment is reset when starting new workers with 'spawn' or 'forkexec' instead of 'fork'. This is actually the way it is implemented in python. I see no way to suppress the warning currently without changing the internals of worker spawning. If this is critical to your application, I guess you could use the multiprocessing backend by using paralell_backend('multiprocessing') in your script. Note that the main drawback of this solution is that you would revert to start_method='fork' which is known to cause bad interaction with third party library, in particular on OSX.

    import warnings
    from sklearn.utils import parallel_backend
    from sklearn.linear_model import LogisticRegression
    from sklearn.model_selection import RandomizedSearchCV
    import pandas as pd
    import numpy as np
    
    
    x = np.random.normal(0, 1, (100, 100))
    y = [0] * 50 + [1] * 50
    
    if __name__ == "__main__":
        warnings.filterwarnings("ignore")
        clf = LogisticRegression()
        clf = RandomizedSearchCV(clf, {"C": [1,2]}, n_jobs=-1)
        with parallel_backend('multiprocessing'):
            clf.fit(x, y)
            clf.predict(x)
        print("done")

    The warning management could be changed for the loky backend directly by sending warning.filters to the spawned workers. My two concerns would be that it would differ from the behavior in multiprocessing and only the filters set before the spawning of the worker would be taken into account. This means that if they change later, new workers would not have the same warning policy.

  6. jnothman commented on Jan 21, 2019

    @jnothman
    Member
  7. hermidalc commented on Jul 17, 2019

    @hermidalc
    Contributor

    @yihengli @tomMoral @jnothman

    In Python you can easily set warning filters that work for any spawned worker by setting the PYTHONWARNINGS env var dynamically in your code. loky workers will pick this up:

    os.environ["PYTHONWARNINGS"] = "ignore::UserWarning"

    Though since this applies globally until you unset it in your code then you want to be more specific:

    os.environ["PYTHONWARNINGS"] = "ignore:Liblinear failed to converge:UserWarning:sklearn.svm.base"

    You can specify multiple warning filters this way (https://docs.python.org/3/library/warnings.html#describing-warning-filters)

    I did see that there is an issue with Python currently that you cannot easily specify custom (subclass) warning categories this way (see https://stackoverflow.com/questions/42495641/filtering-based-on-custom-warning-categories and https://bugs.python.org/issue22543). There is a workaround that is described there by specifying PYTHONPATH, but that didn't work when I tried it:

    import sklearn.exceptions
    os.environ["PYTHONPATH"] = os.path.dirname(sklearn.exceptions.__file__)
    os.environ["PYTHONWARNINGS"] = "ignore::exceptions.ConvergenceWarning:sklearn.svm.base"

    Maybe I did something wrong but it follows exactly what was described. I even tried it from command line and still didn't work.

  8. e3vela commented on Sep 19, 2019

    @e3vela

    If you are using logs, a workaround would be using the logging module to capture warnings and set a filter:

    import logging
    
    logging.captureWarnings(capture=True)
    
    # Get logger for warnings
    logger = logging.getLogger("py.warnings")
    
    # StreamHandler outputs on sys.stderr by default
    handler = logging.StreamHandler()
    logger.addHandler(handler)
    
    # Set rule to ignore warnings
    logger.addFilter(lambda record: "ConvergenceWarning" not in record.getMessage())

    Other types of warnings will be printed on the console.

  9. JoElfner commented on Jul 30, 2020

    @JoElfner
    Contributor

    Any news on this? This reduces the usability of RandomizedSearchCV, since it hides useful information... Setting PYTHONWARNINGS works, but seems like a quite clumsy workaround...

  10. dmnapolitano commented on Feb 18, 2022

    @dmnapolitano

    Per @tomMoral 's comment, if you don't want to completely disable warnings for everything, this "resolves" the issue with Python 3.10, sci-kit learn 1.0.2 on Ubuntu 20.04:

    from sklearn.exceptions import ConvergenceWarning
    from sklearn.utils import parallel_backend
    ...
    
    gs = GridSearchCV(...)
    with parallel_backend("multiprocessing"):
      with warnings.catch_warnings():
        warnings.filterwarnings("ignore", category=ConvergenceWarning, module="sklearn")
        gs.fit(...)

    Hope this helps someone 😄

  11. KoszticzaM commented on Apr 8, 2022

    @KoszticzaM

    I'm experiencing the same issue even in jupyterlab under Linux.

  12. ZoharKol commented on May 24, 2022

    @ZoharKol

    Per @tomMoral 's comment, if you don't want to completely disable warnings for everything, this "resolves" the issue with Python 3.10, sci-kit learn 1.0.2 on Ubuntu 20.04:

    from sklearn.exceptions import ConvergenceWarning
    from sklearn.utils import parallel_backend
    ...
    
    gs = GridSearchCV(...)
    with parallel_backend("multiprocessing"):
      with warnings.catch_warnings():
        warnings.filterwarnings("ignore", category=ConvergenceWarning, module="sklearn")
        gs.fit(...)

    Hope this helps someone smile

    This indeed worked to eliminate ConvergenceWarning printing by the workers. But, at least, in my case it slowed down the search by two orders of magnitude.
    Guess the filtering on each warning message takes a lot of processing...

  13. lesteve commented on Jan 21, 2025

    @lesteve
    Member

    This should have been fixed in #30380. If needed as a stop-gap solution, see #29294 (comment) for a 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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions