【问题标题】:UserWarning: converting a masked element to nanUserWarning:将掩码元素转换为 nan
【发布时间】:2013-04-26 12:36:47
【问题描述】:

执行我写的 python 脚本(在这里包含很长)会导致一条警告消息。我不知道这是在我的代码中的哪一行提出的。我怎样才能得到这些信息?

此外,这究竟是什么意思?事实上,我不知道我在使用某种掩码数组?

/usr/lib/pymodules/python2.7/numpy/ma/core.py:3785: UserWarning: Warning: converting a masked element to nan.
warnings.warn("Warning: converting a masked element to nan.")

【问题讨论】:

  • 我会在您的代码中围绕所有可能的罪魁祸首添加很多 print 语句,这将为您提供正在发生的事情的时间表,在您的 prints 之间的某个位置,您将看到此警告, 这样您就可以本地化您的问题。如果有帮助,警告来自MaskedArray.__float__,它显然将数组转换为浮点数。另一种方法是(临时)编辑core.py 以使其输出有用的信息,例如数组的属性。调试器也是可行的选择。
  • 打印语句帮我找到了对应的行,谢谢!我只是认为可能有更复杂的解决方案。

标签: python numpy


【解决方案1】:

您可以使用warnings 模块将警告转换为异常。最简单的方法称为simplefilter。这是一个例子;生成警告的代码在 func2b() 中,因此有一个非常重要的回溯。

import warnings


def func1():
    print("func1")

def func2():
    func2b()
    print("func2")

def func2b():
    warnings.warn("uh oh")

def func3():
    print("func3")


if __name__ == "__main__":
    # Comment the following line to see the default behavior.
    warnings.simplefilter('error', UserWarning)
    func1()
    func2()
    func3()

当包含对simplefilter 的调用的行被注释掉时,输出为

func1
warning_to_exception.py:13: UserWarning: uh oh
  warnings.warn("uh oh")
func2
func3

包含该行后,您将获得回溯:

func1
Traceback (most recent call last):
  File "warning_to_exception.py", line 23, in <module>
    func2()
  File "warning_to_exception.py", line 9, in func2
    func2b()
  File "warning_to_exception.py", line 13, in func2b
    warnings.warn("uh oh")
UserWarning: uh oh

【讨论】:

    【解决方案2】:

    还可以修补MaskedArray.__float__ 使其引发异常,这样您就可以看到堆栈跟踪,其中包括您的代码。并且可以在您的代码中进行修补,无需弄乱.../ma/core.py

    squeeze() 的示例:

    import numpy as np
    from numpy import ma
    
    def raise_me(*args, **kw):
        raise Exception('ping')
    
    ma.MaskedArray.squeeze = raise_me
    
    def test():
        x = np.array([(1, 1.), (2, 2.)], dtype=[('a',int), ('b', float)])
        m = x.view(ma.MaskedArray)
        m.squeeze()
    
    def main():
        test()
    
    main()
    

    然后输出:

    Traceback (most recent call last):
      File "t.py", line 19, in <module>
        main()
      File "t.py", line 17, in main
        test()
      File "t.py", line 13, in test
        m.squeeze()
      File "t.py", line 6, in raise_me
        raise Exception('ping')
    Exception: ping
    

    如您所见,它向您显示了带有m.squeeze() 的行。

    【讨论】:

      猜你喜欢
      • 2018-05-19
      • 2021-09-27
      • 2020-12-22
      • 2022-10-18
      • 2021-07-15
      • 2016-02-15
      • 1970-01-01
      • 2018-11-30
      • 2021-09-18
      相关资源
      最近更新 更多