输出之间的差异=。。。NumPy中的参数和直接重分配

2024-04-25 22:29:21 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的两个np.dot对于正方形数组x会给出相同的结果吗?你知道吗

import numpy as np
x = np.arange(4 * 4).reshape(4, 4)
np.dot(x, x.T, out=x)  # method 1
x[:] = np.dot(x, x.T)  # method 2

谢谢。你知道吗

我为什么问:

x += x.Tx += x.T.copy()不同

我不知道你的内心np.dot公司工作。 做np.dot公司同样地,将out参数视为一个视图? 如果out是要相乘的矩阵之一,可以吗?你知道吗

我使用的numpy来自anaconda,它使用mkl作为后端。你知道吗


Tags: importnumpy参数asnp公司数组out
3条回答

是的,两种方法产生相同的数组。你知道吗

import numpy as np

def method_1():
    x = np.arange(4 * 4).reshape(4, 4)
    np.dot(x, x.T, out=x)
    return x

def method_2():
    x = np.arange(4 * 4).reshape(4, 4)
    x[:] = np.dot(x, x.T)
    return x

array_1 = method_1()
array_2 = method_2()

print(np.array_equal(array_1, array_2))

给出输出:

True

我安装了一个旧版本的numpy(1.11.0),其中方法1产生了一些奇怪的输出。我知道这不是预期的行为,并且在以后的版本中得到了修复;但为了防止这种情况发生在其他人身上:

Python 2.7.12 (default, Dec  4 2017, 14:50:18) 
[GCC 5.4.0 20160609] on linux2
>>> import numpy as np
>>> x = np.arange(4 * 4).reshape(4, 4)
>>> np.dot(x, x.T, out=x)
array([[                  14,                   94,                 1011,
                       15589],
       [              115715,          13389961335,         120510577872,
               1861218976248],
       [              182547,       21820147595568,  1728119013671256390,
         5747205779608970957],
       [              249379,       29808359122268,  7151350849816304816,
        -3559891853923251270]])
>>> np.version.version
'1.11.0'

据我所知,至少从numpy1.14.1开始,方法#1给出了预期的输出;就像方法#2对两个版本所做的那样。你知道吗

是的,它们是相同的,但从性能角度来看,我看到了整数数组的有趣结果:

import perfplot

def f1(x):
    x = x.copy()
    np.dot(x, x.T, out=x)
    return x

def f2(x):
    x = x.copy()
    x[:] = np.dot(x, x.T)
    return x    

perfplot.show(
    setup=lambda n: np.arange(n * n).reshape(n, n),
    kernels=[f1, f2],
    labels=['out=...', 're-assignment'],
    n_range=[2**k for k in range(0, 9)],
    xlabel='N',
    equality_check=np.allclose
)

enter image description here

我用^{}来生成绘图计时。你知道吗


对于浮点数组,这是完全没有区别的。你知道吗

perfplot.show(
    setup=lambda n: np.arange(n * n).reshape(n, n).astype(float),
    kernels=[f1, f2],
    labels=['out=...', 're-assignment'],
    n_range=[2**k for k in range(0, 9)],
    xlabel='N',
    equality_check=np.allclose
)

enter image description here

相关问题 更多 >