带有重叠切片的NumPy就地操作 [英] NumPy in-place operations with overlapping slices

查看:157
本文介绍了带有重叠切片的NumPy就地操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑此异地操作:

>>> b = numpy.asarray([1, 2, 3])
>>> b[1:] = b[1:] - b[:-1]
>>> b
array([1, 1, 1])

现在考虑就地操作:

>>> a = numpy.asarray([1, 2, 3])
>>> a[1:] -= a[:-1]
>>> a
array([1, 1, 2])

他们给出了不同的结果,这是我所没想到的.

They give different results, which I did not expect.

我会假设NumPy会按照正确的顺序(向后)进行减法运算,这样它们就可以得出与原位减法运算等效的结果.

I would have assumed NumPy would have done the subtraction in the correct order (backward) so that they would give equivalent results to the out-of-place subtraction.

我的问题是:这是NumPy的预期行为,还是错误,或者结果不确定?

My question is: is this intended behavior on NumPy's part, or is it a bug, or is the result undefined?

推荐答案

此行为以前未定义,但

This behavior was previously undefined, but since NumPy 1.13.0, operations with overlapping input and output now behave as if inputs were copied first. Quoting the release notes:

由于数据依赖性问题,ufunc输入和输出操作数与内存重叠的操作在以前的NumPy版本中产生了不确定的结果.在NumPy 1.13.0中,现在将此类操作的结果定义为与没有内存重叠的等效操作相同.

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.

受影响的操作现在可以临时复制,以消除数据依赖性.由于检测这些情况在计算上很昂贵,因此使用了一种启发式方法,在极少数情况下可能会导致不必要的临时副本.对于数据依赖关系足够简单以进行启发式分析的操作,即使阵列重叠也不会创建临时副本,即使可以推断出这些副本也是不必要的.例如,np.add(a, b, out=a)将不涉及副本.

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. As an example,np.add(a, b, out=a) will not involve copies.

这是GitHub上的相关问题.

这篇关于带有重叠切片的NumPy就地操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆