gpt4 book ai didi

python - 通过滥用 as_strided 在 NumPy 中迭代算法

转载 作者:行者123 更新时间:2023-12-05 03:33:46 25 4
gpt4 key购买 nike

我想知道是否有可能在不使用 for 循环的情况下使用 as_strided 和一些就地编辑内存的操作来编写迭代算法。

例如,如果我想编写一个算法,将数组中的数字替换为其邻居的总和。我想到了这个令人厌恶的东西(是的,它用两个正确的邻居对一个元素求和,但这只是为了得到一个想法):

import numpy as np

a = np.arange(10)
ops = 2
a_view_window = np.lib.stride_tricks.as_strided(a, shape = (ops,a.size - 2, 3), strides=(0,) + 2*a.strides)
a_view = np.lib.stride_tricks.as_strided(a, shape = (ops,a.size - 2), strides=(0,) + a.strides)
np.add.reduce(a_view_window, axis = -1, out=a_view)
print(a)

所以我采用了 10 个数字的数组并创建了这个奇怪的 View ,它在不改变步幅的情况下增加了维度。因此,我的想法是减少它将运行在假的新维度上并覆盖以前的值,因此当它到达下一个主要维度时,它将必须从它覆盖的数据中读取,从而迭代地执行加法。

遗憾的是这不起作用:(

(是的,我知道这是一种糟糕的做事方式,但我很好奇底层的 numpy 东西是如何工作的,以及它是否可以通过这种方式被黑客攻击)

最佳答案

此代码会导致 Numpy 1.13 之前的未定义行为,并且在较新版本中不合时宜工作以避免重叠/别名问题。实际上,您不能假设 Numpy 在输入/输出数组 View 上以给定顺序迭代。事实上,Numpy 经常使用 SIMD 指令来加速代码,有时会告诉编译器 View 之间没有重叠/别名(使用 restrict 关键字)它们可以生成一个更有效的代码。有关更多信息,您可以阅读 doc on ufuncs (和 this issue ):

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.
Operations affected now make temporary copies, as needed to eliminate data dependency. As detecting these cases is computationally expensive, a heuristic is used, which may in rare cases result to needless temporary copies. For operations where the data dependency is simple enough for the heuristic to analyze, temporary copies will not be made even if the arrays overlap, if it can be deduced copies are not necessary.

关于python - 通过滥用 as_strided 在 NumPy 中迭代算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70294788/

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