在函数返回矢量使用numpy的矢量
numpy.vectorize
需要一个函数f:A-> B,并把它变成G:一[] - >乙:[]
numpy.vectorize
takes a function f:a->b and turns it into g:a[]->b[].
这工作得很好,当 A
和 B
是标量,但我想不出理由,为什么它不会用b工作作为 ndarray
或列表,即F:A-> b []和G:一[] - >乙:[] []
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,)
所以这个数组是pretty无用。我知道我可以把它转换这样做的:
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)
但既没有效率也没有Python的。可以在任何你们的找到一个更清洁的方式做到这一点?
but that is neither efficient nor pythonic. Can any of you guys find a cleaner way to do this?
在此先感谢!
np.vectorize
仅仅是一个方便的功能。实际上它并不使code跑得更快。如果不方便使用 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.