[英]How to multiply a numpy tuple array by scalar array
我有一個形狀為(N,2)的 numpy 數組 A 和一個形狀為(N)的 numpy 數組 S。
如何將 arrays 相乘? 目前我正在使用這段代碼:
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]])
因此使用python
; 顯式比隱式更直接。
我能想到:
product = A * numpy.tile(S, (2,1)).T
更快的解決方案可能是:
product = [d * S for d in A.T]
雖然這不會讓你得到一個 numpy 數組作為 output,它是轉置的。 所以要得到一個類似的 numpy 數組(注意這比第一種解決方案慢):
product = numpy.array([d * S for d in A.T]).T
可能還有十幾個其他有效的解決方案,包括比這些更好的解決方案......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.