out 参数

numpy dot 函数有一个可选参数 out = None。此参数允许你指定要将结果写入的数组。此数组的形状和类型必须与返回的数组完全相同,否则将引发异常。

>>> I = np.eye(2)
>>> I
array([[ 1.,  0.],
       [ 0.,  1.]])
>>> result = np.zeros((2,2))
>>> result
array([[ 0.,  0.],
       [ 0.,  0.]])
>>> np.dot(I, I, out=result)
array([[ 1.,  0.],
       [ 0.,  1.]])
>>> result
array([[ 1.,  0.],
       [ 0.,  1.]])

让我们尝试将结果的 dtype 更改为 int。

>>> np.dot(I, I, out=result)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: output array is not acceptable (must have the right type, nr dimensions, and be a C-Array)

如果我们尝试使用不同的底层内存顺序,比如 Fortran 风格(因此列是连续的而不是行),也会产生错误。

>>> result = np.zeros((2,2), order='F')
>>> np.dot(I, I, out=result)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: output array is not acceptable (must have the right type, nr dimensions, and be a C-Array)