python - 发生 RuntimeWarning 后暂停或停止 numpy 计算

标签 python numpy

我正在使用 numpy.optimize.fsolve 进行一些计算.由于初始值不正确,其中一些计算导致 RuntimeWarning 告诉

RuntimeWarning: The iteration is not making good progress, as measured by the improvement from the last ten iterations.
warnings.warn(msg, RuntimeWarning)

RuntimeWarning: The iteration is not making good progress, as measured by the improvement from the last five Jacobian evaluations.
warnings.warn(msg, RuntimeWarning)

由于我将所有初始值和所属结果写入文本文件(只是将标准输出传输到文件),所以我想了解在我大约 500 步的计算过程中发生上述 RuntimeWarnings 的线索。

numpy docs 中所述警告由 Python's standard warnings module 处理, 但有没有办法在第一次 RuntimeWarning 发生后停止或暂停计算?

最佳答案

如果您想在发出警告时终止计算,您可以使用 warnings 模块的功能强制将某些类型的警告作为异常引发。你可以这样写:

warnings.simplefilter('error')

这会将所有 警告变成错误并立即停止程序。缺点是无法通过简单地捕获异常来恢复计算:它永远完成了。

如果您希望暂停程序,您可以使用一些“hack”来覆盖warnings 模块用来显示警告的函数。文档明确允许覆盖此函数,尽管我们目前的目的与文档的想法不同。这是一个简单的警告处理程序,它询问用户是否继续。如果用户拒绝,错误将升级为异常:

def handle_warning(message, category, filename, lineno, file=None, line=None):
    print('A warning occurred:')
    print(message)
    print('Do you wish to continue?')

    while True:
        response = input('y/n: ').lower()
        if response not in {'y', 'n'}:
            print('Not understood.')
        else:
            break

    if response == 'n':
        raise category(message)

然后我们覆盖默认警告处理程序:

warnings.showwarning = handle_warning

现在我们尝试优化一个平面函数:

from scipy.optimize import fsolve
fsolve(lambda x: 1, 1)

我们几乎立即收到一条消息:

A warning occurred:
The iteration is not making good progress, as measured by the 
  improvement from the last ten iterations.
Do you wish to continue?
y/n:

如果我们回答y,优化将被允许继续并返回它的结果。如果我们回答 n,则会引发异常并终止计算。

上下文管理器解决方案

或者,如果您不想在模块级别覆盖 showwarning 函数,您可以使用上下文管理器。我们可以把它放在一个函数中,把所有的东西都包装得漂亮整洁:

def pause_if_warning(function, *args, **kwargs):
    with warnings.catch_warnings():
        warnings.showwarning = handle_warning
        return function(*args, **kwargs)

所以我们现在可以写:

pause_if_warning(fsolve, lambda x: 1, 1)

获得与上述相同的行为。

关于python - 发生 RuntimeWarning 后暂停或停止 numpy 计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30983866/

相关文章:

python - Tensorflow session 不执行函数

python - 使用 pandas 和 numpy 获取差异并消除间隙时间序列数据

python - Django 双向 ManyToMany - 如何防止在第二个模型上创建表?

python - 使用格式化函数没有得到我想要的

python - 端口 9050 未监听 tb selenium

python - 将字典保存到文件 Python

python - 使用 pandas 或 numpy 将不规则列数据读入 python 3.X

python - 带参数调用程序

python - 使用 numpy 数组时如何消除 for 循环并使用列表理解?

python - 当选择和更新都存在复杂条件时,更新数据框的最快方法是什么?