Numpy 将输入数组作为 `out` 参数传递给 ufunc

Numpy passing input array as `out` argument to ufunc

如果类型正确,将输入数组作为可选输出参数提供给 numpy 中的 ufunc 通常是否安全?例如,我已验证以下内容有效:

>>> import numpy as np
>>> arr = np.array([1.2, 3.4, 4.5])
>>> np.floor(arr, arr)
array([ 1.,  3.,  4.])

数组类型必须与输出兼容或相同(numpy.floor() 是浮点数),否则会发生这种情况:

>>> arr2 = np.array([1, 3, 4], dtype = np.uint8)
>>> np.floor(arr2, arr2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ufunc 'floor' output (typecode 'e') could not be coerced to provided output parameter (typecode 'B') according to the casting rule ''same_kind''

那么如果数组的类型正确,就地应用 ufunc 通常安全吗?还是 floor() 是特例?文档没有说清楚,以下两个与问题有切线关系的线程也没有说清楚:

  1. Numpy modify array in place?
  2. Numpy Ceil and Floor "out" Argument

编辑:

作为一阶猜测,根据 http://docs.scipy.org/doc/numpy/user/c-info.ufunc-tutorial.html 上的教程,我认为它通常是安全的,但并不总是安全的。在计算期间使用输出数组作为中间结果的临时保存器似乎没有任何限制。虽然像 floor()ciel() 这样的东西可能不需要临时存储,但更复杂的函数可能需要。话虽这么说,整个现有的库都可以考虑到这一点。

numpy函数的out参数是写入结果的数组。使用 out 的主要优点是避免在不需要的地方分配新内存。

将函数的输出写入与输入相同的数组是否安全?没有通用的答案,这取决于功能在做什么。

两个例子

这里有两个类 ufunc 函数的例子:

In [1]: def plus_one(x, out=None):
   ...:     if out is None:
   ...:         out = np.zeros_like(x)
   ...: 
   ...:     for i in range(x.size):
   ...:         out[i] = x[i] + 1
   ...:     return out
   ...: 

In [2]: x = np.arange(5)

In [3]: x
Out[3]: array([0, 1, 2, 3, 4])

In [4]: y = plus_one(x)

In [5]: y
Out[5]: array([1, 2, 3, 4, 5])

In [6]: z = plus_one(x, x)

In [7]: z
Out[7]: array([1, 2, 3, 4, 5])

函数shift_one:

In [11]: def shift_one(x, out=None):
    ...:     if out is None:
    ...:         out = np.zeros_like(x)
    ...: 
    ...:     n = x.size
    ...:     for i in range(n):
    ...:         out[(i+1) % n] = x[i]
    ...:     return out
    ...: 

In [12]: x = np.arange(5)

In [13]: x
Out[13]: array([0, 1, 2, 3, 4])

In [14]: y = shift_one(x)

In [15]: y
Out[15]: array([4, 0, 1, 2, 3])

In [16]: z = shift_one(x, x)

In [17]: z
Out[17]: array([0, 0, 0, 0, 0])

函数plus_one没有问题:当参数x和out为同一个数组时,得到预期的结果。但是当参数 x 和 out 是同一个数组时,函数 shift_one 给出了一个令人惊讶的结果,因为数组

讨论

对于形式为out[i] := some_operation(x[i])的函数,如上面的plus_one,还有函数floor、ceil、sin、cos、tan、log、conj等,据我所知使用参数 out 将结果写入输入是 安全的

对于采用 ``out[i] := some_operation(x[i], y[i ]) 比如numpy函数加、乘、减。

其他功能,视具体情况而定。如下图所示,矩阵乘法是不安全的:

In [18]: a = np.arange(4).reshape((2,2))

In [19]: a
Out[19]: 
array([[0, 1],
       [2, 3]])

In [20]: b = (np.arange(4) % 2).reshape((2,2))

In [21]: b
Out[21]: 
array([[0, 1],
       [0, 1]], dtype=int32)

In [22]: c = np.dot(a, b)

In [23]: c
Out[23]: 
array([[0, 1],
       [0, 5]])

In [24]: d = np.dot(a, b, out=a)

In [25]: d
Out[25]: 
array([[0, 1],
       [0, 3]])

最后评论:如果实现是多线程的,不安全函数的结果甚至可能是不确定的,因为它取决于处理数组元素的顺序。