python - 返回数组的函数的 numpy.vectorize
问题描述
我正在尝试对具有 2 个输入并输出 np.array 形状 =(4,) 的函数进行矢量化。该函数如下所示:
def f(a, b):
return np.array([a+b, a-b, a, b])
我能够使用签名参数对函数进行矢量化,但是只有在我使用以下excluded
参数排除其中一个参数时它才有效np.vectorize
:
这有效:
vec = np.vectorize(f, signature='()->(n)', excluded=[1])
x = np.arange(5)
y = 3
vec(x, y)
>> output:
array([[ 3, -3, 0, 3],
[ 4, -2, 1, 3],
[ 5, -1, 2, 3],
[ 6, 0, 3, 3],
[ 7, 1, 4, 3]])
但是,如果我拿出excluded
论点,事情就不会按计划进行。
这不起作用:
vec = np.vectorize(f, signature='()->(n)')
x = np.arange(5)
y = 3
vec(x, y)
>> Error:
TypeError: wrong number of positional arguments: expected 1, got 2
如何使矢量化函数能够接收一个(或两个)输入参数中的一个(或两个)输入值的数组/列表?
预期的输出将是一个vec
函数,该函数可以为任一输入参数使用多个输入调用它。
解决方案
In [237]: f1 = np.vectorize(f, signature='(),()->(n)')
In [238]: f1(np.arange(5),3)
Out[238]:
array([[ 3, -3, 0, 3],
[ 4, -2, 1, 3],
[ 5, -1, 2, 3],
[ 6, 0, 3, 3],
[ 7, 1, 4, 3]])
In [241]: f1(np.arange(5),np.ones((4,5))).shape
Out[241]: (4, 5, 4)
In [242]: f1(np.arange(5),np.ones((1,5))).shape
Out[242]: (1, 5, 4)
frompyfunc
返回一个对象 dtype 数组:
In [336]: f2 = np.frompyfunc(f,2,1)
In [337]: f2(np.arange(5), 3)
Out[337]:
array([array([ 3, -3, 0, 3]), array([ 4, -2, 1, 3]),
array([ 5, -1, 2, 3]), array([6, 0, 3, 3]), array([7, 1, 4, 3])],
dtype=object)
In [338]: _.shape
Out[338]: (5,)
np.vectorize
, without the signature
, uses frompyfunc
, but adds its own dtype
conversion.
In [340]: f1(np.arange(5), np.arange(3))
ValueError: shape mismatch: objects cannot be broadcast to a single shape
This fails for the same reason the following addition fails:
In [341]: np.arange(5)+np.arange(3)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-341-fb1c4f4372da> in <module>
----> 1 np.arange(5)+np.arange(3)
ValueError: operands could not be broadcast together with shapes (5,) (3,)
To get a (5,3) result we need to make the first argument (5,1) shape:
In [342]: np.arange(5)[:,None]+np.arange(3)
Out[342]:
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4],
[3, 4, 5],
[4, 5, 6]])
推荐阅读
- c++ - Qt Pushbutton 必须在延迟后处理信号
- syntax - 了解在 rust 中使用 '*' 取消引用
- sql - 将 Blueprism 连接到数据库的问题
- android - Ionic cordova-plugin-camera 未在 Android 上打开图库
- symfony - Easy Admin - 在显示操作中显示完整的国家/地区名称
- python - 如何在 Python 中表示枚举
- jquery - 如何在toggledropdown nav上显示列表除以5?
- kotlin - 在 TornadoFX 中使用工作区时如何使用范围?
- kubernetes - 获取已部署镜像 helm/kubernetes 的值
- php - Symfony 和 Doctrine 的语法错误或访问冲突