跟踪 Python 警告/错误到 numpy 和 scipy 中的行号

发布于 2024-10-03 01:15:57 字数 272 浏览 0 评论 0原文

我收到错误:

Warning: invalid value encountered in log

From Python 并且我相信该错误是由 numpy 引发的(使用版本 1.5.0)。但是,由于我在几个地方调用“log”函数,所以我不确定错误来自哪里。有没有办法让 numpy 打印生成此错误的行号?

我认为该警告是由于取一个足够小的数字的对数而引起的,该数字足够小,可以四舍五入到 0 或更小(负数)。是这样吗?这些警告的通常来源是什么?

I am getting the error:

Warning: invalid value encountered in log

From Python and I believe the error is thrown by numpy (using version 1.5.0). However, since I am calling the "log" function in several places, I'm not sure where the error is coming from. Is there a way to get numpy to print the line number that generated this error?

I assume the warning is caused by taking the log of a number that is small enough to be rounded to 0 or smaller (negative). Is that right? What is the usual origin of these warnings?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

南风起 2024-10-10 01:15:57

np.seterr(invalid='raise') 放入代码中(在错误的 log 调用之前)
将导致 numpy 引发异常而不是发出警告。
这将为您提供一条回溯错误消息,并告诉您发生错误时 Python 正在执行的行。

Putting np.seterr(invalid='raise') in your code (before the errant log call)
will cause numpy to raise an exception instead of issuing a warning.
That will give you a traceback error message and tell you the line Python was executing when the error occurred.

無心 2024-10-10 01:15:57

如果您有权访问 numpy 源代码,则应该能够找到打印该警告的行(使用 grep 等),并编辑相应的文件以在传递无效值时强制出现错误(例如使用断言) 。这将为您提供一个堆栈跟踪,指向代码中使用不正确的值调用 log 的位置。

我简要查看了我的 numpy 源代码,但找不到任何与您描述的警告相匹配的内容(不过,我的 numpy 版本比您的版本旧)。

>>> import numpy
>>> numpy.log(0)
-inf
>>> numpy.__version__
'1.3.0'

您是否有可能调用 numpy 中没有的其他日志函数?例如,下面的例子在给出无效输入时实际上会引发异常。

>>> import math
>>> math.log(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error

If you have access to the numpy source, you should be able to find the line that prints that warning (using grep, etc) and edit the corresponding file to force an error (using an assertion, for example) when an invalid value is passed. That will give you a stack trace pointing to the place in your code that called log with the improper value.

I had a brief look in my numpy source, and couldn't find anything that matches the warning you described though (my version of numpy is older than yours, though).

>>> import numpy
>>> numpy.log(0)
-inf
>>> numpy.__version__
'1.3.0'

Is it possible that you're calling some other log function that isn't in numpy? For example, here is one that actually throws an exception when given invalid input.

>>> import math
>>> math.log(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文