[英]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.