在返回向量的函数上使用 Numpy Vectorize [英] Using Numpy Vectorize on Functions that Return Vectors
问题描述
numpy.vectorize
将函数 f:a->b 转换为 g:a[]->b[].
numpy.vectorize
takes a function f:a->b and turns it into g:a[]->b[].
这在 a
和 b
是标量时工作正常,但我想不出为什么它不能将 b 作为 ndarray
或列表,即 f:a->b[] 和 g:a[]->b[][]
This works fine when a
and b
are scalars, but I can't think of a reason why it wouldn't work with b as an ndarray
or list, i.e. f:a->b[] and g:a[]->b[][]
例如:
import numpy as np
def f(x):
return x * np.array([1,1,1,1,1], dtype=np.float32)
g = np.vectorize(f, otypes=[np.ndarray])
a = np.arange(4)
print(g(a))
这产生:
array([[ 0. 0. 0. 0. 0.],
[ 1. 1. 1. 1. 1.],
[ 2. 2. 2. 2. 2.],
[ 3. 3. 3. 3. 3.]], dtype=object)
好的,这样就给出了正确的值,但给出了错误的 dtype.更糟糕的是:
Ok, so that gives the right values, but the wrong dtype. And even worse:
g(a).shape
产量:
(4,)
所以这个数组几乎没用.我知道我可以转换它:
So this array is pretty much useless. I know I can convert it doing:
np.array(map(list, a), dtype=np.float32)
给我我想要的:
array([[ 0., 0., 0., 0., 0.],
[ 1., 1., 1., 1., 1.],
[ 2., 2., 2., 2., 2.],
[ 3., 3., 3., 3., 3.]], dtype=float32)
但这既不高效也不pythonic.你们中的任何人都可以找到一种更清洁的方法来做到这一点吗?
but that is neither efficient nor pythonic. Can any of you guys find a cleaner way to do this?
提前致谢!
推荐答案
np.vectorize
只是一个方便的函数.它实际上并没有让代码运行得更快.如果使用 np.vectorize
不方便,只需编写自己的函数即可.
np.vectorize
is just a convenience function. It doesn't actually make code run any faster. If it isn't convenient to use np.vectorize
, simply write your own function that works as you wish.
np.vectorize
的目的是将不能感知 numpy 的函数(例如以浮点数作为输入并返回浮点数作为输出)转换为可以操作(并返回)numpy 数组的函数.
The purpose of np.vectorize
is to transform functions which are not numpy-aware (e.g. take floats as input and return floats as output) into functions that can operate on (and return) numpy arrays.
你的函数 f
已经是 numpy 感知的——它在定义中使用了一个 numpy 数组并返回一个 numpy 数组.所以 np.vectorize
不太适合您的用例.
Your function f
is already numpy-aware -- it uses a numpy array in its definition and returns a numpy array. So np.vectorize
is not a good fit for your use case.
因此,解决方案只是滚动您自己的函数 f
,以按照您希望的方式工作.
The solution therefore is just to roll your own function f
that works the way you desire.
这篇关于在返回向量的函数上使用 Numpy Vectorize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!