Using
def fxn():
warnings.warn("deprecated", DeprecationWarning)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
warnings.filterwarnings('ignore', r'All-NaN (slice|axis) encountered')
fxn()
did not suppress all Numpy warnings, in fact I still can see sklearn / numpy related warnings like
/usr/local/lib/python3.7/site-packages/sklearn/linear_model/randomized_l1.py:580: DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.
Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations
eps=4 * np.finfo(np.float).eps, n_jobs=None,
/usr/local/lib/python3.7/site-packages/sklearn/feature_extraction/image.py:167: DeprecationWarning: `np.int` is a deprecated alias for the builtin `int`. To silence this warning, use `int` by itself. Doing this will not modify any behavior and is safe. When replacing `np.int`, you may wish to use e.g. `np.int64` or `np.int32` to specify the precision. If you wish to review your current use, check the release note link for additional information.
Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations
dtype=np.int):
To remove those ones as well completely my solution was as simple as
import numpy as np
np.seterr(all="ignore")
Putting all together I did this suppressAllWarnings
that can be furtherly customized:
def suppressAllWarnings(params={}):
'''
LP: suppress all warnings
params = { regex: [ String ] }
'''
options = {
"level": "ignore",
"regex": [ r'All-NaN (slice|axis) encountered' ]
}
for attr in params:
options[attr]=params[attr]
import warnings
# system-wide warning
def fxn():
warnings.warn("deprecated", DeprecationWarning)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
fxn()
# LP custom regex warning
for regex in options['regex']:
warnings.filterwarnings('ignore', regex)
# by module warnings
try:
# numpy warnings
import numpy as np
np.seterr(all=options['level'])
except:
pass
suppressAllWarnings()
[EDIT]
This function cannot solve import level issues, in that case it may help to surround the import with suppress_warnings
:
with np.testing.suppress_warnings() as sup:
sup.filter(DeprecationWarning)
from sklearn.linear_model import LogisticRegression
from sklearn.feature_extraction.text import TfidfVectorizer