gpt4 book ai didi

python - 奇怪的行为 bool 就地操作

转载 作者:太空宇宙 更新时间:2023-11-03 14:43:22 26 4
gpt4 key购买 nike

我有一个 bool 数组,我想做一个简单的单元素二进制膨胀,即将所有元素设置为 True,所有元素紧邻其他 True 元素。

arr=np.array([0,0,1,0,0,0,1,0,0], dtype=bool)
# array([False, False, True, False, False, False, True, False, False], dtype=bool)
# set elements before True to also True
arr[:-1] |= arr[1:]; arr
array([False, True, True, False, False, True, True, False, False], dtype=bool)

这工作得很好。问题是当我想将 True 之后的元素也设置为 True

arr[1:] |= arr[:-1]; arr
array([False, True, True, True, True, True, True, True, True], dtype=bool)

这个结果是错误的。有趣的是,当没有就地完成时,最后一个操作工作得很好:

arr[1:] = arr[1:] | arr[:-1]; arr
array([False, True, True, True, False, True, True, True, False], dtype=bool)

我无法确定像 &| 这样的 bool 运算符是否支持就地赋值。如果他们这样做,为什么 arr[1:] |= arr[:-1] 会产生错误的结果?

最佳答案

这种切片分配的结果在 numpy<1.13.0 中未定义/错误.请参阅发行说明中的​​提及 here .

Operations where ufunc input and output operands have memory overlap produced undefined results in previous NumPy versions, due to data dependency issues. In NumPy 1.13.0, results from such operations are now defined to be the same as for equivalent operations where there is no memory overlap.

升级您的 numpy 版本以获得“正确”的结果。

请注意,二进制膨胀是直接在 scipy 中实现的:

>>> arr
array([False, False, True, False, False, False, True, False, False], dtype=bool)
>>> from scipy.ndimage.morphology import binary_dilation
>>> binary_dilation(arr)
array([False, True, True, True, False, True, True, True, False], dtype=bool)

关于python - 奇怪的行为 bool 就地操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51501758/

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