【问题标题】:Numpy divide by zero encountered in true_divide on np.where()在 np.where() 上的 true_divide 中遇到 Numpy 除以零
【发布时间】:2020-11-09 07:26:48
【问题描述】:

当我得到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)
print(np.all((p_arr - 0.5 != 0))) # FALSE
print(np.all((x - 0.5 != 0))) # TRUE

【问题讨论】:

  • 嗯,大概它发生在(p_arr - 0.5) == 0的任何地方
  • 注意,这是一个警告,而不是错误。

标签: python python-3.x numpy


【解决方案1】:

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

重要的是,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)

哪个应该给你你得到divide by zero错误的坐标

【讨论】:

  • 所以基本上我不应该太在意它或者如何让它正确(和快速)?
  • 哦,是的,这不是答案,它只是显示您的问题所在。我的错,一秒钟。
  • 在我看来,显示问题是一个非常好的答案。我们(至少我是)在这里教书,而不仅仅是提供快速修复。
  • ok thanx,函数比示例中的更复杂,而且我有时也会遇到溢出错误,有什么方法可以在不手动遍历数组的情况下调试它?显示数组的 x,y 还是值?
  • 我不能从有限的信息中看出,不。最好问另一个问题,而不是在评论中更改您的要求。如果这有帮助,请记得标记已解决。
【解决方案2】:

尝试添加这个:

np.seterr(divide='ignore', invalid='ignore')

【讨论】:

  • 忘了说它是python 3,没关系,在python 2中应该没关系,因为第二个参数是0.5,所以如果它们中的任何一个是float,结果会浮动
  • 可能在 (-6.93/(p_arr - 0.5))。在你的数组中的某个点你有 0.5 - 0.5 所以你不能除以零“-6.93/0”
  • 这就是为什么我使用np.wherep_arr > 0.5
  • 和?不明白你在说什么;我删除了 exp(),没有它也是一样的
  • 我认为 np.where 在评估条件之前先进行除法,然后选择存储哪个。尝试这样做: import numpy as np p_arr = 0.5 mo = np.where(0.4 > 0.5, -6.93/(p_arr - 0.5), 0) print(mo) 这应该返回 0,但你会得到一个错误。可能如果你把 np.where 放在 if else 里面可以工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 2015-03-06
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 2016-07-13
  • 2019-05-08
相关资源
最近更新 更多