在 np.where() 上的 true_divide 中遇到的 Numpy 除以零 [英] Numpy divide by zero encountered in true_divide on np.where()

查看:67
本文介绍了在 np.where() 上的 true_divide 中遇到的 Numpy 除以零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我得到 np.where 试图避免被零除时,我仍然收到错误,即使 p_arr - 0.5 应该总是 >0.

mo = np.where(p_arr > 0.5, -6.93/(p_arr - 0.5), 10)

<块引用>

RuntimeWarning: 在 true_divide 中遇到除以零

<块引用>

mo = np.where(p_arr > 0.5, -6.93/(p_arr - 0.5), 10)

知道为什么以及如何解决这个问题吗?另外有什么方法可以正确调试它,因此错误会显示 p_arr 的确切值是多少?

一些测试:

x = np.where(p_arr > 0.5, p_arr, 1)打印(np.all((p_arr - 0.5 != 0))) # FALSE打印(np.all((x - 0.5 != 0))) # TRUE

解决方案

np.where 的伪代码:

def np_where(chooser, true_opt, false_opt):out = np.empty(chooser.shape, dtype = true_opt.dtype)out[~chooser] = false_opt回来

重要的是,true_opt 是在调用函数之前 生成的.因此,如果其中的任何内容引发错误,解释器永远不会调用 np.where - 即使 np.where 永远不会使用 true_opt 引发错误.

您可以摆脱 divide by zero 错误,但不要按照其他答案中的建议使用 np.seterr - 这将关闭它整个会话,并可能导致其他代码位出现问题.你可以这样做:

with np.errstate(divide='ignore'):mo = np.where(p_arr > 0.5, -6.93/(p_arr - 0.5), 10)

要找出错误的来源,只需使用:

np.where(p_arr == 0.5)

哪个应该给你得到除以零错误的坐标

When I got np.where that tries to avoid division by zero, I am still getting the error, even when p_arr - 0.5 should be always > 0.

mo = np.where(p_arr > 0.5, -6.93/(p_arr - 0.5), 10)

RuntimeWarning: divide by zero encountered in true_divide

mo = np.where(p_arr > 0.5, -6.93/(p_arr - 0.5), 10)

Any idea why and how to fix that? Additionally is there any way to debug it properly, so the error would show what was the exact value from p_arr?

Some tests:

x = np.where(p_arr > 0.5, p_arr, 1)
print(np.all((p_arr - 0.5 != 0))) # FALSE
print(np.all((x - 0.5 != 0))) # TRUE

解决方案

pseudocode for np.where:

def np_where(chooser, true_opt, false_opt):
    out = np.empty(chooser.shape, dtype = true_opt.dtype) 
    out[~chooser] = false_opt
    return out

Importantly, true_opt is generated before calling the function. So if anything in it raises an error, the interpreter never gets to call np.where - even if np.where would never use the parts of true_opt that raise the error.

You can get rid of the divide by zero errors, but don't use np.seterr as recommended in the other answer - that will shut it off for the whole session and may cause problems with other bits of code. You can do it like this:

with np.errstate(divide='ignore'):
    mo = np.where(p_arr > 0.5, -6.93/(p_arr - 0.5), 10)

To find out where your error was coming from, just use:

np.where(p_arr == 0.5)

Which should give you the coordinates where you were getting the divide by zero error

这篇关于在 np.where() 上的 true_divide 中遇到的 Numpy 除以零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆