调试 Numpy VisibleDeprecationWarning(来自参差不齐的嵌套序列的 ndarray)

新手上路,请多包涵

从 NumPy 版本 19.0 开始,从“不规则”序列创建数组时必须指定 dtype=object 。我面临着来自我自己的代码和使用线程的 Pandas 的大量数组调用,逐行调试让我无处可去。

我想弄清楚哪个调用导致了我自己的代码中的 VisibleDeprecationWarning 或来自 Pandas 的调用。我怎么能调试这个?我一直在查看源代码,但看不到在 Python 中调用此警告(仅在 numpy.core._multiarray_umath.cp38-win_amd64.pyd 中)。

原文由 misantroop 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

使用创建参差不齐的数组的函数:

 In [60]: def foo():
    ...:     print('one')
    ...:     x = np.array([[1],[1,2]])
    ...:     return x
    ...:
In [61]: foo()
one
/usr/local/bin/ipython3:3: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray
  # -*- coding: utf-8 -*-
Out[61]: array([list([1]), list([1, 2])], dtype=object)

我得到了警告,但也得到了预期的结果。

我可以控制警告。

例如关闭:

 In [68]: np.warnings.filterwarnings('ignore', category=np.VisibleDeprecationWarning)
In [69]: foo()
one
Out[69]: array([list([1]), list([1, 2])], dtype=object)

或者引发错误:

 In [70]: np.warnings.filterwarnings('error', category=np.VisibleDeprecationWarning)
In [71]: foo()
one
---------------------------------------------------------------------------
VisibleDeprecationWarning                 Traceback (most recent call last)
<ipython-input-71-c19b6d9633cf> in <module>
----> 1 foo()

<ipython-input-60-6ad21d9e07b4> in foo()
      1 def foo():
      2     print('one')
----> 3     x = np.array([[1],[1,2]])
      4     return x
      5

VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray

该错误给出了一个回溯,告诉我警告是在哪里发出的。

可能有改进警告过滤器以仅捕获此警告过滤器而不捕获同一类别的其他方法的方法。我没怎么用过这个机制。

阅读 np.warnings.filterwarnings 文档了解更多详情。

原文由 hpaulj 发布,翻译遵循 CC BY-SA 4.0 许可协议

b2 = np.array(
    [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17, 18]],
    dtype=object,
)

参考上面的例子将清除警告。您必须指定 dtype=object

原文由 Am_official 发布,翻译遵循 CC BY-SA 4.0 许可协议