Using Numpy Vectorize on Functions that Return Vectors

前端 未结 6 1715
生来不讨喜
生来不讨喜 2020-11-29 04:57

numpy.vectorize takes a function f:a->b and turns it into g:a[]->b[].

This works fine when a and b are scalars, but I can\'t t

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 05:51

    You want to vectorize the function

    import numpy as np
    def f(x):
        return x * np.array([1,1,1,1,1], dtype=np.float32)
    

    Assuming that you want to get single np.float32 arrays as result, you have to specify this as otype. In your question you specified however otypes=[np.ndarray] which means you want every element to be an np.ndarray. Thus, you correctly get a result of dtype=object.

    The correct call would be

    np.vectorize(f, signature='()->(n)', otypes=[np.float32])
    

    For such a simple function it is however better to leverage numpy's ufunctions; np.vectorize just loops over it. So in your case just rewrite your function as

    def f(x):
        return np.multiply.outer(x, np.array([1,1,1,1,1], dtype=np.float32))
    

    This is faster and produces less obscure errors (note however, that the results dtype will depend on x if you pass a complex or quad precision number, so will be the result).

提交回复
热议问题