2011-11-29 99 views
2

在我看来,有numpy的功能multiply()的两个版本:乘()在numpy的蟒蛇

  1. c = multiply(a, b)
  2. multiply(a, b, c)

我的问题是双重的:

  1. 这两个版本有什么区别?
  2. 我需要使用dot()函数,并且我知道c = dot(a, b)的作品。但是dot(a, b, c)没有。

回答

6
  1. multiply()的两个版本之间的差别:

    c = multilpy(a, b) 
    

    乘以阵列ab逐元素,创建一个新阵列作为结果。名称c绑定到这个新的数组。如果c之前指向另一个数组,则这可能会或可能不会触发之前指向的数组c的垃圾回收,具体取决于对此数组的其他引用是否仍然存在。

    multilpy(a, b, c) 
    

    乘以阵列ab逐元素,并将结果存储在现有阵列c(它必须具有适当的尺寸)英寸没有创建新的数组对象,而是改变了现有的数组。除了不同的语义之外,如果c已经指向适当类型和维度的数组,则此变体更快,因为没有分配新数组。这种变体还可以减少内存使用量。其实不是问题。是的,dot()没有三参数表单。它不是一个ufunc,也不遵循通常的广播规则 - 它不能因为点积的语义。

    编辑:从NumPy 1.6开始,dot()实际上确实有一个三参数形式,其语义与上述相似。 (对于它的价值,它仍然不是一个ufunc。)

+0

非常感谢。 –

1

目前所有的标准numpy的ufuncs的只有一个版本 - 使用点作为一个例子

Type:   builtin_function_or_method 
Base Class:  <type 'builtin_function_or_method'> 
String Form: <built-in function dot> 
Namespace:  Interactive 
Docstring: 
    dot(a, b, out=None) 

Dot product of two arrays. 

For 2-D arrays it is equivalent to matrix multiplication, and for 1-D 
arrays to inner product of vectors (without complex conjugation). For 
N dimensions it is a sum product over the last axis of `a` and 
the second-to-last of `b`:: 

    dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m]) 

Parameters 
---------- 
a : array_like 
    First argument. 
b : array_like 
    Second argument. 
out : ndarray, optional 
    Output argument. This must have the exact kind that would be returned 
    if it was not used. In particular, it must have the right type, must be 
    C-contiguous, and its dtype must be the dtype that would be returned 
    for `dot(a,b)`. This is a performance feature. Therefore, if these 
    conditions are not met, an exception is raised, instead of attempting 
    to be flexible. 

如果您提供正确的dtype和存储顺序的可选第三个agrument,它将工作:

In [78]: a=np.array([1.,2.,3.,4.]) 

In [79]: b=np.diag(a) 

In [80]: c=np.empty_like(a) 

In [81]: np.dot(a,b,c) 
Out[81]: array([ 1., 4., 9., 16.]) 

In [82]: np.dot(a,b) 
Out[82]: array([ 1., 4., 9., 16.])