【问题标题】:The truth value of an array with more than one element is ambiguous. numpy error具有多个元素的数组的真值是不明确的。麻木的错误
【发布时间】:2019-12-07 16:50:15
【问题描述】:

具有多个元素的数组的真值是不明确的。使用 a.any() 或 a.all()

我收到此代码的上述错误。几个月前我没有收到这种错误。但我现在明白了。我该如何解决这个问题?

t = np.linspace(np.zeros((2, 2)), np.ones((2, 2)), 20)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-19-187bbe847597> in <module>
----> 1 t = np.linspace(np.zeros((2, 2)), np.ones((2, 2)), 20)

~\Anaconda3\lib\site-packages\numpy\core\function_base.py in linspace(start, stop, num, endpoint, retstep, dtype)
    122     if num > 1:
    123         step = delta / div
--> 124         if step == 0:
    125             # Special handling for denormal numbers, gh-5437
    126             y /= div

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

【问题讨论】:

  • 你能显示完整的错误跟踪吗?
  • 您使用的是哪个版本的numpy?试试np.version.version
  • 当我在我的机器(python 3.7.3 和 numpy 1.16.4)上执行您的代码示例时,我没有收到任何错误。你用的是哪个版本的 python 和 numpy?
  • 我可以在numpy 1.16 之前的版本中复制此错误。此后,错误跟踪中的该代码将不存在。在此之前,不支持对 linspace 的输入。
  • 我正在使用'1.14.5'

标签: python numpy


【解决方案1】:

我可以在 1.16 之前的 numpy 版本中复制此错误。在此之前,np.linspace 不接受 ndarraystopstart 输入。

@JHY 确认当前版本是 1.14.5。尝试更新numpy

【讨论】:

  • 问题解决了!非常感谢!
【解决方案2】:

仅仅是因为 np.zeros((2,2))np.ones((2,2)) 创建了具有 4 个值的数组,而您正在尝试使用 20 样本创建数组。

t = np.linspace(np.zeros((2, 2)), np.ones((2, 2)), 1)

创建没有问题,只是因为数组的长度。

结果:

array([[0., 0.], [0., 0.]])

【讨论】:

  • 您所做的只是通过使step = NaN 短路错误消息。没有任何情况下您实际上想要np.linspace(x, y, 1)。错误消息来自使用 linspace 的功能,而该功能在之前版本中的 numpy 1.16 之前不存在。
  • 我确实需要它来处理大于 1 的数字。在我不知道为什么现在不行之前它曾经可以工作
【解决方案3】:

更新你的 numpy。

适用于 python 2

pip install numpy --upgrade --user

表也需要更新

pip install tables --upgrade

适用于 python 3

pip3 install numpy --upgrade --user

类似地,对于 python 3

pip3 install tables --upgrade

为了在更新它们后完成 numpy 的工作,您需要将表更新为。 之后运行您的代码,错误将被删除。

【讨论】:

    猜你喜欢
    • 2015-01-06
    • 2019-08-21
    • 1970-01-01
    • 2019-03-19
    • 2020-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多