【问题标题】:"SystemError: <class 'int'> returned a result with an error set" in PythonPython 中的“SystemError:<class 'int'> 返回了带有错误集的结果”
【发布时间】:2019-05-16 16:49:14
【问题描述】:

我想使用来自scipyndimage.generic_filter() 应用一个非常简单的函数。这是代码:

import numpy as np
import scipy.ndimage as ndimage

data = np.random.rand(400,128)
dimx = int(np.sqrt(np.size(data,0)))
dimy = dimx    
coord = np.random.randint(np.size(data,0), size=(dimx,dimy))

def test_func(values):
    idx_center = int(values[4])
    weight_center = data[idx_center]
    weights_around = data[values]
    differences = weights_around - weight_center
    distances = np.linalg.norm(differences, axis=1)
    return np.max(distances)

results = ndimage.generic_filter(coord,
                                 test_func,
                                 footprint = np.ones((3,3)))

当我执行它时,会出现以下错误:

SystemError: <class 'int'> returned a result with an error set

当试图将values[4] 强制转换为int 时。如果我运行函数test_func() 而不使用ndimage.generic_filter() 作为随机数组values,则该函数可以正常工作。

为什么会出现这个错误?有没有办法让它工作?

【问题讨论】:

  • idx_center = int(values[4]) 想要达到什么目的?当您将coord 传递给test_func 时,values[4] 是一个nparray,因此您无法将其转换为an int,并且int(coord[4]) 返回错误:only size-1 arrays can be converted to Python scalars
  • 我怀疑这是一个 SciPy 错误; values 将是一个浮点值数组,因此weights_around = data[values] 行应该生成一个IndexError。显然有些东西破坏了ndimage.generic_filter 中的错误处理。您能否在github.com/scipy/scipy/issues 上为此创建一个新问题?

标签: python scipy runtime-error


【解决方案1】:

对于你的情况:

这一定是 Python 或 SciPy 中的错误。请在https://bugs.python.org 和/或https://www.scipy.org/bug-report.html 提交错误。包括 Python 和 NumPy/SciPy 的版本号、您在此处拥有的完整代码以及整个回溯。

(另外,如果你能找到一种不需要使用随机性来触发这个错误的方法,他们可能会喜欢它。但如果你找不到这样的方法,那么请把它归档为-是。)

一般来说:

“[R]返回带有错误集的结果”是只能在 C 级别完成的事情。 通常,Python/C API 期望大多数 C 函数执行以下两种操作之一:

  1. 使用these functions 之一设置异常并返回NULL(对应于抛出异常)。
  2. 不要设置异常并返回“真实”值,通常是PyObject*(对应于返回值,包括returning None)。

这两种情况通常都不正确:

  1. 设置异常(或无法清除已存在的异常),但随后返回NULL 以外的其他值。
  2. 不设置异常,然后返回NULL

Python 提出了一个SystemError,因为在 Python 标准库中,int 的实现试图做 (3),可能是因为 SciPy 先做的。这总是错误的,因此 Python 或它调用的 SciPy 代码中肯定存在错误。

【讨论】:

    【解决方案2】:

    我在 Linux 上使用 Python 3.8.1 和 SciPy 1.4.1 的体验非常相似。一种解决方法是引入np.floor,以便:

    centre = int(window.size / 2) 变为 centre = int(np.floor(window.size/2))

    这似乎已经解决了问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-13
      • 2017-09-24
      • 2020-09-02
      • 1970-01-01
      • 2015-05-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多