gpt4 book ai didi

python - 使用 == 比较 numpy 数组的规则是什么?

转载 作者:太空狗 更新时间:2023-10-29 21:59:10 24 4
gpt4 key购买 nike

例如,试图理解这些结果:

>>> x
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> (x == np.array([[1],[2]])).astype(np.float32)
array([[ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 1., 0., 0., 0., 0., 0., 0., 0.]], dtype=float32)
>>> (x == np.array([1,2]))
False
>>> (x == np.array([[1]])).astype(np.float32)
array([[ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.]], dtype=float32)
>>> (x == np.array([1])).astype(np.float32)
array([ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.], dtype=float32)

>>> (x == np.array([[1,3],[2]]))
False
>>>

这是怎么回事?在 [1] 的情况下,它将 1 与 x 的每个元素进行比较,并将结果聚合到一个数组中。在 [[1]] 的情况下,同样的事情。只需在 repl 上进行试验,就可以很容易地弄清楚特定阵列形状会发生什么。但是,双方都可以具有任意形状的基本规则是什么?

最佳答案

NumPy 在比较之前尝试将两个数组广播到兼容的形状。如果广播失败,当前返回 False。 In the future ,

The equality operator == will in the future raise errors like np.equal if broadcasting or element comparisons, etc. fails.

否则,返回一个由逐个元素比较产生的 bool 数组。例如,由于 xnp.array([1]) 是可广播的,因此返回一个形状为 (10,) 的数组:

In [49]: np.broadcast(x, np.array([1])).shape
Out[49]: (10,)

由于 xnp.array([[1,3],[2]]) 不可广播,返回 False通过 x == np.array([[1,3],[2]])

In [50]: np.broadcast(x, np.array([[1,3],[2]])).shape
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-50-56e4868cd7f7> in <module>()
----> 1 np.broadcast(x, np.array([[1,3],[2]])).shape

ValueError: shape mismatch: objects cannot be broadcast to a single shape

关于python - 使用 == 比较 numpy 数组的规则是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50007232/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com