Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python warnings.filterwarnings does not ignore DeprecationWarning from 'import sklearn.ensemble'

I am trying to silence the DeprecationWarning with the following method.

import warnings
warnings.filterwarnings(action='ignore')
from sklearn.ensemble import RandomForestRegressor

However, it still shows:

DeprecationWarning: numpy.core.umath_tests is an internal NumPy module and should not be imported. It will be removed in a future NumPy release. from numpy.core.umath_tests import inner1d

Why does this happen, and how can I fix it?

I'm running this on python 3.6.6, numpy 1.15.0 and scikit-learn 0.19.2, and adding category=DeprecationWarning didn't help.

like image 505
Eun Jee Lee Avatar asked Sep 07 '18 14:09

Eun Jee Lee


People also ask

How do I ignore warnings in Sklearn?

with warnings. catch_warnings(): warnings. simplefilter("ignore") from sklearn import preprocessing /usr/local/lib/python3. 5/site-packages/sklearn/utils/fixes.

How do I remove deprecation warnings in Python?

When nothing else works: $ pip install shutup . Then at the top of the code import shutup;shutup. please() . This will disable all warnings.

How do I hide DeprecationWarning?

Answer #1: If you're on Windows: pass -W ignore::DeprecationWarning as an argument to Python. Better though to resolve the issue, by casting to int. (Note that in Python 3.2, deprecation warnings are ignored by default.)

How do I turn off warnings in Python?

Use the filterwarnings() Function to Suppress Warnings in Python. The warnings module handles warnings in Python. We can show warnings raised by the user with the warn() function. We can use the filterwarnings() function to perform actions on specific warnings.


1 Answers

The reason this happens is that Scikit resets your DeprecationWarning filter when you import it:

# Make sure that DeprecationWarning within this package always gets printed
warnings.filterwarnings('always', category=DeprecationWarning,
                        module=r'^{0}\.'.format(re.escape(__name__)))

Sneaky!

The only fix I've found is to temporarily suppress stderr:

import os
import sys
sys.stderr = open(os.devnull, "w")  # silence stderr
from sklearn.ensemble import RandomForestRegressor
sys.stderr = sys.__stderr__  # unsilence stderr

where sys.__stderr__ refers to the system's actual stderr (as opposed to sys.stderr, which just tells Python where to print stderr to).

like image 129
1'' Avatar answered Sep 27 '22 15:09

1''