且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

转让numpy数据的所有权

更新时间:2022-04-01 05:11:06

这不是一个令人满意的答案,但是它也不适合用作注释...您可以使用ufunc来解决数据的拥有问题. out参数.一个愚蠢的例子:

It is hardly a satisfactory answer, but it doesn't fit into a comment either... You can work around the owning of the data by using the ufunc's out parameter. A silly example:

>>> a = Foo((5,))
>>> b = Foo((5,))
>>> c = a + b # BAD
True PREPARE <type 'numpy.ndarray'>
False WRAP <class '__main__.Foo'>
>>> c.flags.owndata
False

>>> c = Foo((5,))
>>> c[:] = a + b # BETTER
True PREPARE <type 'numpy.ndarray'>
False WRAP <class '__main__.Foo'>
>>> c.flags.owndata
True

>>> np.add(a, b, out=c) # BEST
True PREPARE <class '__main__.Foo'>
True WRAP <class '__main__.Foo'>
Foo([  1.37754085e-38,   1.68450356e-20,   6.91042737e-37,
         1.74735556e-04,   1.48018885e+29], dtype=float32)
>>> c.flags.owndata
True

我认为上面的输出与c[:] = a + b一致,因为它拥有数据,但以将其从临时数组复制到c中为代价.但是,当您使用out参数时,应该不会发生这种情况.

I think that the output above is consistent with c[:] = a + b getting to own the data at the expense of copying it into c from a temporary array. But that shouldn't be happening when you use the out parameter.

由于您已经担心数学表达式中的中间存储,因此微管理如何处理它可能不是一件坏事.也就是说,替换

Since you were already worried about intermediate storage in your mathematical expressions, it may not be such a bad thing to micro-manage how it is handled. That is, replacing

g = a + b + np.sqrt(d*d + e*e + f*f)

使用

g = foo_like(d) # you'll need to write this function!
np.multiply(d, d, out=g)
g += e * e
g += f * f
np.sqrt(g, out=g)
g += b
g += a

可以为您节省一些中间存储器,并且它可以让您拥有自己的数据.它确实将可读性计数"的口号抛到了窗外,但是...

may save you some intermediate memory, and it lets you own your data. It does throw the "readability counts" mantra out the window, but...