为什么我不能禁止显示numpy警告

mlmc2os5  于 2023-05-07  发布在  其他
关注(0)|答案(4)|浏览(214)

我真的想避免这些恼人的numpy警告,因为我必须处理大量的NaNs。我知道这通常是用seterr完成的,但由于某种原因,它在这里不起作用:

import numpy as np
data = np.random.random(100000).reshape(10, 100, 100) * np.nan
np.seterr(all="ignore")
np.nanmedian(data, axis=[1, 2])

它给了我一个运行时警告,即使我设置numpy忽略所有错误...有帮助吗?
编辑(这是收到的警告):
/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-p ackages/numpy/lib/nanfunctions.py:612:运行时警告:All-NaN slice encountered warnings.warn(“All-NaN slice encountered”,RuntimeWarning)

bis0qfac

bis0qfac1#

警告通常是有用的,在大多数情况下,我不建议这样做,但你总是可以使用Warnings模块来忽略filterwarnings的所有警告:

warnings.filterwarnings('ignore')

如果要唯一地隐藏特定错误,可以使用以下命令指定:

with warnings.catch_warnings():
    warnings.filterwarnings('ignore', r'All-NaN (slice|axis) encountered')
8ehkhllq

8ehkhllq2#

seterr()控制的警告是由numpy ufunc机器发出的警告;例如,当A / B在实现除法的C代码中创建NaN时,因为在这些数组中的某个位置存在inf/inf。其他numpy代码可能会因为其他原因发出自己的警告。在本例中,您使用的是NaN-忽略归约函数之一,如nanmin()等。您向它传递一个数组,该数组包含所有NaN s,或者至少包含所有NaN s,这些NaN s沿着您请求减少的轴。由于使用nanmin()的通常原因是不想再取出另一个NaN,因此nanmin()将发出警告,表示它别无选择,只能给予您一个NaN。这直接进入标准库warnings机器,而不是numpy ufunc错误控制机器,因为它不是ufunc,并且NaN的生成与seterr(invalid=...)处理的不一样。

sg3maiej

sg3maiej3#

您可能希望避免隐藏警告,因为numpy引发此警告是有充分理由的。如果你想清理你的输出,当你的数组都是nan时,也许可以通过显式返回一个预定义的值来处理它。

def clean_nanmedian(s):
    if np.all(np.isnan(s)):
        return np.nan
    return np.nanmedian(s)

另外,请记住,只有在运行时中第一次发生这种情况时,才会引发此RuntimeWarning。

nfzehxib

nfzehxib4#

使用

def fxn():
    warnings.warn("deprecated", DeprecationWarning)
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    warnings.filterwarnings('ignore', r'All-NaN (slice|axis) encountered')
    fxn()

我没有抑制所有Numpy警告,事实上我仍然可以看到sklearn / numpy相关的警告,如

/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):

要完全删除这些问题,我的解决方案非常简单

import numpy as np
np.seterr(all="ignore")

把所有这些放在一起,我做了这个suppressAllWarnings,可以进一步定制:

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

相关问题