[英]numpy.multiply can have at most 3 arguments (operands), is there any way to do more than 3?
通過以下示例,我可以確認乘法最多只能使用3個參數:
import numpy as np
w = np.asarray([2, 4, 6])
x = np.asarray([1, 2, 3])
y = np.asarray([3, 1, 2])
z = np.asarray([10, 10, 10])
np.multiply(w, x, y) # works
np.multiply(w, x, y, z) #failed
這是錯誤消息:
ValueError Traceback (most recent call last)
<ipython-input-14-9538812eb3b4> in <module>()
----> 1 np.multiply(w, x, y, z)
ValueError: invalid number of arguments
有什么方法可以實現超過3個參數的乘法運算? 我不介意使用其他Python庫。
您可以使用np.prod
來計算給定軸上的數組元素的乘積 ,這里是(axis = 0),即按元素乘以行:
np.prod([w, x, y], axis=0)
# array([ 6, 8, 36])
np.prod([w, x, y, z], axis=0)
# array([ 60, 80, 360])
其實multiply
需要兩個數組。 這是一個二進制操作。 第三個是可選的out
。 但是作為ufunc
它具有一個reduce
方法,該方法帶有一個列表:
In [234]: x=np.arange(4)
In [235]: np.multiply.reduce([x,x,x,x])
Out[235]: array([ 0, 1, 16, 81])
In [236]: x*x*x*x
Out[236]: array([ 0, 1, 16, 81])
In [237]: np.prod([x,x,x,x],axis=0)
Out[237]: array([ 0, 1, 16, 81])
np.prod
可以執行相同的操作,但請注意axis
參數。
ufunc
更有趣-累積:
In [240]: np.multiply.accumulate([x,x,x,x])
Out[240]:
array([[ 0, 1, 2, 3],
[ 0, 1, 4, 9],
[ 0, 1, 8, 27],
[ 0, 1, 16, 81]], dtype=int32)
In [241]: np.cumprod([x,x,x,x],axis=0)
Out[241]:
array([[ 0, 1, 2, 3],
[ 0, 1, 4, 9],
[ 0, 1, 8, 27],
[ 0, 1, 16, 81]], dtype=int32)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.