我有一个形状为(N,2)的numpy数组a和形状为(N)的numpy数组S。
如何将两个数组相乘?目前我正在使用这个代码:
tupleS = numpy.zeros( (N , 2) )
tupleS[:,0] = S
tupleS[:,1] = S
product = A * tupleS
我是一个python初学者。有更好的方法吗?
Numpy使用行为主顺序,因此必须显式地创建一个列。如:
>> A = numpy.array(range(10)).reshape(5, 2)
>>> B = numpy.array(range(5))
>>> B
array([0, 1, 2, 3, 4])
>>> A * B
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: shape mismatch: objects cannot be broadcast to a single shape
>>> B = B.reshape(5, 1)
>>> B
array([[0],
[1],
[2],
[3],
[4]])
>>> A * B
array([[ 0, 0],
[ 2, 3],
[ 8, 10],
[18, 21],
[32, 36]])
本质上与@senderle的答案相同,但不需要对s进行就地操作。您可以通过添加索引None
的轴的方式获得数组的切片,并将它们相乘:A * S[:,None]
。
>>> S = np.arange(5)
>>> S
array([0, 1, 2, 3, 4])
>>> A = np.arange(10).reshape((5,2))
>>> A
array([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])
>>> S[:,None]
array([[0],
[1],
[2],
[3],
[4]])
>>> A * S[:,None]
array([[ 0, 0],
[ 2, 3],
[ 8, 10],
[18, 21],
[32, 36]])
你试过了吗:
product = A * S
虽然你的问题标题有点用词不当,但我认为你遇到的问题主要与numpy
广播规则有关。因此,下面的代码将不起作用(正如您已经观察到的):
In []: N= 5
In []: A= rand(N, 2)
In []: A.shape
Out[]: (5, 2)
In []: S= rand(N)
In []: S.shape
Out[]: (5,)
In []: A* S
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (5,2) (5)
然而,现在一种使S
兼容广播规则(A* S
的元素积)的简单方法是扩展它的维数,如:
In []: A* S[:, None]
Out[]:
array([[ 0.54216549, 0.04964989],
[ 0.41850647, 0.4197221 ],
[ 0.03790031, 0.76744563],
[ 0.29381325, 0.53480765],
[ 0.0646535 , 0.07367852]])
但是这只是expand_dims的语法糖,就像:
In []: expand_dims(S, 1).shape
Out[]: (5, 1)
无论如何,我个人更喜欢这个简单的无麻烦的方法:
In []: S= rand(N, 1)
In []: S.shape
Out[]: (5, 1)
In []: A* S
Out[]:
array([[ 0.40421854, 0.03701712],
[ 0.63891595, 0.64077179],
[ 0.03117081, 0.63117954],
[ 0.24695035, 0.44950641],
[ 0.14191946, 0.16173008]])
so with python
;
我可以想到:
product = A * numpy.tile(S, (2,1)).T
一个更快的解决方案可能是:
product = [d * S for d in A.T]
虽然这不会让你得到一个numpy数组作为输出,而且它是转置的。因此,要获得类似的numpy数组(注意,这比第一个解决方案要慢):
product = numpy.array([d * S for d in A.T]).T
可能有一打其他有效的解决方案,包括比这些更好的…